尊敬的 微信汇率:1円 ≈ 0.046166 元 支付宝汇率:1円 ≈ 0.046257元 [退出登录]
SlideShare a Scribd company logo
1. Program to generate Fibonacci series




   import java.io.*;
   import java.util.*;
   public class Fibonacci
    {
   public static void main(String[] args)
   {
    DataInputStream reader = new DataInputStream((System.in));
      int f1=0,f2=0,f3=1;
   try
   {

      System.out.print("Enter value of n: ");
      String st = reader.readLine();
    int num = Integer.parseInt(st);

       for(int i=1;i<=num;i++)
   {
         System.out.println("tt"+f3+"tnt");
              f1=f2;
              f2=f3;
            f3=f1+f2;
     }
   }
   catch(Exception e)
   {
   System.out.println("wrong input");
   }
   }
   }

2. Program to take two numbers as input from command line interface and display their sum
Coding:
    class Sum
    {
    public void add(int a,int b)
    {
    int c;
    c=a+b;
    System.out.print("tttnnThe sum of two no is = "+c);
    System.out.println("nnn");
    }
    }

    class SMain
    {
    public static void main(String arg[])
    {
    Sum obj1=new Sum();
    int x,y;
    String s1,s2;
    s1=arg[0];
    s2=arg[1];
    x=Integer.parseInt(s1);
    y=Integer.parseInt(s2);
    obj1.add(x,y);
    }
    }




3. Use of array in java
Coding:
class Person
{
String name[];
int age[];
}
class PersonMain
{
public static void main(String arg[])
{


Person obj=new Person();


obj.name=new String[6];
obj.age=new int[6];
obj.name[0]="Neha";
obj.age[0]=19;


obj.name[1]="manpreet";
obj.age[1]=19;


obj.name[2]="rahul";
obj.age[2]=23;


obj.name[3]="yuvraj";
obj.age[3]=12;


obj.name[4]="kombe";
obj.age[4]=19;


obj.name[5]="tony";
obj.age[5]=19;
for(int i=0;i<4;i++)
System.out.println(obj.name[i]);
{
for(int j=0;j<4;j++)
System.out.println(obj.age[j]);
}
}
}




4. Create a class customer having three attributes name, bill and id. Include appropriate
     methods for taking input from customer and displaying its values
Coding: import java.io.DataInputStream;
class Customer
{
public static void main(String arf[])
{
DataInputStream myinput=new DataInputStream(System.in);
String name;
 int bill=0,id=0;
try
{
System.out.println("enter name of customer");
name=myinput.readLine();

System.out.println("enter bill");
bill=Integer.parseInt(myinput.readLine());

System.out.println("enter id");
id=Integer.parseInt(myinput.readLine());
System.out.println("name of customer is"+name);
System.out.println("bill of customer"+bill);
System.out.println("id of customer"+id);
}
catch(Exception e)
{
System.out.println("wrong input error!!!");
}
}
}




5. To show the concept of method overloading
   Coding:

   class Addition//FUNCTION OVERLOADING

   {

   public int add(int a,int b)

   {

   int c=a+b;

   return (c);

   }

   public float add(float a,float b)

   {

   float c=a+b;

   return (c);
}

   public double add(double a,double b)

   {

   double c=a+b;

   return (c);

   }

   }

   class AddMain

   {

   public static void main(String arg[])

   {

   Addition obj=new Addition();

   System.out.println(obj.add(20,30));

   System.out.println(obj.add(100.44f,20.54f));

   System.out.println(obj.add(1380.544,473.56784));

   }

   }




6. To count no. of object created of a class
   class Demo//OBJECT CREATION

   {

   private static int count=0;

   public Demo()
{

   System.out.println("i am from demo");

   count++;

   System.out.println("object created is"+count);

   }

   }

   class DemoMains

   {

   public static void main(String args[])

   {

   Demo obj1=new Demo();

   Demo obj2=new Demo();

   Demo obj3=new Demo();



   }

   }




7. To show concept of multilevel inheritance
   Coding:
   class A
   {
   private int num1,num2,sum;
   public void set(int x,int y)
   {
num1=x;
num2=y;
sum=num1+num2;
}
public int get1()
{
return(sum);
}
}
class B extends A
{
public void display()
{
System.out.println("sum of two numbers is"+get1());
}
}
class C extends B
{
private double sqr;
public void sqrs()
{
sqr=java.lang.Math.sqrt(get1());
System.out.println("square root of sum is"+sqr);
}
}
class ABCMain
{
public static void main(String args[])
{
C obj1=new C();
obj1.set(100,200);
System.out.println("first number is 100");
System.out.println("second number is 200");
obj1.display();
obj1.sqrs();
}
}
8.           To show concept of method overriding
Coding:

class Demo

{

private static int count=0;

public Demo()

{

System.out.println("i am from demo");

count++;

System.out.println("object created is"+count);

}

public String toString()

{

return("method overridding");

}

}

class MethodOverride

{

public static void main(String args[])

{

Demo obj1=new Demo();

Demo obj2=new Demo();

Demo obj3=new Demo();
System.out.println("overriding toString methodnnttoverriden message=: "+obj1.toString());

}

}




    9. Create a class that will at least import two packages and use the method defined in the
       classes of those packages.
       Coding:
       MyApplet.java:
        import java.awt.*;
       import java.applet.*;
       public class MyApplet extends Applet
       {
       public void paint(Graphics g)
       {

       g.drawLine(400,100,100,400);
       }
       }
       Ex1.html:
       <applet code="MyApplet.class"
       height="600"
       width="800"
       >
       </applet>
10. To create thread by extending thread class
    Coding:
    class T1 extends Thread
    {
    public void run()
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("thread 1 created");
    }
    }
    }
    class T2 extends Thread
    {
    public void run()
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("thread 2 created");
    }
    }
    }
    class TMain
    {
    public static void main(String arg[])
    {
    T1 obj1=new T1();
    obj1.start();

   T2 obj2=new T2();
   obj2.start();
   }
   }
11. Create thread by implementing runnable interface
    Coding:
    class T1 implements Runnable
    {
    public void run()
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("thread 1 created");
    }
    }
    }
    class T2 implements Runnable
    {
    public void run()
    {
    for(int i=0;i<5;i++)
    {
    System.out.println("thread 2 created");
    }
    }
    }
    class RMain
    {
    public static void main(String arg[])
    {
    T1 obj1=new T1();
    Thread t1=new Thread(obj1);
    T2 obj2=new T2();
    Thread t2=new Thread(obj2);
    t1.start();
    t2.start();
}
   }




12. To create user defined exception
    class InvalidRollno extends Exception

   {

   String msg;

   public InvalidRollno()

   {

   }

   public InvalidRollno(String m)

   {

   msg=m;

   }

   public String toString()

   {

   return(msg);

   }

   }
class Student

{

private int rollno;

public void setStudent(int r) throws InvalidRollno

{

rollno=r;

if(r<1)

{

throw new InvalidRollno("invalid rollno");

}

}

}

class SMain

{

public static void main(String agf[])

{

Student obj1=new Student();

try

{

obj1.setStudent(-11);

}

catch(InvalidRollno e)

{

System.out.println(e);

}
}

          }




13. Program for showing the concept of sleep method in multithreading.

    public class DelayExample{

    public static void main(String[] args)

{

    System.out.println("Hi");

    for (int i = 0; i < 10; i++)

    {

    System.out.println("Number of itartion = " + i);

    System.out.println("Wait:");

    try

    {
Thread.sleep(4000);

    }

catch (InterruptedException ie)

 {

 System.out.println(ie.getMessage());

}}}




14. Program to demonstrate a basic applet.

import java.awt.*;

import java.applet.*;

/*

<applet code="sim" width=300 height=300>

</applet>

*/

public class sim extends Applet

{

String msg=" ";

public void init()
{

msg+="init()--->";

setBackground(Color.orange);

}

public void start()

{

msg+="start()--->";

setForeground(Color.blue);

}

public void paint(Graphics g)

{

msg+="paint()--->";

g.drawString(msg,200,50);

}}




15. Program for drawing various shapes on applets.

import java.awt.*;

import java.applet.*;

/*
<applet code="Sujith" width=200 height=200>

</applet>

*/

public class Sujith extends Applet

{

public void paint(Graphics g)

{

for(int i=0;i<=250;i++)

{

Color c1=new Color(35-i,55-i,110-i);

g.setColor(c1);

g.drawRect(250+i,250+i,100+i,100+i);

g.drawOval(100+i,100+i,50+i,50+i);

g.drawLine(50+i,20+i,10+i,10+i);

}

}

}
16. Program for filling various objects with colours.

import java.awt.*;

public class GradientPaintExample extends ShapeExample {

private GradientPaint gradient =

new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow,

true);

public void paintComponent(Graphics g)

{

clear(g)

Graphics2D g2d = (Graphics2D)g;

drawGradientCircle(g2d);

}

protected void drawGradientCircle(Graphics2D g2d)
g2d.setPaint(gradient);

g2d.fill(getCircle());

g2d.setPaint(Color.black);

g2d.draw(getCircle());

 }

public static void main(String[] args) {

WindowUtilities.openInJFrame(new GradientPaintExample(),

380, 400);

 }




17. Program of an applet which respond to mouse motion listener interface method.

import javax.swing.*;

import java.awt.Color;
import java.awt.FlowLayout;

import java.awt.Graphics;

import java.awt.Container;

import java.awt.event.*;

public class MovingMessage

{

public static void main (String[] s)

{ HelloJava f = new HelloJava();}

}

class HelloJava extends JFrame implements MouseMotionListener, ActionListener

{

int messageX = 25, messageY = 100;

String theMessage;

JButton theButton;

int colorIndex = 0;

static Color[] someColors = { Color.black, Color.red,Color.green, Color.blue, Color.magenta };

HelloJava()

{

theMessage = "Dragging Message";

setSize(300, 200);

Container contentPane = getContentPane();

contentPane.setLayout(new FlowLayout());

theButton = new JButton("Change Color");

contentPane.add(theButton);

theButton.addActionListener(this);
addMouseMotionListener(this);

setVisible(true);

}

private void changeColor()

{

if (++colorIndex == someColors.length)

colorIndex = 0;

setForeground(currentColor());

repaint();

}

private Color currentColor()

{ return someColors[colorIndex]; }

public void paint(Graphics g)

{

super.paint(g);

g.drawString(theMessage, messageX, messageY);

}

public void mouseDragged(MouseEvent e)

{

messageX = e.getX();

messageY = e.getY();

repaint();

}

public void mouseMoved(MouseEvent e) { }

public void actionPerformed(ActionEvent e)
{

if (e.getSource() == theButton)

changeColor();

}

}




18. Program of an applet which uses the various methods defined in the key listener
interface.

import java.awt.*;

import java.awt.event.*;

public class KeyListenerTester extends Frame implements KeyListener{

TextField t1;

Label l1;

public KeyListenerTester(String s ) {

super(s);

Panel p =new Panel();

l1 = new Label ("Key Listener!" ) ;

p.add(l1);

add(p);

addKeyListener ( this ) ;
setSize ( 200,100 );

setVisible(true);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent e){

System.exit(0);

}

});

}

public void keyTyped ( KeyEvent e ){

l1.setText("Key Typed");

}

public void keyPressed ( KeyEvent e){

l1.setText ( "Key Pressed" ) ;

}

public void keyReleased ( KeyEvent e ){

l1.setText( "Key Released" ) ;

}

public static void main (String[]args ){

new KeyListenerTester ( "Key Listener Tester" ) ;

}

}
19. program to change the background colour of applet by clicking on command button.

import java.applet.Applet;

import java.awt.Button;

import java.awt.Color;

public class ChangeButtonBackgroundExample extends Applet{

public void init()

{

Button button1 = new Button("Button 1");

Button button2 = new Button("Button 2");

button1.setBackground(Color.red);

button2.setBackground(Color.green);

add(button1);

add(button2);

}

}
20. Program of an applet that will demonstrate a basic calculator.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.event.*;

class Calculator extends JFrame {

private final Font BIGGER_FONT = new Font("monspaced",

Font.PLAIN, 20);

private JTextField textfield;

private boolean number = true;

private String equalOp = "=";

private CalculatorOp op = new CalculatorOp();

public Calculator() {

textfield = new JTextField("0", 12);

textfield.setHorizontalAlignment(JTextField.RIGHT);
textfield.setFont(BIGGER_FONT);

ActionListener numberListener = new NumberListener();

String buttonOrder = "1234567890 ";

JPanel buttonPanel = new JPanel();

buttonPanel.setLayout(new GridLayout(4, 4, 4, 4));

for (int i = 0; i < buttonOrder.length(); i++) {

String key = buttonOrder.substring(i, i+1);

if (key.equals(" ")) {

buttonPanel.add(new JLabel(""));

} else {

JButton button = new JButton(key);

button.addActionListener(numberListener);

button.setFont(BIGGER_FONT);

buttonPanel.add(button);

}

}

ActionListener operatorListener = new OperatorListener();

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(4, 4, 4, 4));

String[] opOrder = {"+", "-", "*", "/","=","C"};

for (int i = 0; i < opOrder.length; i++) {

JButton button = new JButton(opOrder[i]);

button.addActionListener(operatorListener);

button.setFont(BIGGER_FONT);

panel.add(button);
}

JPanel pan = new JPanel();

pan.setLayout(new BorderLayout(4, 4));

pan.add(textfield, BorderLayout.NORTH );

pan.add(buttonPanel , BorderLayout.CENTER);

pan.add(panel , BorderLayout.EAST );

this.setContentPane(pan);

this.pack();

this.setTitle("Calculator");

this.setResizable(false);

}

private void action() {

number = true;

textfield.setText("0");

equalOp = "=";

op.setTotal("0");

}

class OperatorListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

if (number) {

action();

textfield.setText("0");

} else {

number = true;

String displayText = textfield.getText();
if (equalOp.equals("=")) {

op.setTotal(displayText);

} else if (equalOp.equals("+")) {

op.add(displayText);

} else if (equalOp.equals("-")) {

op.subtract(displayText);

} else if (equalOp.equals("*")) {

op.multiply(displayText);

} else if (equalOp.equals("/")) {

op.divide(displayText);

}

textfield.setText("" + op.getTotalString());

equalOp = e.getActionCommand();

}

}

}

class NumberListener implements ActionListener {

public void actionPerformed(ActionEvent event) {

String digit = event.getActionCommand();

if (number) {

textfield.setText(digit);

number = false;

} else {

textfield.setText(textfield.getText() + digit);

}
}

}

public class CalculatorOp {

private int total;

public CalculatorOp() {

total = 0;

}

public String getTotalString() {

return ""+total;

}

public void setTotal(String n) {

total = convertToNumber(n);

}

public void add(String n) {

total += convertToNumber(n);

}

public void subtract(String n) {

total -= convertToNumber(n);

}

public void multiply(String n) {

total *= convertToNumber(n);

}

public void divide(String n) {

total /= convertToNumber(n);

}
private int convertToNumber(String n) {

return Integer.parseInt(n);

}

}

}




21. Program for showing the use of various method of URL class.

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.net.MalformedURLException;

import java.net.URL;

public class GetURL {

static protected void getURL(String u) {

URL url;

InputStream is;

InputStreamReader isr;

BufferedReader r;
String str;

try {

System.out.println("Reading URL: " + u);

url = new URL(u);

is = url.openStream();

isr = new InputStreamReader(is);

r = new BufferedReader(isr);

do {

str = r.readLine();

if (str != null)

System.out.println(str);

} while (str != null);

} catch (MalformedURLException e) {

System.out.println("Must enter a valid URL");

} catch (IOException e) {

System.out.println("Can not connect");

}

}

static public void main(String args[]) {

if (args.length < 1)

System.out.println("Usage: GetURL ");

else

getURL(args[0]);

}

}
22. Program to print concentric circles

import java.awt.*;

import java.applet.*;

import java.util.*;



public class c_cir extends Applet

{

public void paint(Graphics g)

{

Random rg = new Random();



for (int i=1; i<=3; i++)

{

int r = rg.nextInt(255);

int gr = rg.nextInt(255);

int b = rg.nextInt(255);

Color c = new Color(r,gr,b);

g.setColor(c);
g.fillOval(100+i*5,100+i*5,100-i*10,100-i*10);

}

}

}




23. Program to illustrate the use of methods of vector class

import java.util.*;
class vvect
{
        public static void main(String a[])
        {
Vector a1 = new Vector();

                 int l = a.length;
                 int i;
                 for(i=0;i<l;i++)
                 {
                          a1.addElement(a[i]);
                 }
                 a1.insertElementAt("Vatan",2);
                 int s = a1.size();
                 String r[] = new String[s];
                 a1.copyInto(r);
                 System.out.println("n Different Font Styles:n");
                 for(i=0;i<s;i++)
                 {
                          System.out.println(r[i]);
                 }
       }
}




24. Program for showing the use ‘for’ in each statement.

package loops;

public class Forloops

{

public static void main(string[] args) {

int loopval;
int end_value=11;

for (loopval=0; loopval<end_value;loopval++) {

system.out.printin("loop value="+ loopval);

}

}

}




25. Program for showing a use of jdp programming in java.

import java.lang.*;
import java.sql.*;
class bca
{
public static void main(String arg[]) throws Exception
{
        String stdrollno,stdname,stdclass;
        Connection conn;
Statement stmt;
    ResultSet rs;
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    conn=DriverManager.getConnection("jdbc:odbc:pctedsn","bca","bca");

    stmt=conn.createStatement();
    rs=stmt.executeQuery("select id,stdname,class from try");

    System.out.println("Roll No Student Name Class");

    while(rs.next())
    {

    stdclass = rs.getString(1);
    stdname = rs.getString(2);
    stdrollno = rs.getString(3);

    System.out.println(stdrollno+"      "+stdname+" "+stdclass);

    }

    //stmt.close();
    //rs.close();
}
}

More Related Content

What's hot

Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
Navneet Prakash
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
DJango
DJangoDJango
DJango
Sunil OS
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 
Hibernate
Hibernate Hibernate
Hibernate
Sunil OS
 
C++
C++C++
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Visual Basic(Vb) practical
Visual Basic(Vb) practicalVisual Basic(Vb) practical
Visual Basic(Vb) practical
Rahul juneja
 
Method overloading
Method overloadingMethod overloading
Method overloading
Lovely Professional University
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
Sunil OS
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
Kelley Robinson
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
functions of C++
functions of C++functions of C++
functions of C++
tarandeep_kaur
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
RACHIT_GUPTA
 
JavaScript
JavaScriptJavaScript
JavaScript
Sunil OS
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
Sunil OS
 
Applets
AppletsApplets
Applets
SanthiNivas
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
Infoviaan Technologies
 

What's hot (20)

Java I/O and Object Serialization
Java I/O and Object SerializationJava I/O and Object Serialization
Java I/O and Object Serialization
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
DJango
DJangoDJango
DJango
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Hibernate
Hibernate Hibernate
Hibernate
 
C++
C++C++
C++
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Visual Basic(Vb) practical
Visual Basic(Vb) practicalVisual Basic(Vb) practical
Visual Basic(Vb) practical
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Why The Free Monad isn't Free
Why The Free Monad isn't FreeWhy The Free Monad isn't Free
Why The Free Monad isn't Free
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
functions of C++
functions of C++functions of C++
functions of C++
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Applets
AppletsApplets
Applets
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 

Viewers also liked

Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
Mumbai Academisc
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Java codes
Java codesJava codes
Java codes
Hussain Sherwani
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 
Interview questions(programming)
Interview questions(programming)Interview questions(programming)
Interview questions(programming)
sunilbhaisora1
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questions
Gradeup
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
Programming Homework Help
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questions
Dhivyashree Selvarajtnkpm
 
Bank management system with java
Bank management system with java Bank management system with java
Bank management system with java
Neha Bhagat
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
Gradeup
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritance
jwjablonski
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
Vipul Naik
 
31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentation31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentation
Swaroop Mane
 
Brochure rafael velásquez
Brochure rafael velásquezBrochure rafael velásquez
Brochure rafael velásquez
rafaelhvv
 
Mgceu presentation
Mgceu presentationMgceu presentation
Mgceu presentationOlena Ursu
 
Cushion Butterfield Collection - February 2015
Cushion Butterfield Collection - February 2015Cushion Butterfield Collection - February 2015
Cushion Butterfield Collection - February 2015
Steve Wilkinson
 
Smart practices rev
Smart practices   revSmart practices   rev
Smart practices rev
Olena Ursu
 
Literatura catalana de postguerra
Literatura catalana de postguerraLiteratura catalana de postguerra
Literatura catalana de postguerraIgnacio Martinez
 
Bawse Legacy 2.4
Bawse Legacy 2.4Bawse Legacy 2.4
Bawse Legacy 2.4
ChanPear
 

Viewers also liked (20)

Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Java codes
Java codesJava codes
Java codes
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Interview questions(programming)
Interview questions(programming)Interview questions(programming)
Interview questions(programming)
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questions
 
Bank account in java
Bank account in javaBank account in java
Bank account in java
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questions
 
Bank management system with java
Bank management system with java Bank management system with java
Bank management system with java
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritance
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentation31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentation
 
Brochure rafael velásquez
Brochure rafael velásquezBrochure rafael velásquez
Brochure rafael velásquez
 
Mgceu presentation
Mgceu presentationMgceu presentation
Mgceu presentation
 
Cushion Butterfield Collection - February 2015
Cushion Butterfield Collection - February 2015Cushion Butterfield Collection - February 2015
Cushion Butterfield Collection - February 2015
 
Smart practices rev
Smart practices   revSmart practices   rev
Smart practices rev
 
Literatura catalana de postguerra
Literatura catalana de postguerraLiteratura catalana de postguerra
Literatura catalana de postguerra
 
Bawse Legacy 2.4
Bawse Legacy 2.4Bawse Legacy 2.4
Bawse Legacy 2.4
 

Similar to Java practical

Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
Niraj Bharambe
 
Java practical
Java practicalJava practical
Java practical
william otto
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
Upender Upr
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
Java file
Java fileJava file
Java file
simarsimmygrewal
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
Java oops features
Java oops featuresJava oops features
Java oops features
VigneshManikandan11
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
anupamfootwear
 
Awt
AwtAwt
Thread
ThreadThread
Thread
phanleson
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Ayes Chinmay
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
Fahad Shaikh
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
ROHIT JAISWAR
 
JAVAPGMS.docx
JAVAPGMS.docxJAVAPGMS.docx
JAVAPGMS.docx
Mgm Mallikarjun
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
hanumanthu mothukuru
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
MuhammadTalha436
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
Soumya Behera
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
Vinayak Shedgeri
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
Vinayak Shedgeri
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
ishan0019
 

Similar to Java practical (20)

Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Java practical
Java practicalJava practical
Java practical
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Java file
Java fileJava file
Java file
 
Java file
Java fileJava file
Java file
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Java oops features
Java oops featuresJava oops features
Java oops features
 
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 Problem1 java codeimport java.util.Scanner; Java code to pr.pdf Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
Problem1 java codeimport java.util.Scanner; Java code to pr.pdf
 
Awt
AwtAwt
Awt
 
Thread
ThreadThread
Thread
 
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
Internet and Web Technology (CLASS-16) [Basic Elements of Java Program] | NIC...
 
Advanced Java - Practical File
Advanced Java - Practical FileAdvanced Java - Practical File
Advanced Java - Practical File
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
JAVAPGMS.docx
JAVAPGMS.docxJAVAPGMS.docx
JAVAPGMS.docx
 
Java and j2ee_lab-manual
Java and j2ee_lab-manualJava and j2ee_lab-manual
Java and j2ee_lab-manual
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
54240326 (1)
54240326 (1)54240326 (1)
54240326 (1)
 
54240326 copy
54240326   copy54240326   copy
54240326 copy
 
Java practice programs for beginners
Java practice programs for beginnersJava practice programs for beginners
Java practice programs for beginners
 

More from shweta-sharma99

Biometrics
BiometricsBiometrics
Biometrics
shweta-sharma99
 
Biometrics
BiometricsBiometrics
Biometrics
shweta-sharma99
 
Sql commands
Sql commandsSql commands
Sql commands
shweta-sharma99
 
Rep on grid computing
Rep on grid computingRep on grid computing
Rep on grid computing
shweta-sharma99
 
Graphics file
Graphics fileGraphics file
Graphics file
shweta-sharma99
 
Vbreport
VbreportVbreport
Vbreport
shweta-sharma99
 
Simplex
SimplexSimplex
Grid computing
Grid computingGrid computing
Grid computing
shweta-sharma99
 
Cyborg
CyborgCyborg
Smartphone
SmartphoneSmartphone
Smartphone
shweta-sharma99
 
Instruction cycle
Instruction cycleInstruction cycle
Instruction cycle
shweta-sharma99
 

More from shweta-sharma99 (13)

Biometrics
BiometricsBiometrics
Biometrics
 
Biometrics
BiometricsBiometrics
Biometrics
 
Testing
TestingTesting
Testing
 
Sql commands
Sql commandsSql commands
Sql commands
 
Rep on grid computing
Rep on grid computingRep on grid computing
Rep on grid computing
 
Graphics file
Graphics fileGraphics file
Graphics file
 
Vbreport
VbreportVbreport
Vbreport
 
Software re engineering
Software re engineeringSoftware re engineering
Software re engineering
 
Simplex
SimplexSimplex
Simplex
 
Grid computing
Grid computingGrid computing
Grid computing
 
Cyborg
CyborgCyborg
Cyborg
 
Smartphone
SmartphoneSmartphone
Smartphone
 
Instruction cycle
Instruction cycleInstruction cycle
Instruction cycle
 

Recently uploaded

From NCSA to the National Research Platform
From NCSA to the National Research PlatformFrom NCSA to the National Research Platform
From NCSA to the National Research Platform
Larry Smarr
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDBScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB
 
Day 4 - Excel Automation and Data Manipulation
Day 4 - Excel Automation and Data ManipulationDay 4 - Excel Automation and Data Manipulation
Day 4 - Excel Automation and Data Manipulation
UiPathCommunity
 
Radically Outperforming DynamoDB @ Digital Turbine with SADA and Google Cloud
Radically Outperforming DynamoDB @ Digital Turbine with SADA and Google CloudRadically Outperforming DynamoDB @ Digital Turbine with SADA and Google Cloud
Radically Outperforming DynamoDB @ Digital Turbine with SADA and Google Cloud
ScyllaDB
 
ScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking ReplicationScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking Replication
ScyllaDB
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
FilipTomaszewski5
 
TrustArc Webinar - Your Guide for Smooth Cross-Border Data Transfers and Glob...
TrustArc Webinar - Your Guide for Smooth Cross-Border Data Transfers and Glob...TrustArc Webinar - Your Guide for Smooth Cross-Border Data Transfers and Glob...
TrustArc Webinar - Your Guide for Smooth Cross-Border Data Transfers and Glob...
TrustArc
 
Call Girls Chandigarh🔥7023059433🔥Agency Profile Escorts in Chandigarh Availab...
Call Girls Chandigarh🔥7023059433🔥Agency Profile Escorts in Chandigarh Availab...Call Girls Chandigarh🔥7023059433🔥Agency Profile Escorts in Chandigarh Availab...
Call Girls Chandigarh🔥7023059433🔥Agency Profile Escorts in Chandigarh Availab...
manji sharman06
 
APJC Introduction to ThousandEyes Webinar
APJC Introduction to ThousandEyes WebinarAPJC Introduction to ThousandEyes Webinar
APJC Introduction to ThousandEyes Webinar
ThousandEyes
 
Building a Semantic Layer of your Data Platform
Building a Semantic Layer of your Data PlatformBuilding a Semantic Layer of your Data Platform
Building a Semantic Layer of your Data Platform
Enterprise Knowledge
 
Call Girls Chennai ☎️ +91-7426014248 😍 Chennai Call Girl Beauty Girls Chennai...
Call Girls Chennai ☎️ +91-7426014248 😍 Chennai Call Girl Beauty Girls Chennai...Call Girls Chennai ☎️ +91-7426014248 😍 Chennai Call Girl Beauty Girls Chennai...
Call Girls Chennai ☎️ +91-7426014248 😍 Chennai Call Girl Beauty Girls Chennai...
anilsa9823
 
CTO Insights: Steering a High-Stakes Database Migration
CTO Insights: Steering a High-Stakes Database MigrationCTO Insights: Steering a High-Stakes Database Migration
CTO Insights: Steering a High-Stakes Database Migration
ScyllaDB
 
Introduction to ThousandEyes AMER Webinar
Introduction  to ThousandEyes AMER WebinarIntroduction  to ThousandEyes AMER Webinar
Introduction to ThousandEyes AMER Webinar
ThousandEyes
 
Cyber Recovery Wargame
Cyber Recovery WargameCyber Recovery Wargame
Cyber Recovery Wargame
Databarracks
 
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
AlexanderRichford
 
ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes New Product Features and Release Highlights: June 2024ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes
 
An All-Around Benchmark of the DBaaS Market
An All-Around Benchmark of the DBaaS MarketAn All-Around Benchmark of the DBaaS Market
An All-Around Benchmark of the DBaaS Market
ScyllaDB
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
UiPathCommunity
 
Chapter 5 - Managing Test Activities V4.0
Chapter 5 - Managing Test Activities V4.0Chapter 5 - Managing Test Activities V4.0
Chapter 5 - Managing Test Activities V4.0
Neeraj Kumar Singh
 

Recently uploaded (20)

From NCSA to the National Research Platform
From NCSA to the National Research PlatformFrom NCSA to the National Research Platform
From NCSA to the National Research Platform
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDBScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
ScyllaDB Leaps Forward with Dor Laor, CEO of ScyllaDB
 
Day 4 - Excel Automation and Data Manipulation
Day 4 - Excel Automation and Data ManipulationDay 4 - Excel Automation and Data Manipulation
Day 4 - Excel Automation and Data Manipulation
 
Radically Outperforming DynamoDB @ Digital Turbine with SADA and Google Cloud
Radically Outperforming DynamoDB @ Digital Turbine with SADA and Google CloudRadically Outperforming DynamoDB @ Digital Turbine with SADA and Google Cloud
Radically Outperforming DynamoDB @ Digital Turbine with SADA and Google Cloud
 
ScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking ReplicationScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking Replication
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
 
TrustArc Webinar - Your Guide for Smooth Cross-Border Data Transfers and Glob...
TrustArc Webinar - Your Guide for Smooth Cross-Border Data Transfers and Glob...TrustArc Webinar - Your Guide for Smooth Cross-Border Data Transfers and Glob...
TrustArc Webinar - Your Guide for Smooth Cross-Border Data Transfers and Glob...
 
Call Girls Chandigarh🔥7023059433🔥Agency Profile Escorts in Chandigarh Availab...
Call Girls Chandigarh🔥7023059433🔥Agency Profile Escorts in Chandigarh Availab...Call Girls Chandigarh🔥7023059433🔥Agency Profile Escorts in Chandigarh Availab...
Call Girls Chandigarh🔥7023059433🔥Agency Profile Escorts in Chandigarh Availab...
 
APJC Introduction to ThousandEyes Webinar
APJC Introduction to ThousandEyes WebinarAPJC Introduction to ThousandEyes Webinar
APJC Introduction to ThousandEyes Webinar
 
Building a Semantic Layer of your Data Platform
Building a Semantic Layer of your Data PlatformBuilding a Semantic Layer of your Data Platform
Building a Semantic Layer of your Data Platform
 
Call Girls Chennai ☎️ +91-7426014248 😍 Chennai Call Girl Beauty Girls Chennai...
Call Girls Chennai ☎️ +91-7426014248 😍 Chennai Call Girl Beauty Girls Chennai...Call Girls Chennai ☎️ +91-7426014248 😍 Chennai Call Girl Beauty Girls Chennai...
Call Girls Chennai ☎️ +91-7426014248 😍 Chennai Call Girl Beauty Girls Chennai...
 
CTO Insights: Steering a High-Stakes Database Migration
CTO Insights: Steering a High-Stakes Database MigrationCTO Insights: Steering a High-Stakes Database Migration
CTO Insights: Steering a High-Stakes Database Migration
 
Introduction to ThousandEyes AMER Webinar
Introduction  to ThousandEyes AMER WebinarIntroduction  to ThousandEyes AMER Webinar
Introduction to ThousandEyes AMER Webinar
 
Cyber Recovery Wargame
Cyber Recovery WargameCyber Recovery Wargame
Cyber Recovery Wargame
 
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
QR Secure: A Hybrid Approach Using Machine Learning and Security Validation F...
 
ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes New Product Features and Release Highlights: June 2024ThousandEyes New Product Features and Release Highlights: June 2024
ThousandEyes New Product Features and Release Highlights: June 2024
 
An All-Around Benchmark of the DBaaS Market
An All-Around Benchmark of the DBaaS MarketAn All-Around Benchmark of the DBaaS Market
An All-Around Benchmark of the DBaaS Market
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
 
Chapter 5 - Managing Test Activities V4.0
Chapter 5 - Managing Test Activities V4.0Chapter 5 - Managing Test Activities V4.0
Chapter 5 - Managing Test Activities V4.0
 

Java practical

  • 1. 1. Program to generate Fibonacci series import java.io.*; import java.util.*; public class Fibonacci { public static void main(String[] args) { DataInputStream reader = new DataInputStream((System.in)); int f1=0,f2=0,f3=1; try { System.out.print("Enter value of n: "); String st = reader.readLine(); int num = Integer.parseInt(st); for(int i=1;i<=num;i++) { System.out.println("tt"+f3+"tnt"); f1=f2; f2=f3; f3=f1+f2; } } catch(Exception e) { System.out.println("wrong input"); } } } 2. Program to take two numbers as input from command line interface and display their sum
  • 2. Coding: class Sum { public void add(int a,int b) { int c; c=a+b; System.out.print("tttnnThe sum of two no is = "+c); System.out.println("nnn"); } } class SMain { public static void main(String arg[]) { Sum obj1=new Sum(); int x,y; String s1,s2; s1=arg[0]; s2=arg[1]; x=Integer.parseInt(s1); y=Integer.parseInt(s2); obj1.add(x,y); } } 3. Use of array in java Coding: class Person { String name[]; int age[]; }
  • 3. class PersonMain { public static void main(String arg[]) { Person obj=new Person(); obj.name=new String[6]; obj.age=new int[6]; obj.name[0]="Neha"; obj.age[0]=19; obj.name[1]="manpreet"; obj.age[1]=19; obj.name[2]="rahul"; obj.age[2]=23; obj.name[3]="yuvraj"; obj.age[3]=12; obj.name[4]="kombe"; obj.age[4]=19; obj.name[5]="tony"; obj.age[5]=19;
  • 4. for(int i=0;i<4;i++) System.out.println(obj.name[i]); { for(int j=0;j<4;j++) System.out.println(obj.age[j]); } } } 4. Create a class customer having three attributes name, bill and id. Include appropriate methods for taking input from customer and displaying its values Coding: import java.io.DataInputStream; class Customer { public static void main(String arf[]) { DataInputStream myinput=new DataInputStream(System.in); String name; int bill=0,id=0; try { System.out.println("enter name of customer"); name=myinput.readLine(); System.out.println("enter bill"); bill=Integer.parseInt(myinput.readLine()); System.out.println("enter id"); id=Integer.parseInt(myinput.readLine());
  • 5. System.out.println("name of customer is"+name); System.out.println("bill of customer"+bill); System.out.println("id of customer"+id); } catch(Exception e) { System.out.println("wrong input error!!!"); } } } 5. To show the concept of method overloading Coding: class Addition//FUNCTION OVERLOADING { public int add(int a,int b) { int c=a+b; return (c); } public float add(float a,float b) { float c=a+b; return (c);
  • 6. } public double add(double a,double b) { double c=a+b; return (c); } } class AddMain { public static void main(String arg[]) { Addition obj=new Addition(); System.out.println(obj.add(20,30)); System.out.println(obj.add(100.44f,20.54f)); System.out.println(obj.add(1380.544,473.56784)); } } 6. To count no. of object created of a class class Demo//OBJECT CREATION { private static int count=0; public Demo()
  • 7. { System.out.println("i am from demo"); count++; System.out.println("object created is"+count); } } class DemoMains { public static void main(String args[]) { Demo obj1=new Demo(); Demo obj2=new Demo(); Demo obj3=new Demo(); } } 7. To show concept of multilevel inheritance Coding: class A { private int num1,num2,sum; public void set(int x,int y) {
  • 8. num1=x; num2=y; sum=num1+num2; } public int get1() { return(sum); } } class B extends A { public void display() { System.out.println("sum of two numbers is"+get1()); } } class C extends B { private double sqr; public void sqrs() { sqr=java.lang.Math.sqrt(get1()); System.out.println("square root of sum is"+sqr); } } class ABCMain { public static void main(String args[]) { C obj1=new C(); obj1.set(100,200); System.out.println("first number is 100"); System.out.println("second number is 200"); obj1.display(); obj1.sqrs(); } }
  • 9. 8. To show concept of method overriding Coding: class Demo { private static int count=0; public Demo() { System.out.println("i am from demo"); count++; System.out.println("object created is"+count); } public String toString() { return("method overridding"); } } class MethodOverride { public static void main(String args[]) { Demo obj1=new Demo(); Demo obj2=new Demo(); Demo obj3=new Demo();
  • 10. System.out.println("overriding toString methodnnttoverriden message=: "+obj1.toString()); } } 9. Create a class that will at least import two packages and use the method defined in the classes of those packages. Coding: MyApplet.java: import java.awt.*; import java.applet.*; public class MyApplet extends Applet { public void paint(Graphics g) { g.drawLine(400,100,100,400); } } Ex1.html: <applet code="MyApplet.class" height="600" width="800" > </applet>
  • 11. 10. To create thread by extending thread class Coding: class T1 extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println("thread 1 created"); } } } class T2 extends Thread { public void run() { for(int i=0;i<5;i++) { System.out.println("thread 2 created"); } } } class TMain { public static void main(String arg[]) { T1 obj1=new T1(); obj1.start(); T2 obj2=new T2(); obj2.start(); } }
  • 12. 11. Create thread by implementing runnable interface Coding: class T1 implements Runnable { public void run() { for(int i=0;i<5;i++) { System.out.println("thread 1 created"); } } } class T2 implements Runnable { public void run() { for(int i=0;i<5;i++) { System.out.println("thread 2 created"); } } } class RMain { public static void main(String arg[]) { T1 obj1=new T1(); Thread t1=new Thread(obj1); T2 obj2=new T2(); Thread t2=new Thread(obj2); t1.start(); t2.start();
  • 13. } } 12. To create user defined exception class InvalidRollno extends Exception { String msg; public InvalidRollno() { } public InvalidRollno(String m) { msg=m; } public String toString() { return(msg); } }
  • 14. class Student { private int rollno; public void setStudent(int r) throws InvalidRollno { rollno=r; if(r<1) { throw new InvalidRollno("invalid rollno"); } } } class SMain { public static void main(String agf[]) { Student obj1=new Student(); try { obj1.setStudent(-11); } catch(InvalidRollno e) { System.out.println(e); }
  • 15. } } 13. Program for showing the concept of sleep method in multithreading. public class DelayExample{ public static void main(String[] args) { System.out.println("Hi"); for (int i = 0; i < 10; i++) { System.out.println("Number of itartion = " + i); System.out.println("Wait:"); try {
  • 16. Thread.sleep(4000); } catch (InterruptedException ie) { System.out.println(ie.getMessage()); }}} 14. Program to demonstrate a basic applet. import java.awt.*; import java.applet.*; /* <applet code="sim" width=300 height=300> </applet> */ public class sim extends Applet { String msg=" "; public void init()
  • 17. { msg+="init()--->"; setBackground(Color.orange); } public void start() { msg+="start()--->"; setForeground(Color.blue); } public void paint(Graphics g) { msg+="paint()--->"; g.drawString(msg,200,50); }} 15. Program for drawing various shapes on applets. import java.awt.*; import java.applet.*; /*
  • 18. <applet code="Sujith" width=200 height=200> </applet> */ public class Sujith extends Applet { public void paint(Graphics g) { for(int i=0;i<=250;i++) { Color c1=new Color(35-i,55-i,110-i); g.setColor(c1); g.drawRect(250+i,250+i,100+i,100+i); g.drawOval(100+i,100+i,50+i,50+i); g.drawLine(50+i,20+i,10+i,10+i); } } }
  • 19. 16. Program for filling various objects with colours. import java.awt.*; public class GradientPaintExample extends ShapeExample { private GradientPaint gradient = new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow, true); public void paintComponent(Graphics g) { clear(g) Graphics2D g2d = (Graphics2D)g; drawGradientCircle(g2d); } protected void drawGradientCircle(Graphics2D g2d)
  • 20. g2d.setPaint(gradient); g2d.fill(getCircle()); g2d.setPaint(Color.black); g2d.draw(getCircle()); } public static void main(String[] args) { WindowUtilities.openInJFrame(new GradientPaintExample(), 380, 400); } 17. Program of an applet which respond to mouse motion listener interface method. import javax.swing.*; import java.awt.Color;
  • 21. import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Container; import java.awt.event.*; public class MovingMessage { public static void main (String[] s) { HelloJava f = new HelloJava();} } class HelloJava extends JFrame implements MouseMotionListener, ActionListener { int messageX = 25, messageY = 100; String theMessage; JButton theButton; int colorIndex = 0; static Color[] someColors = { Color.black, Color.red,Color.green, Color.blue, Color.magenta }; HelloJava() { theMessage = "Dragging Message"; setSize(300, 200); Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); theButton = new JButton("Change Color"); contentPane.add(theButton); theButton.addActionListener(this);
  • 22. addMouseMotionListener(this); setVisible(true); } private void changeColor() { if (++colorIndex == someColors.length) colorIndex = 0; setForeground(currentColor()); repaint(); } private Color currentColor() { return someColors[colorIndex]; } public void paint(Graphics g) { super.paint(g); g.drawString(theMessage, messageX, messageY); } public void mouseDragged(MouseEvent e) { messageX = e.getX(); messageY = e.getY(); repaint(); } public void mouseMoved(MouseEvent e) { } public void actionPerformed(ActionEvent e)
  • 23. { if (e.getSource() == theButton) changeColor(); } } 18. Program of an applet which uses the various methods defined in the key listener interface. import java.awt.*; import java.awt.event.*; public class KeyListenerTester extends Frame implements KeyListener{ TextField t1; Label l1; public KeyListenerTester(String s ) { super(s); Panel p =new Panel(); l1 = new Label ("Key Listener!" ) ; p.add(l1); add(p); addKeyListener ( this ) ;
  • 24. setSize ( 200,100 ); setVisible(true); addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); } public void keyTyped ( KeyEvent e ){ l1.setText("Key Typed"); } public void keyPressed ( KeyEvent e){ l1.setText ( "Key Pressed" ) ; } public void keyReleased ( KeyEvent e ){ l1.setText( "Key Released" ) ; } public static void main (String[]args ){ new KeyListenerTester ( "Key Listener Tester" ) ; } }
  • 25. 19. program to change the background colour of applet by clicking on command button. import java.applet.Applet; import java.awt.Button; import java.awt.Color; public class ChangeButtonBackgroundExample extends Applet{ public void init() { Button button1 = new Button("Button 1"); Button button2 = new Button("Button 2"); button1.setBackground(Color.red); button2.setBackground(Color.green); add(button1); add(button2); } }
  • 26. 20. Program of an applet that will demonstrate a basic calculator. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Calculator extends JFrame { private final Font BIGGER_FONT = new Font("monspaced", Font.PLAIN, 20); private JTextField textfield; private boolean number = true; private String equalOp = "="; private CalculatorOp op = new CalculatorOp(); public Calculator() { textfield = new JTextField("0", 12); textfield.setHorizontalAlignment(JTextField.RIGHT);
  • 27. textfield.setFont(BIGGER_FONT); ActionListener numberListener = new NumberListener(); String buttonOrder = "1234567890 "; JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 4, 4, 4)); for (int i = 0; i < buttonOrder.length(); i++) { String key = buttonOrder.substring(i, i+1); if (key.equals(" ")) { buttonPanel.add(new JLabel("")); } else { JButton button = new JButton(key); button.addActionListener(numberListener); button.setFont(BIGGER_FONT); buttonPanel.add(button); } } ActionListener operatorListener = new OperatorListener(); JPanel panel = new JPanel(); panel.setLayout(new GridLayout(4, 4, 4, 4)); String[] opOrder = {"+", "-", "*", "/","=","C"}; for (int i = 0; i < opOrder.length; i++) { JButton button = new JButton(opOrder[i]); button.addActionListener(operatorListener); button.setFont(BIGGER_FONT); panel.add(button);
  • 28. } JPanel pan = new JPanel(); pan.setLayout(new BorderLayout(4, 4)); pan.add(textfield, BorderLayout.NORTH ); pan.add(buttonPanel , BorderLayout.CENTER); pan.add(panel , BorderLayout.EAST ); this.setContentPane(pan); this.pack(); this.setTitle("Calculator"); this.setResizable(false); } private void action() { number = true; textfield.setText("0"); equalOp = "="; op.setTotal("0"); } class OperatorListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (number) { action(); textfield.setText("0"); } else { number = true; String displayText = textfield.getText();
  • 29. if (equalOp.equals("=")) { op.setTotal(displayText); } else if (equalOp.equals("+")) { op.add(displayText); } else if (equalOp.equals("-")) { op.subtract(displayText); } else if (equalOp.equals("*")) { op.multiply(displayText); } else if (equalOp.equals("/")) { op.divide(displayText); } textfield.setText("" + op.getTotalString()); equalOp = e.getActionCommand(); } } } class NumberListener implements ActionListener { public void actionPerformed(ActionEvent event) { String digit = event.getActionCommand(); if (number) { textfield.setText(digit); number = false; } else { textfield.setText(textfield.getText() + digit); }
  • 30. } } public class CalculatorOp { private int total; public CalculatorOp() { total = 0; } public String getTotalString() { return ""+total; } public void setTotal(String n) { total = convertToNumber(n); } public void add(String n) { total += convertToNumber(n); } public void subtract(String n) { total -= convertToNumber(n); } public void multiply(String n) { total *= convertToNumber(n); } public void divide(String n) { total /= convertToNumber(n); }
  • 31. private int convertToNumber(String n) { return Integer.parseInt(n); } } } 21. Program for showing the use of various method of URL class. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; public class GetURL { static protected void getURL(String u) { URL url; InputStream is; InputStreamReader isr; BufferedReader r;
  • 32. String str; try { System.out.println("Reading URL: " + u); url = new URL(u); is = url.openStream(); isr = new InputStreamReader(is); r = new BufferedReader(isr); do { str = r.readLine(); if (str != null) System.out.println(str); } while (str != null); } catch (MalformedURLException e) { System.out.println("Must enter a valid URL"); } catch (IOException e) { System.out.println("Can not connect"); } } static public void main(String args[]) { if (args.length < 1) System.out.println("Usage: GetURL "); else getURL(args[0]); } }
  • 33. 22. Program to print concentric circles import java.awt.*; import java.applet.*; import java.util.*; public class c_cir extends Applet { public void paint(Graphics g) { Random rg = new Random(); for (int i=1; i<=3; i++) { int r = rg.nextInt(255); int gr = rg.nextInt(255); int b = rg.nextInt(255); Color c = new Color(r,gr,b); g.setColor(c);
  • 34. g.fillOval(100+i*5,100+i*5,100-i*10,100-i*10); } } } 23. Program to illustrate the use of methods of vector class import java.util.*; class vvect { public static void main(String a[]) {
  • 35. Vector a1 = new Vector(); int l = a.length; int i; for(i=0;i<l;i++) { a1.addElement(a[i]); } a1.insertElementAt("Vatan",2); int s = a1.size(); String r[] = new String[s]; a1.copyInto(r); System.out.println("n Different Font Styles:n"); for(i=0;i<s;i++) { System.out.println(r[i]); } } } 24. Program for showing the use ‘for’ in each statement. package loops; public class Forloops { public static void main(string[] args) { int loopval;
  • 36. int end_value=11; for (loopval=0; loopval<end_value;loopval++) { system.out.printin("loop value="+ loopval); } } } 25. Program for showing a use of jdp programming in java. import java.lang.*; import java.sql.*; class bca { public static void main(String arg[]) throws Exception { String stdrollno,stdname,stdclass; Connection conn;
  • 37. Statement stmt; ResultSet rs; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); conn=DriverManager.getConnection("jdbc:odbc:pctedsn","bca","bca"); stmt=conn.createStatement(); rs=stmt.executeQuery("select id,stdname,class from try"); System.out.println("Roll No Student Name Class"); while(rs.next()) { stdclass = rs.getString(1); stdname = rs.getString(2); stdrollno = rs.getString(3); System.out.println(stdrollno+" "+stdname+" "+stdclass); } //stmt.close(); //rs.close(); } }
  翻译: