SlideShare una empresa de Scribd logo
1 de 37
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();
}
}

Más contenido relacionado

La actualidad más candente (20)

Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)Lab manual data structure (cs305 rgpv) (usefulsearch.org)  (useful search)
Lab manual data structure (cs305 rgpv) (usefulsearch.org) (useful search)
 
The Stack And Recursion
The Stack And RecursionThe Stack And Recursion
The Stack And Recursion
 
Constructor
ConstructorConstructor
Constructor
 
String c
String cString c
String c
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
Introduction to Input/Output Functions in C
Introduction to Input/Output Functions in CIntroduction to Input/Output Functions in C
Introduction to Input/Output Functions in C
 
Method overriding
Method overridingMethod overriding
Method overriding
 
Applets
AppletsApplets
Applets
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Scope of variables
Scope of variablesScope of variables
Scope of variables
 
Multidimensional array in C
Multidimensional array in CMultidimensional array in C
Multidimensional array in C
 
Web Technology Lab File
Web Technology Lab FileWeb Technology Lab File
Web Technology Lab File
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 

Destacado

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya 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 AnswerTOPS Technologies
 
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 jobGaruda 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 questionsGradeup
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questionsDhivyashree 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 questionsGradeup
 
Java Code for Sample Projects Inheritance
Java Code for Sample Projects InheritanceJava Code for Sample Projects Inheritance
Java Code for Sample Projects Inheritancejwjablonski
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for vivaVipul Naik
 
31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentation31911477 internet-banking-project-documentation
31911477 internet-banking-project-documentationSwaroop Mane
 
Brochure rafael velásquez
Brochure rafael velásquezBrochure rafael velásquez
Brochure rafael velásquezrafaelhvv
 
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 2015Steve Wilkinson
 
Smart practices rev
Smart practices   revSmart practices   rev
Smart practices revOlena 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.4ChanPear
 

Destacado (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 a Java practical

Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Java Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab FileKandarp Tiwari
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
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.pdfanupamfootwear
 
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 FileFahad 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_jaiswarROHIT JAISWAR
 
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++ ExamsMuhammadTalha436
 

Similar a 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 Programs Lab File
Java Programs Lab FileJava Programs Lab File
Java Programs Lab File
 
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
 

Más de 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
 

Último

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

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(); } }