Java Certification, Programming, JavaBean and Object Oriented Reference Books
Java Example Event Programming

import java.awt.*;

import java.applet.*;

/*

<Applet code=bounds.class width=400 height=400>

</applet>

*/

public class bounds extends Applet

{

Button b1, b2,b3,b4;

public void init()

{

// setLayout(null);

b1 = new Button("First button");

b2 = new Button("test");

b3 = new Button("First button");

b4 = new Button("test");

Label l = new Label("same Label");

l.setBounds(10,10,40,40);

b1.setBounds(50,50,110,110);

b2.setBounds(200,200,50,20);

add(l);

add(b1);

add(b2);

/* setLayout(new FlowLayout());*/

add(l);

add(b3);

add(b4);

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*<applet code=butt width=500 height=400>

</applet>

*/
 
 

public class butt extends Applet implements ActionListener

{

TextField tx,tx1,tx2;

Button b1,b2;

public void init()

{

tx = new TextField(20);

tx1 = new TextField(20);

tx2 = new TextField(20);

b1 = new Button(" + ");

b2 = new Button(" - ");

b1.addActionListener(this);

b2.addActionListener(this);

add(tx);

add(tx1);

add(tx2);

add(b1);

add(b2);

}

public void actionPerformed(ActionEvent ae)

{

int a,b,c;

a = Integer.parseInt(tx1.getText());

b = Integer.parseInt(tx2.getText());

if(ae.getSource()==b1)

{

c = a + b;

tx.setText(String.valueOf(c));

}

else

{

c = a - b;

tx.setText(String.valueOf(c));

}

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class check extends Applet implements ItemListener

{

Checkbox ch,ch1,ch2,ch3;

CheckboxGroup chg;

TextField tx,tx1;

public void init()

{

ch = new Checkbox("Required");

add(ch);

ch.addItemListener(this);

chg = new CheckboxGroup();

ch1 = new Checkbox("Small",false,chg);

ch2 = new Checkbox("Medium",false,chg);

ch3 = new Checkbox("Large",true,chg);

add(ch1);

add(ch2);

add(ch3);

ch1.addItemListener(this);

ch2.addItemListener(this);

ch3.addItemListener(this);

tx = new TextField(15);

add(tx);

tx1 = new TextField(15);

add(tx1);

}

public void itemStateChanged(ItemEvent e)

{

if(e.getItemSelectable()==ch1)

tx.setText("Small selected");

if(e.getItemSelectable()==ch2)

tx.setText("Medium selected");

if(e.getItemSelectable()==ch3)

tx.setText("Large selected");

if(e.getItemSelectable()==ch)

if(ch.getState()==true)

tx1.setText("Required selected");

else

tx1.setText("Required not selected");

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/*<applet code=choice width=500 height=400>

</applet>

*/

public class choice extends Applet implements ItemListener

{

Choice ch;

TextField tx;

public void init()

{

tx = new TextField(14);

add(tx);

ch = new Choice();

ch.add("Videocon");

ch.add("BPL");

ch.add("Onida");

ch.add("Sony");

add(ch);

ch.addItemListener(this);

}

public void itemStateChanged(ItemEvent e)

{

if(e.getItemSelectable() == ch)

tx.setText(ch.getSelectedItem());

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code=drag width=400 height=400>

</applet>

*/

public class drag extends Applet implements MouseMotionListener

{

int x,y;

public void init()

{

addMouseMotionListener(this);

}

public void update(Graphics g)

{

paint(g);

}

public void paint(Graphics g)

{

g.setColor(Color.red);

g.drawOval(x,y,4,4);

}

public void mouseDragged(MouseEvent e)

{

x = e.getX();

y = e.getY();

repaint();

showStatus(x +"," + y);

}

public void mouseMoved(MouseEvent e) { }

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class mseadapt extends Applet

{

public void init()

{

Button b;

b = new Button("click me");

b.addMouseListener(new a());

add(b);

}

class a extends MouseAdapter

{

public void mouseClicked(MouseEvent e)

{

showStatus("clicked");

}

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class mseevents extends Applet implements MouseListener

{

public void init( )

{

addMouseListener(this);

}

public void mouseClicked(MouseEvent e)

{

showStatus("Mouse clicked at " + e.getX( ) +" , " + e.getY( ));

}

// Write above code for other mouse events

public void mouseEntered(MouseEvent e)

{

showStatus("Mouse entered at " + e.getX( ) +" , " + e.getY( ));

}

public void mousePressed(MouseEvent e)

{

showStatus("Mouse pressed at " + e.getX( ) +" , " + e.getY( ));

}

public void mouseExited(MouseEvent e)

{

showStatus("Mouse exited at " + e.getX( ) +" , " + e.getY( ));

}

public void mouseReleased(MouseEvent e)

{

showStatus("Mouse released at " + e.getX( ) +" , " + e.getY( ));

}
 
 

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code=drag width=400 height=400>

</applet>

*/

public class drag extends Applet implements MouseMotionListener

{

int x,y,c=0;

public void init()

{

addMouseMotionListener(this);

}

public void update(Graphics g)

{

paint(g);

}

public void paint(Graphics g)

{

if(c==0)

{ g.setColor(Color.blue);

g.drawLine(x,y,x+1,y+1);

}

else

{ g.setColor(Color.red);

g.drawOval(x,y,10,10);

}

}

public void mouseDragged(MouseEvent e)

{

c=1;

x = e.getX(); y = e.getY();

repaint();

}

public void mouseMoved(MouseEvent e)

{

c=0;

x=e.getX(); y=e.getY();

repaint();

}

}
 
 
 
 
 
 
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

public class txt extends Applet implements ActionListener

{

TextField tx;

Button b1,b2;

public void init()

{

tx = new TextField(20);

b1 = new Button("Display");

b2 = new Button("Clear");

b1.addActionListener(this);

b2.addActionListener(this);

add(tx);

add(b1);

add(b2);

}

public void actionPerformed(ActionEvent a)

{

if(a.getSource()==b1)

tx.setText("Welcome to Applet");

else

tx.setText("");

}

}
 
 

Frame Program

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code=colormenu width=400 height=400>

</applet>

*/

class frammenu extends Frame implements ActionListener

{

MenuBar mb; Menu m1,m2 ;

MenuItem mi1,mi2,mi3,mi4;

public void init()

{

mb = new MenuBar();

m1 = new Menu("File");

m2 = new Menu("Color");

mi1 = new MenuItem("Exit");

mi2 = new MenuItem("Blue");

mi3 = new MenuItem("Red");

mi4 = new MenuItem("Green");

mi1.addActionListener(this);

mi2.addActionListener(this);

mi3.addActionListener(this);

mi4.addActionListener(this);

m1.add(mi1);

m2.add(mi2); m2.add(mi3); m2.add(mi4);

mb.add(m1); mb.add(m2);

setMenuBar(mb);

}

public void actionPerformed(ActionEvent ae)

{

if(ae.getSource() == mi2)

setBackground(Color.blue);

if(ae.getSource() == mi3)

setBackground(Color.red);

}

}
 
 

public class colormenu extends Applet

{

public void init()

{

Frame f = new frammenu();

f.setSize(400,400);

f.setVisible(true);

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

class fra extends Frame

{

fra()

{

super("frame title");

winadapt w = new winadapt(this);

addWindowListener(w);

}

public void paint(Graphics g)

{

g.drawString("This is frame",100,100);

}

}

class winadapt extends WindowAdapter

{

fra f1;

public winadapt(fra f2)

{

f1 = f2;

}

public void windowClosing(WindowEvent e)

{

f1.setVisible(false);

}

}

class filedia

{

public static void main(String a[])

{

Frame f = new fra();

f.setSize(300,300);

f.setVisible(true);

FileDialog fd = new FileDialog(f,"File dialog");

fd.setVisible(true);

String ffile=fd.getFile();

String fdir=fd.getDirectory();

System.out.println("file " + ffile+" " + fdir);

}

}
 
 
 
 
 
 

import java.awt.*;

import java.applet.*;

public class frame1 extends Applet

{

Frame f;

public void init()

{

f = new Frame();

f.setSize(100,100);

f.setVisible(true);

}

public void paint(Graphics g)

{

g.drawString("this is applet",10,10);

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

class fra extends Frame

{

public void paint(Graphics g)

{

g.setColor(Color.blue);

g.drawString("This is frame",50,50);

g.drawLine(50,50,100,50);

g.fillOval(100,100,50,50);

}

}

public class frame2 extends Applet

{

Frame f;

public void init()

{

f = new fra();

f.setSize(100,100);

f.setVisible(true);

}

public void paint(Graphics g)

{

g.drawString("this is applet",10,10);

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

class fra extends Frame

{

fra()

{

super("frame title");

winadapt w = new winadapt(this);

addWindowListener(w);

}

public void paint(Graphics g)

{

g.drawString("This is frame",100,100);

}

}

class winadapt extends WindowAdapter

{

fra f1;

public winadapt(fra f2)

{

f1 = f2;

}

public void windowClosing(WindowEvent e)

{

f1.setVisible(false);

}

}

public class frame3 extends Applet

{

Frame f;

public void init()

{

f = new fra();

f.setSize(100,100);

f.setVisible(true);

}

public void paint(Graphics g)

{

g.drawString("this is applet",10,10);

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

/* <applet code=frammenu.class width=400 height=500>

</applet>

*/

class fram extends Frame

{

String msg=" ";

fram()

{

super("Menu Frame");

MenuBar mb = new MenuBar();

Menu m1 = new Menu("File");

Menu m2 = new Menu("Edit");

MenuItem mi1 = new MenuItem("Open");

MenuItem mi2 = new MenuItem("Save");

MenuItem mi3 = new MenuItem("Copy");

MenuItem mi4 = new MenuItem("Paste");

m1.add(mi1);

m1.add(mi2);

m2.add(mi3);

m2.add(mi4);

mb.add(m1);

mb.add(m2);

setMenuBar(mb);

winadapt w = new winadapt(this);

addWindowListener(w);

mi1.addActionListener(new mnuhandler(this));

mi2.addActionListener(new mnuhandler(this));

mi3.addActionListener(new mnuhandler(this));

}

public void paint(Graphics g)

{

g.drawString(msg,100,100);

}

}

class mnuhandler implements ActionListener

{

fram f1;

public mnuhandler(fram f2)

{

f1 = f2;

}

public void actionPerformed(ActionEvent ae)

{

String msg;

String s = (String) ae.getActionCommand();

if(s.equals("Open"))

msg = "Open";

else if(s.equals("Save"))

msg ="Save";

else if(s.equals("Copy"))

msg = "Copy";

else

msg = "Paste";

msg = msg +" selected";

f1.msg=msg;

f1.repaint();

}

}
 
 

class winadapt extends WindowAdapter

{

fram f1;

public winadapt(fram f2)

{

f1 = f2;

}

public void windowClosing(WindowEvent e)

{

f1.dispose();

}

}

public class frammenu extends Applet

{

Frame f;

public void init()

{

f = new fram();

f.setSize(300,300);

f.setVisible(true);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class mnu extends Applet

{

Frame f;

MenuBar mb;

Menu m1,m2;

MenuItem mi1,mi2,mi3,mi4;

public void init()

{

f = new Frame();

f.setSize(400,400);

f.setVisible(true);

mb = new MenuBar();

m1 = new Menu("files");

m2 = new Menu("edit");

mi1 = new MenuItem("new");

mi2 = new MenuItem("open");

mi3 = new MenuItem("cut");

mi4 = new MenuItem("paste");

m1.add(mi1);

m1.add(mi2);

m2.add(mi3);

m2.add(mi4);

mb.add(m1);

mb.add(m2);

f.setMenuBar(mb);

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Applet Program

import java.awt.*;

import java.applet.*;

public class appcolor extends Applet

{

public void init()

{

setBackground(Color.yellow);

}

public void paint(Graphics g)

{

g.drawString("Applet ",10,10);

g.setColor(Color.red);

g.drawString("This is red color",20,10);

g.setColor(Color.magenta);

g.drawString("Magenta",30,10);

g.setColor(Color.blue);

g.drawString("Blue",40,10);

g.setColor(Color.green);

g.drawString("Green",30,10);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class borderlay extends Applet

{

public void init()

{

BorderLayout f = new BorderLayout();

setLayout(f);

Button b1 = new Button("Left-West");

Button b2 = new Button("Footer-south");

Button b3 = new Button("PALANI");

Button b4 = new Button("Right-East");

Button b5 = new Button("Top-North");

Button b6 = new Button("RADIANT");

add(b1,BorderLayout.WEST);

add(b2,BorderLayout.SOUTH);

add(b3,BorderLayout.CENTER);

add(b4,BorderLayout.EAST);

add(b5,BorderLayout.NORTH);

add(b6,BorderLayout.CENTER);

TextField t = new TextField();

add(t,BorderLayout.CENTER);

}

public Insets getInsets()

{

return new Insets(10,10,10,10);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class butt extends Applet

{

public void init()

{

Label one = new Label("mouse");

Label two = new Label();

Label three = new Label("HCL",Label.CENTER);

add(one);

add(two);

add(three);

two.setText("visible");

add(two);

Button b1 = new Button("One");

Button b2 = new Button("Two");

add(b1);

add(b2);

Checkbox c1 = new Checkbox("Required");

Checkbox c2 = new Checkbox();

add(c1);

add(c2);

CheckboxGroup cg = new CheckboxGroup();

Checkbox c3 = new Checkbox("PentiumIII",true,cg);

Checkbox c4 = new Checkbox("Machintosh",false,cg);

Checkbox c5 = new Checkbox("487 machine",cg,false);

add(c3);

add(c4);

add(c5);

}

}
 
 

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

/*

<Applet code=card width=300 height=400>

</applet>

*/

public class card extends Applet implements ActionListener , MouseListener

{

String s="PP";

CardLayout c;

Button one,two;

Panel p,p1,p2;

Checkbox ch,ch1,ch2,ch3;

public void init()

{

one = new Button("one");

two = new Button("two");

add(one);

add(two);

c = new CardLayout();

p = new Panel();

p.setLayout(c);

ch = new Checkbox("Required");

ch1 = new Checkbox("Enable");

p1 = new Panel();

p1.add(ch);

p1.add(ch1);
 
 

ch2 = new Checkbox("Required");

ch3 = new Checkbox("Enable");

p2 = new Panel();

p2.add(ch2);

p2.add(ch3);

p.add(p1,"First pane");

p.add(p2,"Second pane");

add(p);

one.addActionListener(this);

two.addActionListener(this);

addMouseListener(this);

}

public void paint(Graphics g)

{

g.drawString(s,100,100);

}

public void mouseClicked(MouseEvent e)

{

}

public void mouseEntered(MouseEvent e)

{

}

public void mousePressed(MouseEvent e)

{

c.next(p);

s="fired";

repaint();

}

public void mouseExited(MouseEvent e)

{

}

public void mouseReleased(MouseEvent e)

{

}

public void actionPerformed(ActionEvent a)

{

if(a.getSource() == one)

{

c.show(p,"First pane");

}

else

{

c.show(p,"Second pane");

}

}

}
 
 

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class cardlay extends Applet implements ActionListener , MouseListener

{

CardLayout c;

Button one,two;

Panel p,p1,p2;

Checkbox ch,ch1,ch2,ch3;

public void init()

{

one = new Button("one");

two = new Button("two");

add(one);

add(two);

c = new CardLayout();

p = new Panel();

p.setLayout(c);

ch = new Checkbox("Required");

ch1 = new Checkbox("Enable");

p1 = new Panel();

p1.add(ch);

p1.add(ch1);
 
 

ch2 = new Checkbox("Required");

ch3 = new Checkbox("Enable");

p2 = new Panel();

p2.add(ch2);

p2.add(ch3);

p.add(p1,"First");

p.add(p2,"Second");

add(p);

one.addActionListener(this);

two.addActionListener(this);

addMouseListener(this);

}

public void mouseClicked(MouseEvent e)

{

}

public void mouseEntered(MouseEvent e)

{

}

public void mousePressed(MouseEvent e)

{

c.next(p);

}

public void mouseExited(MouseEvent e)

{

}

public void mouseReleased(MouseEvent e)

{

}

public void actionPerformed(ActionEvent a)

{

if(a.getSource() == one)

{

c.show(p,"First");

}

else

{

c.show(p,"Second");

}

}

}
 
 

import java.applet.*;

import java.awt.*;

public class cho extends Applet

{

public void init()

{

Choice ch = new Choice();

ch.add("One");

ch.add("Two");

ch.addItem("Three");

ch.addItem("Four");

add(ch);

List l = new List();

l.add("One");

l.add("Two");

l.addItem("Three");

l.addItem("Four");

add(l);

List l1 = new List(3);

l1.add("One");

l1.add("Two");

l1.addItem("Three");

l1.addItem("Four");

add(l1);

List l2 = new List(3,true);

l2.add("One");

l2.add("Two");

l2.addItem("Three");

l2.addItem("Four");

add(l2);

Scrollbar s1 = new Scrollbar();

Scrollbar s2 = new Scrollbar(Scrollbar.HORIZONTAL);

Scrollbar s3 = new Scrollbar(Scrollbar.VERTICAL,10,1,1,100);

add(s1);

add(s2);

add(s3);

}

}
 
 

import java.applet.*;

import java.awt.*;

public class cho1 extends Applet

{

public void init()

{

Choice ch = new Choice();

ch.add("One");

ch.add("Two");

ch.add("Three");

ch.add("Four");

add(ch);

List l = new List();

l.add("One");

l.add("Two");

l.add("Three");

l.add("Four");

add(l);

List l1 = new List(3);

l1.add("One");

l1.add("Two");

l1.add("Three");

l1.add("Four");

add(l1);

List l2 = new List(3,true);

l2.add("One");

l2.add("Two");

l2.add("Three");

l2.add("Four");

add(l2);

}

}
 
 

import java.applet.*;

import java.awt.*;

public class colors extends Applet

{

public void paint(Graphics g)

{

g.setFont(new Font("Arial",Font.BOLD,20));

g.drawString("Default color",10,10);

g.setColor(Color.red.green.yellow.red.cyan);

g.drawString("Find the color",10,30);

g.setColor(Color.pink);

g.drawString("Pink color",10,50);

g.setColor(Color.cyan);

g.drawString("Cyan color",10,70);

g.fillArc(80,80,120,120,0,90);

g.drawString("Squiggle #9",10,130);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class draw1 extends Applet

{

public void paint(Graphics g)

{

g.drawOval(60,60,120,120);

g.fillOval(90,120,50,20);

g.drawLine(165,125,165,175);

g.drawArc(110,130,95,95,0,-185);

g.drawLine(165,175,150,160);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class draw2 extends Applet

{

public void paint(Graphics g)

{

g.setColor(Color.red);

g.fillOval(205,60,30,30);

g.setColor(Color.orange);

g.fillRoundRect(180,90,80,80,20,20);

g.setColor(Color.blue);

g.fillRect(198,168,10,70);

g.fillRect(228,168,10,70);

g.fillRect(140,80,10,40);

g.fillRect(290,115,10,40);

g.fillRect(260,115,40,10);

g.fillRect(140,115,40,10);

g.setColor(Color.magenta);

g.drawString("Had fun",10,30);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class drawstr extends Applet

{

String s;

public void init()

{

s = "Welcome to Java" ;

}

public void paint(Graphics g)

{

g.drawString(s,100,100);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class flowlay extends Applet

{

public void init()

{

// FlowLayout f = new FlowLayout(FlowLayout.RIGHT);

FlowLayout f = new FlowLayout(0,10,10);

setLayout(f);

Button b1 = new Button("One");

Button b2 = new Button("One");

Button b3 = new Button("One");

Button b4 = new Button("One");

Button b5 = new Button("One");

add(b1);

add(b2);

add(b3);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class fonts extends Applet

{

Font f1,f2 ,f3;

public void init()

{

Font f1 = new Font("Courier",Font.BOLD,8);

Font f2 = new Font("Times Roman",Font.ITALIC,15);

Font f3 = new Font("Arial",Font.PLAIN,22);

}

public void paint(Graphics g)

{

g.setColor(Color.red);

g.drawString("Normal font",20,10);

g.setFont(f1);

g.setColor(Color.green);

g.drawString("Courier font",20,60);

g.setFont(f2);

g.setColor(Color.blue);

g.drawString("Times Roman",20,110);

g.setFont(f3);

g.setColor(Color.magenta);

g.drawString("Arial font",20,160);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class graph extends Applet

{

public void paint(Graphics g)

{

setBackground(Color.pink);

g.drawLine(10,10,10,200);

g.drawString("Palani",130,130);

g.drawRect(50,50,120,120);

g.setColor(Color.red);

g.drawRoundRect(150,150,250,250,30,30);

g.fillRect(270,270,50,50);

g.draw3DRect(300,300,10,10,true);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class gridlay extends Applet

{

public void init()

{

GridLayout f = new GridLayout(6,6,1,1);

setLayout(f);

Button b1 = new Button("One");

Button b2 = new Button("One");

Button b3 = new Button("One");

Button b4 = new Button("One");

Button b5 = new Button("One");

add(b1);

add(b2);

add(b3);

add(b4);

add(b5);

}

}
 
 

import java.applet.*;

import java.awt.*;

public class img extends Applet

{

Image i;

public void init()

{

i = getImage(getCodeBase(),"fish.gif");

}

public void paint(Graphics g)

{

g.drawImage(i,10,10,this);

}

}
 
 

import java.awt.*;

import java.applet.*;

public class order extends Applet

{

String s ;

public void init()

{

s = " Init " ;

}

public void start()

{

s = s + " start ";

}

public void paint(Graphics g)

{

s = s + " paint ";

g.drawString(s,100,100);

}

public void stop()

{

repaint();

s = "null";

}

}
 
 

import java.applet.*;

import java.awt.*;

public class param extends Applet

{

String str;

public void init()

{

str=getParameter("n");

setBackground(Color.cyan);

str="hai " + str + "How are you";

}

public void paint(Graphics g)

{

g.drawString(str,20,20);

}

}
 
 

import java.applet.*;

import java.awt.*;

public class poly extends Applet

{

int xp[]={10,20,30};

int yp[]={10,20,30};

int n =3;

public void paint(Graphics g)

{

g.drawPolygon(xp,yp,n);

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Book Program

class x

{

int a;

float f;

}

class y extends x

{

double c;

}

class clas

{

public static void main(String arg[])

{

x xx = new x();

y yy = new y();

Class ob;

ob = xx.getClass();

System.out.println("xx is object of type : " + ob.getName());

ob = yy.getClass();

System.out.println("yy is object of type : " + ob.getName());

ob = ob.getSuperclass();

System.out.println("y's superclass is : " + ob.getName());

}

}
 
 

class disp

{

public static void main(String a[])

{

System.out.println(a.length);

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

{

System.out.println(a[i]);

}

}

}
 
 

class init

{

public static void main(String[] arg)

{

int k;

int n=!1;

System.out.println(n);

System.out.println(arg[0]);

}

}
 
 

class out

{

int i=20;

private int j=30;

public int k =40;

protected int l=50;

public void m()

{

in inn = new in();

inn.inmethod();

}

public void mpu()

{

System.out.println("Pub");

}

public void mpr()

{

System.out.println("Pri");

}

void mde()

{

System.out.println("default");

}

class in

{

int j=10;

public void inmethod()

{

System.out.println("Inner method" + (i+j+k+l));

mpr();

mpu();

mde();

System.out.println("this j"+j);

// m();

}

}

}

class inner

{

public static void main(String arg[])

{

out o = new out();

o.m();

}

}
 
 

class math

{

public static void main(String arg[])

{

System.out.println(Math.random());

System.out.println(Math.E);

System.out.println(Math.PI);

System.out.println(4^5);

}

}
 
 

class mem

{

public static void main(String arg[])

{

Runtime r = Runtime.getRuntime();

long mem1,mem2;

int i;

Integer in[] = new Integer[1000];

System.out.println("total memory " + r.totalMemory());

mem1 = r.freeMemory();

System.out.println("Free memory " + mem1);

r.gc();

mem1 = r.freeMemory();

System.out.println("Free memory after garbage " + mem1);

for(i=0;i<1000;i++)

in[i] = new Integer(i);

mem2 = r.freeMemory();

System.out.println("Free memory after decl" + mem2);

System.out.println("diff " + (mem1-mem2));

r.gc();

r.gc();

r.gc();

mem2 = r.freeMemory();

System.out.println("Free memory after gc " + mem2);

}

}
 
 

class meth

{

public static void p(String s)

{

System.out.println(s);

}

static

{

p("hello");

}

public static void main(String a[])

{

p("hi");

char k='f';

switch(k)

{

case 'f' :

p("true");

break;

case 'a':

p("false");

break;

default :

p("default");

}

}

}
 
 

public class priclass

{

public static void main(String a[])

{

a ob1 = new a();

b ob2 = new b();

c ob3 = new c();

}

}

protected class a

{

public int k=33;

}

class b

{

public int j=23;

}

public class c

{

public int i=24;

}
 
 
 
 
 
 
 
 

class quest

{

public static void main(String arg[])

{

int i=7,j=8;

int n=(i|j) % (i & j) ;

System.out.println(n);

}

}
 
 

/* static class s

{

System.out.println("hi");

}

*/

static class statclass

{

public static void main(String arg[])

{

s ss = new s();

}

}
 
 

import java.util.*;

class test19

{

public static void main(String g[])

{

Vector v = new Vector();

v.add("Radiant");

v.add("Software");

System.out.println(v.elementAt(0) + v.elementAt(1));

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Exception Program

class myexception extends Exception

{

public String toString()

{

return "Myexception caught. A should be greater than 10";

}

}

class ex

{

public static void main(String arg[]) throws Exception

{

int a = Integer.parseInt(arg[0]);

if(a<10)

throw new myexception();

System.out.println("A is correct");

}

}
 
 

class myexception extends Exception

{

public String getMessage()

{

return "Myexception caught. A should be greater than 10";

}

}

class ex1

{

public static void main(String arg[]) throws Exception

{

int a = Integer.parseInt(arg[0]);

if(a<10)

throw new myexception();

System.out.println("A is correct");

}

}
 
 
 
 
 
 
 
 
 
 

class ex3

{

public static void main(String a[])

{

int m = Integer.parseInt(a[0]);

int n = Integer.parseInt(a[1]);

int r = m/n;

int k;

System.out.println(r);

// System.out.println(k);

}

}
 
 

class ex4

{

public static void main(String a[])

{

int m = Integer.parseInt(a[0]);

int n = Integer.parseInt(a[1]);

try

{

int r = m/n;

}

catch(ArithmeticException e)

{

System.out.println("div by zero");

}

catch(Exception e)

{ System.out.println("general");

}

finally

{

System.out.println("finally");

}

System.out.println("Successfull");

int k;

// System.out.println(r);

// System.out.println(k);

}

}
 
 

class A

{

A()

{ System.out.println("A 's constructor");}

}

class B extends A

{

public void A()

{ System.out.println("B 's constructor");}

B()

{

super();

}

}

class C extends B

{

C()

{ System.out.println("C 's constructor");}

}

class ext1

{

public static void main(String a[])

{

C cc = new C();

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Inh Program

class aa

{

public int a = 11;

private int b = 22;

int c = 33;

protected int d =44;

}

class bb extends aa

{

public void disp()

{

System.out.println(a);

// System.out.println(b);

System.out.println(c);

System.out.println(d);

}

}

class access

{

public static void main(String arg[])

{

bb ob = new bb();

ob.disp();

}

}
 
 

class a

{

a()

{

System.out.println("A 's constructor");

}

public void m()

{

System.out.println("a 's method");

}

}

class b extends a

{

b()

{

super();

System.out.println("B's constructor");

super.m();

}

public void a()

{

System.out.println("overrided a");

}

}

class inh1

{

public static void main(String a[])

{

b bb = new b();

}

}
 
 

class over

{

public void m()

{

}

public void m(int a)

{

}

public void m(float a)

{

}

public int m(int a)

{

return a;

}

}

class methover

{

public static void main(String arg[])

{

over o = new o();

o.m();

o.m(4);

o.m(9.4f);

int d = o.m(5);

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Infterface Program

interface callback

{

void callback(int param);

}
 
 

class imp2 implements callback

{

public void callback(int p)

{

System.out.println("callback called with " + p);

}

}

class imp1

{

public static void main(String a[])

{

callback c = new imp2();

c.callback(42);

}

}
 
 

class imp3 implements callback

{

public void callback(int t)

{

System.out.println("Interface");

}

public static void main(String a[])

{

imp3 i = new imp3();

i.callback(6);

}

}
 
 

class int1 implements inter

{

public void m()

{

}

}
 
 

public interface inter

{

public void m();

}
 
 

import java.io.*;

class read

{

public static void main(String a[]) throws IOException

{

char c;

InputStreamReader i = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

c = (char) br.read();

System.out.println(c);

c = (char) i.read();

System.out.println(c);

}

}
 
 

import java.io.*;

class read1

{

public static void main(String a[]) throws IOException

{

char c;

String s;

InputStreamReader i = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("press chars");

do

{

s = br.readLine();

System.out.println(s);

}while(!s.equals("stop"));

System.out.println("press chars");

do

{

// s = i.readLine();

System.out.println(s);

} while(!s.equals("stop"));

}

}
 
 

import java.io.*;

class fileread

{

public static void main(String a[]) throws IOException

{

int i;

FileInputStream fin;

try{

fin = new FileInputStream(a[0]);

}

catch(FileNotFoundException e)

{

System.out.println("File not found");

return ;

}

do

{

i = fin.read();

if(i != -1)

System.out.print((char) i);

}

while(i!= -1);

fin.close();

}

}
 
 

import java.io.*;

class files

{

public static void main(String arg[])

{

File f = new File ("c.c");

System.out.println("File Name : " + f.getName());

System.out.println(f.getPath());

System.out.println(f.getAbsolutePath());

String s;

s = (f.canRead()? "is readable" : "is writable");

System.out.println(s);

s = (f.isDirectory()? "dir" : "not dir");

System.out.println(s);

s = (f.isFile()? "file" : "not file");

System.out.println(s);

boolean b = f.delete();

}

}
 
 

import java.io.*;

class filewrite

{

public static void main(String a[]) throws IOException,FileNotFoundException

{

FileOutputStream fin = new FileOutputStream(a[0]);

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// int i = br.read();

String str = br.readLine();

byte[] b = str.getBytes();

fin.write(b);

System.out.print("Stored in the file");

fin.close();

}

}
 
 

import java.io.*;

class filewrite

{

public static void main(String a[]) throws IOException,FileNotFoundException

{

FileOutputStream fin = new FileOutputStream(a[0]);

BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

InputStreamReader br2 = new InputStreamReader(System.in));

// int i = br.read();

byte b = br.read();

byte b1 = br2.read();

String str = br.readLine();

// byte[] b = str.getBytes();

fin.write(b);

System.out.print("Stored in the file");

fin.close();

}

}
 
 

import java.io.*;

class in

{

public static void main(String arg[]) throws Exception

{

System.out.println("enter a number");

char c =(char) System.in.read();

System.out.println(c);

}

}
 
 
 
 
 
 
 
 
 
 
 
 

import java.io.*;

class pw

{

public static void main(String a[])

{

PrintWriter pw = new PrintWriter(System.out,true);

pw.print("this is the string");

int i=9;

pw.println(i);

double d=34.34;

pw.println(d);

System.out.write('e');

// System.out.write('lle');

System.out.write('\n');

}

}
 
 

import java.io.*;

class read

{

public static void main(String a[]) throws IOException,FileNotFoundException

{

int i;

FileInputStream fin = new FileInputStream(a[0]);

do

{

i = fin.read();

if(i != -1)

System.out.print((char) i);

}

while(i!= -1);

fin.close();

}

}
 
 

import java.io.*;

class reader

{

public static void main(String a[]) throws IOException

{

char c;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("enter characters . q to quit");

do

{

c = (char) br.read();

System.out.println(c);

}while(c!= 'q');

}

}
 
 

import java.io.*;

class reader1

{

public static void main(String a[]) throws IOException

{

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

String str;

System.out.println("Enter 'stop' to quit");

do

{

str = br.readLine();

System.out.println(str);

}while(!str.equals("stop"));

}

}
 
 

class str

{

public static void main(String a[])

{

StringBuffer s1 = new StringBuffer();

StringBuffer s2 = new StringBuffer(12);

StringBuffer s3 = new StringBuffer("palani");

System.out.println(s1.length() +" "+ s2.length() +" " + s3.length());

String s4 ="kumar" ;

String s5 = s4;

s2.append("Radiant");

System.out.println(s4.toUpperCase());

System.out.println(s1.length() +" "+ s2.length() +" " + s3.length());

System.out.println("substring " + s3.substring(3,3));

s3.append("kumar");

System.out.println(s3);

System.out.println(s2.reverse());

System.out.println(s2.delete(2,2));

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 

JDBC Program

import java.sql.*;

import java.sql.Types.*;

import java.util.*;

import java.io.*;

class callstatapp

{

public static final int VARCHAR=2;

public static void main(String args[])

{

try

{

String st;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:odbcoracle";

Connection con=DriverManager.getConnection(url,"palani","kumar");

CallableStatement cst;

cst=con.prepareCall("?=call fun");

con.close();

cst.registerOutParameter(1,VARCHAR);

st=cst.getString(1);

System.out.println("The result is "+st);

}

catch(Exception ex)

{

System.out.println(ex);

System.exit(0);

}

}

}
 
 

import java.sql.*;

import java.util.*;

class connecapp

{

public static void main(String sarg[])

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:odbcoracle";

Connection con=DriverManager.getConnection(url);

DatabaseMetaData meta=con.getMetaData();

System.out.println("database : "+meta.getDatabaseProductName());

System.out.println("version : "+meta.getDatabaseProductVersion());

System.out.println("username : "+meta.getUserName());

con.close();

}

catch(Exception ex)

{

System.out.println(ex);

System.exit(0);

}

}

}
 
 

import java.sql.*;

class dbcon

{

static Connection con;

public static void main(String a[ ]) throws Exception

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

try

{

con = DriverManager.getConnection("jdbc:odbc:empdsn","palani","kumar");

System.out.println("Connected to database");

Statement s = con.createStatement();

int rows = s.executeUpdate("Insert into emp values(110,'murali1',19000)");

System.out.println(rows + " rows inserted");

rows = s.executeUpdate("Update emp set salary=1200 where empid=120");

System.out.println(rows + " rows updated");

s.close();

con.close();

}

catch(SQLException e)

{

System.out.println("not Connected to database"+ e);

}

}

}
 
 

import java.sql.*;

class dbcon1

{

static Connection con;

public static void main(String a[ ]) throws Exception

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

try

{

con = DriverManager.getConnection("jdbc:odbc:odbcoracle","palani","kumar");

System.out.println("Connected to database");

Statement s = con.createStatement();

int rows = s.executeUpdate("create table runtt (sno number, sname varchar2(20))");

System.out.println(rows + " table created");

s.close();

con.close();

}

catch(SQLException e)

{

System.out.println("not Connected to database"+ e);

}

}

}
 
 

import java.sql.*;

import java.util.*;

class driverapp

{

public static void main(String args[])

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Enumeration drivers=DriverManager.getDrivers();

System.out.println("The list of drivers in the system");

while(drivers.hasMoreElements())

{

Driver driver=(Driver)drivers.nextElement();

System.out.println("Driver: "+driver.getClass().getName());

System.out.println("Major version: "+driver.getMajorVersion());

System.out.println("Minor version: "+driver.getMinorVersion());

System.out.println("JDBC complaint: "+driver.jdbcCompliant());

DriverPropertyInfo props[]=driver.getPropertyInfo(" ",null);

if(props!=null)

{

System.out.println("The list of properties");

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

{

System.out.println(" Name : "+props[i].name);

System.out.println(" Description : "+props[i].description);

System.out.println(" value : "+props[i].value);

if(props[i].choices!=null)

{

System.out.println("The list of choices");

for(int j=0;i<props[i].choices.length;j++)

System.out.println(" "+props[i].choices[j]);

}

System.out.println("requires :"+props[i].required);

}

}

}

}

catch(Exception ex)

{

System.out.println(ex);

System.exit(0);

}

}

}
 
 

import java.sql.*;

import java.util.*;

import java.io.*;

class prestat

{

public static void main(String args[])

{

int i=1;

try

{

String no;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:odbcoracle";

Connection con=DriverManager.getConnection(url,"palani","kumar");

PreparedStatement pst;

ResultSet rs;

boolean hasResults;

while(i<=2)

{

pst=con.prepareStatement("insert into tt values(?)");

System.out.println("\n Enter the employee no needed");

no=br.readLine();

System.out.println("\n The employee number chosen is "+no);

pst.setString(1,no);

hasResults=pst.execute();

if(hasResults)

{

rs=pst.getResultSet();

if(rs!=null)

disp(rs);

hasResults=false;

}

i=i+1;

}

con.close();

}

catch(Exception ex)

{

System.out.println(ex);

System.exit(0);

}

}

static void disp(ResultSet r) throws SQLException

{

System.out.print(r.getString(1));

boolean m =r.next();

System.out.print(r.getString(1));
 
 
 
 

}

}

}
 
 

import java.sql.*;

import java.util.*;

import java.io.*;

class prestatapp

{

public static void main(String args[])

{

int i=1;

try

{

String no;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:odbcoracle";

Connection con=DriverManager.getConnection(url,"palani","kumar");

PreparedStatement pst;

ResultSet rs;

boolean hasResults;

while(i<=3)

{

pst=con.prepareStatement("insert into tt values(?)");

System.out.println("\n Enter the employee no needed");

no=br.readLine();

System.out.println("\n The employee number chosen is "+no);

pst.setString(1,no);

hasResults=pst.execute();

if(hasResults)

{

rs=pst.getResultSet();

if(rs!=null)

disp(rs);

hasResults=false;

}

i=i+1;

}

con.close();

}

catch(Exception ex)

{

System.out.println(ex);

System.exit(0);

}

}

static void disp(ResultSet r) throws SQLException

{

ResultSetMetaData rmeta=r.getMetaData();

int numcol=rmeta.getColumnCount();

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

System.out.print(rmeta.getColumnName(i));

while(r.next())

{

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

System.out.print(r.getString(i));

}

}

}
 
 

import java.sql.*;

import java.util.*;

class resulapp

{

public static void main(String sarg[])

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:odbcoracle";

Connection con=DriverManager.getConnection(url,"palani","kumar");

Statement st=con.createStatement();

String sql="select * from emp";

ResultSet rs=st.executeQuery(sql);

disp(rs);

con.close();

}

catch(Exception ex)

{

System.out.println(ex);

System.exit(0);

}

}

static void disp(ResultSet r) throws SQLException

{

ResultSetMetaData rmeta=r.getMetaData();

int numcol=rmeta.getColumnCount();

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

System.out.print(rmeta.getColumnName(i)+"\t");

Sytem.out.print("\n");

while(r.next())

{

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

System.out.print(r.getString(i)+ "\t" );

System.out.print("\n");

}

}

}
 
 

import java.sql.*;

import java.util.*;

class statapp

{

public static void main(String args[])

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:odbcoracle";

Connection con=DriverManager.getConnection(url,"palani","kumar");

Statement st=con.createStatement();

String sql=args[0];

System.out.println(sql);

boolean hasResults=st.execute(sql);

if(hasResults)

{

ResultSet rs=st.getResultSet();

if(rs!=null)

disp(rs);

}

con.close();

}

catch(Exception ex)

{

System.out.println(ex);

System.exit(0);

}

}

static void disp(ResultSet r) throws SQLException

{

ResultSetMetaData rmeta=r.getMetaData();

int numcol=rmeta.getColumnCount();

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

System.out.print(rmeta.getColumnName(i));

while(r.next())

{

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

System.out.print(r.getString(i));

}

}

}
 
 

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.sql.*;

/* Table emp in oracle user palani columns eno ename sal */

class fram extends JFrame implements ActionListener

{

TextField txteno, txtename, txtsal ;

JLabel lbleno, lblename, lblsal, lblstat ;

Container cp;

Connection con;

Statement st;

JButton butinsert;

fram()

{

txteno = new TextField(12);

txtename = new TextField(12);

txtsal = new TextField(12);

lbleno = new JLabel("Empno ");

lblename= new JLabel("Ename ");

lblsal = new JLabel("salary");

lblstat = new JLabel("");

butinsert = new JButton("Insert");

cp = this.getContentPane();

cp.setLayout(new FlowLayout());

cp.add(lbleno);

cp.add(txteno);

cp.add(lblename);

cp.add(txtename);

cp.add(lblsal);

cp.add(txtsal);

cp.add(butinsert);

cp.add(lblstat);

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:odbcoracle";

con=DriverManager.getConnection(url,"palani","kumar");

lblstat.setText("successfully connected");

st=con.createStatement();

}

catch(Exception ex)

{

System.out.println("Cannot connect " + ex);

}

butinsert.addActionListener(this);

addWindowListener(new w(this));

}

class w extends WindowAdapter

{

fram f1;

w(fram f2)

{

f1 = f2;

}

public void windowClosing(WindowEvent we)

{

f1.setVisible(false);

f2.dispose();

}

}

public void actionPerformed(ActionEvent e)

{

if(e.getSource() == butinsert)

{

try

{

int rows = st.executeUpdate("insert into emp values(121,'melvin',5500)");

lblstat.setText(rows+ "inserted");

} catch(SQLException se) { }

}

}

}
 
 

class swodbc

{

public static void main(String arg[])

{

fram f = new fram();

f.setVisible(true);

f.setSize(400,400);

f.setLocation(200,200);

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Network Program

import java.net.*;

class dataclient

{

public static DatagramSocket ds;

public static byte buffer[] = new byte[1024];

public static void main(String args[]) throws Exception

{

ds = new DatagramSocket(1999);

while(true)

{

DatagramPacket p = new DatagramPacket(buffer,buffer.length);

ds.receive(p);

System.out.println(new String(p.getData(),0,p.getLength()));

}

}

}
 
 

import java.net.*;

class dataserver

{

public static DatagramSocket ds;

public static byte buffer[] = new byte[1024];

public static void main(String args[]) throws Exception

{

InetAddress ia = InetAddress.getByName(args[0]);

ds = new DatagramSocket(1666);

int pos=0;

while(true)

{

int c = System.in.read();

switch(c)

{

case 'q':

System.out.println("Server quits");

return;

case '\r':

break;

case '\n':

ds.send(new DatagramPacket(buffer,pos,ia,1999));

pos=0;

break;

default:

buffer[pos++] = (byte) c;

}

}

}

}
 
 

// a simple client that sends lines to server and reads lines from server

import java.net.*;

import java.io.* ;

public class tcpclient

{

public static void main(String arg[]) throws IOException

{

InetAddress addr;

if(arg.length > 0)

addr = InetAddress.getByName(arg[0]);

else

addr = InetAddress.getByName("localhost");

System.out.println("addr = " + addr);

Socket s = new Socket(addr,1666);

try

{

System.out.println("Socket = " + s);

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);

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

{

out.println("howdy " + i);

String str = in.readLine();

System.out.println(str);

}

out.println("End");

} finally

{

System.out.println("closing...");

s.close();

}

}

}
 
 

import java.io.* ;

import java.net.* ;

public class tcpserver

{

public static void main(String arg[]) throws IOException

{

ServerSocket ss = new ServerSocket(1666);

System.out.println("Server started " + ss);

try

{

Socket s = ss.accept();

try

{

System.out.println("Connection accepted " + s);

BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

// output is flushed by printwriter

PrintWriter pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true);

while(true)

{

String str = br.readLine();

if(str.equals("End"))

break;

System.out.println("Echoing : " + str);

pw.println(str);

}

}

finally

{

System.out.println("closing ...");

s.close();

}

}

finally

{

ss.close();

}

}

}
 
 

import java.net.*;

class client

{

public static DatagramSocket ds;

public static byte buffer[] = new byte[1024];

public static void main(String arg[]) throws Exception

{

ds = new DatagramSocket(6);

while(true)

{

String a;

DatagramPacket p = new DatagramPacket(buffer,buffer.length);

ds.receive(p);

a=new String(p.getData(),p.getLength(),1);

if (a.equals("q"))

{

System.out.println("Server response is shut off now");

return;

}

System.out.println(new String(p.getData(),0,p.getLength()));

}

}

}
 
 

import java.net.*;

class dataclient

{

public static DatagramSocket ds;

public static byte buffer[] = new byte[1024];

public static void main(String args[]) throws Exception

{

ds = new DatagramSocket(1999);

while(true)

{

DatagramPacket p = new DatagramPacket(buffer,buffer.length);

ds.receive(p);

System.out.println(new String(p.getData(),0,p.getLength()));

}

}

}
 
 

import java.net.*;

class dataserver

{

public static int serverport = 1666;

public static int clientport = 1999;

public static DatagramSocket ds;

public static byte buffer[] = new byte[1024];

public static void server() throws Exception

{

int pos=0;

while(true)

{

int c = System.in.read();

switch(c)

{

case -1:

System.out.println("Server quits");

return;

case '\r':

break;

case '\n':

ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientport));

pos=0;

break;

default:

buffer[pos++] = (byte) c;

}

}

}

public static void client() throws Exception

{

while(true)

{

DatagramPacket p = new DatagramPacket(buffer,buffer.length);

ds.receive(p);

System.out.println(new String(p.getData(),0,p.getLength()));

}

}

public static void main(String args[]) throws Exception

{

if(args.length ==1)

{

ds = new DatagramSocket(serverport);

server();

}

else

{

ds = new DatagramSocket(clientport);

client();

}

}

}
 
 

import java.net.*;

class inet

{

public static void main(String arg[]) throws UnknownHostException,MalformedURLException

{

InetAddress b = InetAddress.getLocalHost();

System.out.println(b);

String s = b.getHostAddress();

System.out.println(s);

InetAddress c = InetAddress.getByName(arg[0]);

System.out.println(c);
 
 

URL u = new URL("file:/j:/j002");

}

}
 
 
 
 
 
 
 
 
 
 

import java.net.*;

class server

{

public static DatagramSocket ds;

public static byte buffer[] = new byte[1024];

public static void main(String a[]) throws Exception

{

InetAddress ia = InetAddress.getByName("tmproj13");

System.out.print("Connect to ");

System.out.println(ia);

ds = new DatagramSocket(123);

int pos=0;

while(true)

{

int c = System.in.read();

switch(c)

{

case 'q':

System.out.println("Server quits");

return;

case '\r':

break;

case '\n':

DatagramPacket dp = new DatagramPacket(buffer,pos,ia,456);

ds.send(dp);

pos=0;

break;

default:

buffer[pos++] = (byte) c;

}

}

}

}
 
 

// a simple client that sends lines to server and reads lines from server

import java.net.*;

import java.io.* ;

public class tcpclient

{

public static void main(String arg[]) throws IOException

{

InetAddress addr = InetAddress.getByName(null);

// instead of null you can use localhost

System.out.println("addr = " + addr);

Socket s = new Socket(addr,tcpserver.port);

try

{

System.out.println("Socket = " + s);

BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));

PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())),true);

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

{

out.println("howdy " + i);

String str = in.readLine();

System.out.println(str);

}

out.println("End");

} finally{

System.out.println("closing...");

s.close();

}

}

}
 
 

import java.io.* ;

import java.net.* ;

public class tcpserver

{

public static final int port=8080;

public static void main(String arg[]) throws IOException

{

ServerSocket ss = new ServerSocket(port);

Socket s ;

System.out.println("Server started " + ss);

try {

s = ss.accept();

System.out.println("Connection accepted " + s);

BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));

// output is flushed by printwriter

PrintWriter pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()),true);

while(true)

{

String str = br.readLine();

if(str.equals("stop"))

break;

System.out.println("Echoing : " + str);

pw.println(str);

}

}finally {

System.out.println("closing ...");

s.close();

ss.close();

}}}
 
 

import java.net.*;

class udpclient

{

public static int serverport = 666;

public static int clientport = 999;

public static DatagramSocket ds;

public static byte buffer[] = new byte[1024];

public static void client() throws Exception

{

while(true)

{

DatagramPacket p = new DatagramPacket(buffer,buffer.length);

ds.receive(p);

System.out.print(new String(p.getData(),0,p.getLength()));

}

}

public static void main(String args[]) throws Exception

{

ds = new DatagramSocket(clientport);

client();

}

}

import java.net.*;

class udpserver

{

public static int serverport = 666;

public static int clientport = 999;

public static DatagramSocket ds;

public static byte buffer[] = new byte[1024];

public static void server() throws Exception

{

int pos=0;

while(true)

{

InetAddress ia = InetAddress.getByName("rad-tm-17");

int c = System.in.read();

ds.send(new DatagramPacket(buffer,pos,ia,clientport));

pos=0;

buffer[pos++] = (byte) c;

}

}

public static void main(String args[]) throws Exception

{

ds = new DatagramSocket(serverport);

server();

}}
 
 

Pack Programs

import pack.*;

class p

{

public static void main(String arg[])

{

pa p = new pa();

p.m();

}

}
 
 

package pack;

public class pa

{

public void m()

{

aa ob = new aa();

System.out.println(ob.a);

}

}

class aa

{

public int a=22;

}
 
 

import pack.*;

class pa1

{

public static void main(String arg[])

{

pa p = new pa();

p.m();

}

}

import pack.*;

class s

{

public static void main(String arg[])

{

sample ss = new sample();

ss.m();

c ss1 = new c();

System.out.println(ss1.a);

}

}
 
 

package pack;

import p.*;

public class sam

{

public void m()

{

c ob1 = new c();

// c1 ob2 = new c1();

// c2 ob3 = new c2();

ob2.m();

// ob2.m2();

System.out.println(ob1.a);

// System.out.println(ob1.b);

// System.out.println(ob1.c);

// System.out.println(ob1.d);

}

}

class c

{

public int a=55;

}
 
 

package pack;

public class sample

{

public void m()

{

c ob1 = new c();

System.out.println(ob1.a);

}

}

class c

{

public int a=55;

}
 
 

package p;

public class c

{

public int a=1;

private int b=2;

protected int c=3;

int d =4;

}
 
 

package p;

public class c1

{

public void m()

{

System.out.println("m method");

}

public void m1()

{

System.out.println("m1 method");

}

}
 
 

package p;

public class c2

{

public static void main(String arg[])

{

System.out.println("this is package");

}

}
 
 

interface i

{

final int a=33;

int b=44;

class c

{

}

public void m();

public void m1();

}
 
 

class int1 implements i

{

public void m()

{

}

public void m1()

{

}

public static void main(String arg[])

{

c ob = new c();

}

}

package p.p1;

public class c

{

public static void main(String arg[])

{

System.out.println("Subpackage");

}

}

Remote Method Invocation [RMI]
 
 

allows object in one machine to use method in another machine

one method of creating distributed application

Layers in RMI

Stub/Skeleton Layer

Remote Reference Layer

Transport Layer
 
 

Client Server
 
 

Stub Skeleton
 
 

RRL RRL
 
 

Transport Layer Transport Layer
 
 

Example program to find the sum of 2 numbers using rmi

inter.java

import java.rmi.*;

public interface inter extends Remote

{

public void getdata(int m,int n) throws RemoteException;

int adddata() throws RemoteException;

}
 
 

server.java

import java.rmi.*;

import java.rmi.server.*;

public class server extends UnicastRemoteObject implements inter

{

int x,y;

public server() throws RemoteException

{

}

public int adddata() throws RemoteException

{

return x+y;

}

public void getdata(int m, int n) throws RemoteException

{

x=m; y=n;

}

public static void main(String arg[])

{

try

{

server s = new server();

Naming.rebind("Addserver",s);

}

catch(Exception e)

{

System.out.println("can not bund the name " + e);

}

}

}
 
 

client.java

import java.rmi.*;

public class client

{

public static void main(String arg[ ])

{

try

{

int a = Integer.parseInt(arg[1]);

int b = Integer.parseInt(arg[2]);

int result;

inter i = (inter) Naming.lookup("rmi://" + arg[0] +

"/Addserver");

System.out.println("client");

i.getdata(a,b);

result = i.adddata();

System.out.println(result);

}

catch(Exception e)

{

System.out.println("can not connect with server " + e);

}

}

}

Important points

  1. import java.rmi.* ; all methods in this package throws

  2. RemoteException that must be caught.

  3. Remote in interface indicates that this is remote interface,

  4. the methods can be used by object in the remote machine.

  5. Server extends UnicastRemoteObject implements

  6. remote interface

    Also import java.rmi.server.* for server program

  7. Naming.rebind("servername", serverobject);

  8. Others methods are bind , rebind, unbind

  9. In client, Naming.lookup("rmi://ipaddress/servername") method is used to identify the server and returns remote interface.
6. Use inter.method to call the method in client.
 
 

Steps to exucute RMI

  1. Write programs for interface, server and client and
compile them.

javac inter.java

javac server.java

javac client.java or javac *.java

2. Then use rmi compiler to create stub and skeleton class.

rmic server

3. Copy inter, server, skeleton to server machine and

inter, client and stub to client program

4. Then start rmi registry by

start rmiregistry

5. Run the server program in server machine by

java server

6. Execute the client program by

java client ipaddress arg1 arg2

java client 200.200.1.120 5 8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

import java.rmi.*;

public class client

{

public static void main(String arg[])

{

try

{

int a = Integer.parseInt(arg[1]);

int b = Integer.parseInt(arg[2]);

int result;

inter i = (inter) Naming.lookup("rmi://" + arg[0] + "/Addserver");

System.out.println("client");

i.getdata(a,b);

result = i.adddata();

System.out.println(result);

}

catch(Exception e)

{

System.out.println("error " + e);

}

}

}
 
 

/* Example for deserialization

ObjectInputStream(FileInputStream f)

*/

import java.io.*;

class myclass implements Serializable

{

String s;

int i;

int j;

myclass(String s1,int m,int n)

{

s=s1; i=m;j=n;

}

public String toString()

{

return (s + i + j);

}

}

class deser

{

public static void main(String arg[]) throws Exception

{

myclass ob2 ;

FileInputStream f = new FileInputStream("obj");

ObjectInputStream o = new ObjectInputStream(f);

ob2 = (myclass) o.readObject();

System.out.println(ob2.s + ob2.i);

o.close();

System.out.println("Obeject2 " + ob2);

}

}
 
 

import java.rmi.*;

public interface inter extends Remote

{

public void getdata(int m,int n) throws RemoteException;

int adddata() throws RemoteException;

}
 
 

/* Example for serialization

ObjectOutputStream(FileOutputStream f)

o.writeObject(ob)

*/

import java.io.*;

class myclass implements Serializable

{

String s;

int i;

int j;

myclass(String s1,int m,int n)

{

s=s1; i=m;j=n;

}

}

class ser

{

public static void main(String arg[]) throws IOException, NotSerializableException

{

myclass ob = new myclass("Murali",4,5);

FileOutputStream f = new FileOutputStream("obj");

ObjectOutputStream o = new ObjectOutputStream(f);

o.writeObject(ob);

o.flush();

o.close();

System.out.println(ob);

}

}
 
 

import java.rmi.*;

import java.rmi.server.*;

public class server extends UnicastRemoteObject implements inter

{

int x,y;

public server() throws RemoteException

{

}

public int adddata() throws RemoteException

{

return x+y;

}

public void getdata(int m, int n) throws RemoteException

{

x=m; y=n;

}

public static void main(String arg[])

{

try

{

server s = new server();

Naming.rebind("Addserver",s);

}

catch(Exception e)

{

System.out.println("Exception e");

}

}

}
 
 

import java.rmi.*;

import java.rmiregistry.*;

public class clientport

{

public void actionPerformed(ActionEvent e)

{

if(e.getSource() == submit)

{

try

{

rmiserver server = (rmiserver) Naming.lookup("rmi//localhost/connect");

String name = getData();

}

catch(Exception e)

{

System.out.pritnln("Unable to connect");

}

}

}

}
 
 

import java.sql.*;

public class details

{

private Connection connect = null;

private Statement query =null;

private ResultSet result = null;

String dsn;

public details(String dsn)

{

this.dsn = "jdbc:odbc:" + dsn ;

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

connect = DriverManager.getConnection(dsn,"","");

query = connect.createStatement();

}

catch(Exception e)

{

e.printStackTrace();

System.out.println("Connection failed");

}

}

public void setData(String Table, String data)

{

try

{

// String sql = "Insert into " + table + (name) values("'+data+'")";

String sql = "Insert into table(name) values('rrr')";

query.executeUpdate(sql);

}

catch(Exception e)

{

System.out.println("Query failed");

}

}

}
 
 

import java.rmi.*;

import java.rmi.server.*;

public class rmidatabase extends UnicastRemoteObject implements rmiserver

{

private details det=null;

public rmidatabase(String name) throws RemoteException

{

super();

try

{

Naming.rebind(name,this);

}

catch(Exception e)

{

System.out.println("Unable to bind");

}

det = new details("student");

}

public String receiveData(String s)

{

return null;

}

public void sendData(String data)

{

System.out.println("Server sending data");

det.sendData("registration",data);

}

public static void main(String a[])

{

try

{

System.setSecurityManager(new RMISecurityManager());

rmidatabase connect = new rmidatabase("connect");

System.out.println("Server started");

}

catch(Exception e)

{

System.out.println("Error in server");

}

}

}
 
 

import java.rmi.*;

interface rmiserver extends Remote

{

public void sendData(String data) throws RemoteException ;

public String receiveData(String data) throws RemoteException ;

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Servelts Program

import java.io.*;

import javax.servlet.*;

import javax.servlet.http;

public class colorservlet extends HttpServlet

{

public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException, HttpServletException

{

String color = request.getParameter("color");

res.setContentType("text/html");

PrintWriter pw = res.getWriter();

pw.println("<B> the selected color is </B>");

pw.println(color);

pw.close();

}

}
 
 

import java.io.*;

import javax.servlet.*;

public class serv1 extends GenericServlet

{

public void service (ServletRequest req, ServletResponse res) throws ServletException,IOException

{

res.setContentType("text/html");

PrintWriter pw = res.getWriter();

pw.println("<B> Hello <I> Palani</B></I>");

pw.close();

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Swing Program

import java.awt.*;

import javax.swing.*;

/*

<applet code="butt" width=400 height=500>

</applet>

*/

public class butt extends JApplet

{

public void init()

{

Container c = getContentPane();

ImageIcon ii = new ImageIcon("fish.gif");

JLabel j = new JLabel("Fish image",ii,JLabel.LEFT);

c.add(j);

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/*

<Applet code="butt1" width=400 height=500>

</Applet>

*/

public class butt1 extends JApplet implements ActionListener

{

JTextField jtf = new JTextField(20);

public void init()

{

Container c = getContentPane();

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

ImageIcon i1 = new ImageIcon("Genier.gif");

ImageIcon i2 = new ImageIcon("Genieg.gif");

ImageIcon i3 = new ImageIcon("Genies.gif");
 
 

JButton jb1 = new JButton(i1);

JButton jb2 = new JButton(i2);

JButton jb3 = new JButton(i3);

jb1.setActionCommand("Fish");

jb2.setActionCommand("Genisis");

jb3.setActionCommand("Cherries");

jb1.addActionListener(this);

jb2.addActionListener(this);

jb3.addActionListener(this);

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

c.add(jb1);

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

c.add(jb2);

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

c.add(jb3);

c.add(jtf);

}

public void actionPerformed(ActionEvent ae)

{

jtf.setText(ae.getActionCommand());

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/*

<Applet code="gene" width=400 height=500>

</Applet>

*/

public class gene extends JApplet implements ActionListener

{

JLabel l;

public void init()

{

Container c = getContentPane();

l = new JLabel("Image icon");

c.setLayout(new GridLayout(3,3));

ImageIcon i2 = new ImageIcon("Genieg.gif");

JButton jb2 = new JButton("swing button",i2);

jb2.setActionCommand("Genisis");

c.add(jb2);

jb2.addActionListener(this);

}

public void actionPerformed(ActionEvent a)

{

l.setText("Pressed");

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/*

<Applet code="geneier" width=400 height=500>

</Applet>

*/

public class geneier extends JApplet implements ActionListener

{

JTextField jtf = new JTextField(20);

JButton jb1;

Container c = getContentPane();

public void init()

{

c.setLayout(new GridLayout(2,2));

ImageIcon i1 = new ImageIcon("Genier.gif");

ImageIcon i2 = new ImageIcon("Genieg.gif");

ImageIcon i3 = new ImageIcon("Genies.gif");

jb1 = new JButton(i1);

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

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

jb1.setIcon(i2);

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

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

c.add(jb1);

jb1.setActionCommand("Fish");

jb1.addActionListener(this);

c.add(jtf);

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

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

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

c.add(jb1);

}

/* public void paint(Graphics g)

{

c.add(jb1);

}

*/

public void actionPerformed(ActionEvent ae)

{

jtf.setText(ae.getActionCommand());

}

}
 
 

import javax.swing.*;

import java.awt.*;

public class jscroll extends JApplet

{

public void init( )

{

Container CP = getContentPane( );

JPanel jp = new JPanel( );

GridLayout g = new GridLayout(20,20);

jp.setLayout(g);

int b = 0,i,k;

for( i = 0; i<20; i++)

{

for(k=0;k<20;k++)

{

jp.add(new JButton("Button " + b));

b++;

}

}
 
 

int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;

JScrollPane jsp = new JScrollPane(jp, v, h) ;

CP.add(jsp, BorderLayout.CENTER);

}

}
 
 

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class radio extends JApplet

{

public void init()

{

Container c = getContentPane();

c.setLayout(new FlowLayout());

ImageIcon i1 = new ImageIcon("cup1.gif");

ImageIcon i2 = new ImageIcon("cup2.gif");

ImageIcon i3 = new ImageIcon("cup3.gif");

JRadioButton jb1 = new JRadioButton("Face ",i1);

JRadioButton jb2 = new JRadioButton("Sun ",i2);

JRadioButton jb3 = new JRadioButton("Song ",i3);

ButtonGroup bg = new ButtonGroup();

bg.add(jb1);

bg.add(jb2);

bg.add(jb3);

c.add(jb1);

c.add(jb2);

c.add(jb3);

}

}
 
 

import javax.swing.*;

import java.awt.*;

public class swing1 extends JApplet

{

public void init()

{

Container cp=getContentPane();

JLabel l1=new JLabel("Enter name");

JTextField jt=new JTextField(20);

JLabel l2=new JLabel("Enter age");

JTextField jt1=new JTextField(20);

cp.add(l1);cp.add(jt);

cp.add(l2);cp.add(jt1); }

}
 
 

import javax.swing.*;

import java.awt.*;

/*<applet code=swing1.class width=500 height=400>

</applet>

*/

public class swing1 extends JApplet

{

public void init()

{

Container cp=getContentPane();

cp.setLayout(new FlowLayout());

JLabel l1=new JLabel("Enter name");

JTextField jt=new JTextField(20);

JLabel l2=new JLabel("Enter age");

JTextField jt1=new JTextField(20);

cp.add(l1);cp.add(jt);

cp.add(l2);cp.add(jt1);

}

}
 
 

import javax.swing.*;

import java.awt.*;

public class swing2 extends JApplet

{

public void init()

{

Container cp=getContentPane();

String head[]={"name","phone","fax"};

Object data[][]={{"jaya","870075","0422"},

{"swapna","24683","04633"},

{"Murali","243443","3434"},

{"kaya","344545","34553"}};

JTable t=new JTable(data,head);

cp.add(t);

}

}
 
 

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class swing3 extends JApplet implements ActionListener // ,MouseListener

{

JTextField jtf;

public void init()

{

Container cp=getContentPane();

cp.setLayout(new FlowLayout());

ImageIcon i=new ImageIcon("MAPIF0S.ICO");

JButton jb=new JButton("exit",new ImageIcon("MAPIF0S.ICO"));

jb.setActionCommand("france");

jb.addActionListener(this);

// jb.addMouseListener(this);

cp.add(jb);

}

// public void mouseClicked(MouseEvent me)

// {

// }

public void actionPerformed(ActionEvent ae)

{

jtf.setText(ae.getActionCommand());

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import java.net.*;

import java.applet.*;

import javax.swing.*;

/** A very simple applet. */

public class SwingApplet extends JApplet

{

JButton button;

public void init() {

// Force SwingApplet to come up in the System L&F

String laf = UIManager.getSystemLookAndFeelClassName();

try {

UIManager.setLookAndFeel(laf);

// If you want the Cross Platform L&F instead,

//comment out the above line and // uncomment the following: //IManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); }

}

catch (UnsupportedLookAndFeelException exc)

{

System.err.println("Warning: UnsupportedLookAndFeel: " + laf);

}

catch (Exception exc)

{

System.err.println("Error loading " + laf + ": " + exc);

}

getContentPane().setLayout(new FlowLayout());

button = new JButton("Hello, I'm a Swing Button!"); getContentPane().add(button);

}

public void stop()

{

if (button != null)

{ getContentPane().remove(button);

button = null;

}

}

}
 
 

import javax.swing.*;

import java.awt.*;

/*

<applet code=datapanel height=400 width=400>

</applet>

*/

public class datapanel extends JPanel {

JTextField id, first, last,address, home, city,

state, zip, country, email, fax;

JLabel lfirst, llast, laddress,lhome, lcity,

lstate, lzip, lcountry, lemail, lfax;

public datapanel() {

// Label panel

JPanel labelPanel = new JPanel();

labelPanel.setLayout(new GridLayout(10,1));

lfirst = new JLabel("First Name:",0);

labelPanel.add(lfirst);

llast = new JLabel("Last Name:",0);

labelPanel.add( llast);

lhome = new JLabel("Phone:", 0 );

labelPanel.add(lhome);

laddress = new JLabel("Address:", 0 );

labelPanel.add(laddress);

lcity = new JLabel("City:", 0 );

labelPanel.add(lcity);

lstate = new JLabel("State:", 0 );

labelPanel.add( lstate);

lzip = new JLabel("Zip Code:", 0 );

labelPanel.add(lzip);

lcountry = new JLabel("Country:", 0 );

labelPanel.add( lcountry);

lemail = new JLabel("Email:", 0 );

labelPanel.add( lemail);

lfax = new JLabel("Fax Number:", 0 );

labelPanel.add( lfax);

// TextField panel

JPanel screenvarPanel = new JPanel();

screenvarPanel.setLayout(new GridLayout( 10, 1 ) );

id = new JTextField( 20) ;

first = new JTextField( 20 );

screenvarPanel.add( first );

last = new JTextField( 20 );

screenvarPanel.add( last );

home = new JTextField("Enter number-click Find", 20);

screenvarPanel.add( home );

address = new JTextField( 20 );

screenvarPanel.add( address );

city = new JTextField( 20 );

screenvarPanel.add( city );

state = new JTextField( 20 );

screenvarPanel.add( state );

zip = new JTextField( 20 );

screenvarPanel.add( zip );

country = new JTextField( 20 );

screenvarPanel.add( country );

email = new JTextField( 20 );

screenvarPanel.add( email );

fax = new JTextField( 20 );

screenvarPanel.add( fax );

// Accessibility Section - relate labels and text

// fields for use by assistive technologies

lfirst.setLabelFor( first );

llast.setLabelFor( last );

lhome.setLabelFor( home );

laddress.setLabelFor( address );

lcity.setLabelFor( city );

lstate.setLabelFor( state );

lzip.setLabelFor( zip );

lcountry.setLabelFor( country );

lemail.setLabelFor( email );

lfax.setLabelFor( fax );

setLayout( new GridLayout( 1, 2 ) );

add( labelPanel );

add( screenvarPanel );

}

}
 
 

import java.awt.event.*;

import javax.swing.*;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import java.awt.*;

import java.awt.geom.*;

import java.awt.print.*;

public class SimpleBook extends JPanel implements ActionListener

{

final static Color bg = Color.white;

final static Color fg = Color.black;

final static Color red = Color.red;

final static Color white = Color.white;

final static BasicStroke stroke = new BasicStroke(2.0f);

final static BasicStroke wideStroke = new BasicStroke(8.0f);

final static float dash1[] = {10.0f};

final static BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,10.0f, dash1, 0.0f);

final static JButton button = new JButton("Print");

public SimpleBook()

{ setBackground(bg); button.addActionListener(this);

}

public void actionPerformed(ActionEvent e)

{

// Get a PrinterJob

PrinterJob job = PrinterJob.getPrinterJob();

// Create a landscape page format

PageFormat landscape = job.defaultPage(); landscape.setOrientation(PageFormat.LANDSCAPE);

// Set up a book

Book bk = new Book();

bk.append(new PaintCover(), job.defaultPage());

bk.append(new PaintContent(), landscape);

// Pass the book to the PrinterJob

job.setPageable(bk);

// Put up the dialog box

if (job.printDialog())

{

// Print the job if the user didn't cancel printing

try { job.print(); }

catch (Exception exc)

{

/* Handle Exception */

}

}

}

public void paintComponent(Graphics g)

{

super.paintComponent(g);

Graphics2D g2 = (Graphics2D) g;

drawShapes(g2);

}

static void drawShapes(Graphics2D g2)

{

int gridWidth = 600 / 6;

int gridHeight = 250 / 2;

int rowspacing = 5;

int columnspacing = 7;

int rectWidth = gridWidth - columnspacing;

int rectHeight = gridHeight - rowspacing;

Color fg3D = Color.lightGray;

g2.setPaint(fg3D);

g2.drawRect(80, 80, 605 - 1, 265);

g2.setPaint(fg);

int x = 85;

int y = 87;

// draw Line2D.Double

g2.draw(new Line2D.Double(x, y+rectHeight-1, x + rectWidth, y));

x += gridWidth;

Graphics2D temp = g2;

// draw Rectangle2D.Double

g2.setStroke(stroke);

g2.draw(new Rectangle2D.Double(x, y, rectWidth, rectHeight));

x += gridWidth;

// draw RoundRectangle2D.Double

g2.setStroke(dashed);

g2.draw(new RoundRectangle2D.Double(x, y, rectWidth,

rectHeight, 10, 10));

x += gridWidth;

// draw Arc2D.Double

g2.setStroke(wideStroke);

g2.draw(new Arc2D.Double(x, y, rectWidth, rectHeight, 90,

135, Arc2D.OPEN));

x += gridWidth;

// draw Ellipse2D.Double

g2.setStroke(stroke);

g2.draw(new Ellipse2D.Double(x, y, rectWidth, rectHeight));

x += gridWidth;

// draw GeneralPath (polygon)

int x1Points[] = {x, x+rectWidth, x, x+rectWidth};

int y1Points[] = {y, y+rectHeight, y+rectHeight, y};

GeneralPath polygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,

x1Points.length);

polygon.moveTo(x1Points[0], y1Points[0]);

for ( int index = 1; index < x1Points.length; index++ ) {

polygon.lineTo(x1Points[index], y1Points[index]);

};

polygon.closePath();

g2.draw(polygon);

// NEW ROW

x = 85;

y += gridHeight;

// draw GeneralPath (polyline)

int x2Points[] = {x, x+rectWidth, x, x+rectWidth};

int y2Points[] = {y, y+rectHeight, y+rectHeight, y};

GeneralPath polyline = new GeneralPath(GeneralPath.WIND_EVEN_ODD,

x2Points.length);

polyline.moveTo (x2Points[0], y2Points[0]);

for ( int index = 1; index < x2Points.length; index++ ) {

polyline.lineTo(x2Points[index], y2Points[index]);

};

g2.draw(polyline);

x += gridWidth;

// fill Rectangle2D.Double (red)

g2.setPaint(red);

g2.fill(new Rectangle2D.Double(x, y, rectWidth, rectHeight));

g2.setPaint(fg);

x += gridWidth;

// fill RoundRectangle2D.Double

GradientPaint redtowhite = new GradientPaint(x,y,red,x+rectWidth,y,white);

g2.setPaint(redtowhite);

g2.fill(new RoundRectangle2D.Double(x, y, rectWidth,

rectHeight, 10, 10));

g2.setPaint(fg);

x += gridWidth;

// fill Arc2D

g2.setPaint(red);

g2.fill(new Arc2D.Double(x, y, rectWidth, rectHeight, 90,

135, Arc2D.OPEN));

g2.setPaint(fg);

x += gridWidth;

// fill Ellipse2D.Double

redtowhite = new GradientPaint(x,y,red,x+rectWidth, y,white);

g2.setPaint(redtowhite);

g2.fill (new Ellipse2D.Double(x, y, rectWidth, rectHeight));

g2.setPaint(fg);

x += gridWidth;

// fill and stroke GeneralPath

int x3Points[] = {x, x+rectWidth, x, x+rectWidth};

int y3Points[] = {y, y+rectHeight, y+rectHeight, y};

GeneralPath filledPolygon = new GeneralPath(GeneralPath.WIND_EVEN_ODD,

x3Points.length);

filledPolygon.moveTo(x3Points[0], y3Points[0]);

for ( int index = 1; index < x3Points.length; index++ ) {

filledPolygon.lineTo(x3Points[index], y3Points[index]);

};

filledPolygon.closePath();

g2.setPaint(red);

g2.fill(filledPolygon);

g2.setPaint(fg);

g2.draw(filledPolygon);

g2.setStroke(temp.getStroke());

}
 
 
 
 

public static void main(String[] args) {

WindowListener l = new WindowAdapter() {

public void windowClosing(WindowEvent e) {System.exit(0);}

public void windowClosed(WindowEvent e) {System.exit(0);}

};

JFrame f = new JFrame();

f.addWindowListener(l);

JPanel panel = new JPanel();

panel.add(button);

f.getContentPane().add(BorderLayout.SOUTH, panel);

f.getContentPane().add(BorderLayout.CENTER, new SimpleBook());

f.setSize(775, 450);

f.show();

}

}

class PaintCover implements Printable {

Font fnt = new Font("Helvetica-Bold", Font.PLAIN, 48);

public int print(Graphics g, PageFormat pf, int pageIndex)

throws PrinterException {

g.setFont(fnt);

g.setColor(Color.black);

g.drawString("Sample Shapes", 100, 200);

return Printable.PAGE_EXISTS;

}

}

class PaintContent implements Printable {

public int print(Graphics g, PageFormat pf, int pageIndex)

throws PrinterException {

SimpleBook.drawShapes((Graphics2D) g);

return Printable.PAGE_EXISTS;

}

}

Timer

Swing timer is a software device that triggers an action at the specifed rate. Programs sometimes need to perform task that involves periodic execution of certain operations. For ex to perform animation, we need to periodically display images at a certain rate and perhaps in a separate thread. JTimers uses a separate thread to execute that task.

Timer (delay, ActionListener listener)

delay in milliseconds

methods : start() stop() restart()
 
 

import java.awt.*;

import javax.swing.*;

/*<Applet code=jtimer1 width=400 height=500>

</applet>

*/

public class jtimer1 extends JApplet

{

int i=0;

Container cp =null;

Timer t=null;

JLabel label;

public void init()

{

label = new JLabel("1");

cp = this.getContentPane();

t = new Timer(20,new TimerListener());

t.setInitialDelay(20);

cp.add(label);

t.start();

}

class TimerListener implements ActionListener

{

public void actionPerformed(ActionEvent ae)

{

label.setText(i+" ");

i++;

}

}

}
 
 

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.awt.image.*;

import javax.swing.filechooser.*;

/*<applet code=imgview width=500 height=500>

</applet>

*/

public class imgview extends JFrame implements ActionListener

{

private JLabel label;

public imgview()

{

setTitle("ImageViewer");

setSize(300,300);

JMenuBar mb = new JMenuBar();

JMenu m1 = new JMenu("File");

JMenuItem mi1 = new JMenuItem("Open");

JMenuItem mi2 = new JMenuItem("Exit");

mi1.addActionListener(this);

mi2.addActionListener(this);

m1.add(mi1);

m1.addSeparator();

m1.add(mi2);
 
 

mb.add(m1);

setJMenuBar(mb);

label = new JLabel();

Container cp = this.getContentPane();

cp.add(label,"Center");

}

public void actionPerformed(ActionEvent ae)

{

String arg = ae.getActionCommand();

if(arg.equals("Open"))

{

JFileChooser ch = new JFileChooser();

ch.setCurrentDirectory(new File("."));

ch.setFileFilter(new javax.swing.filechooser.FileFilter()

{

public boolean accept(File f)

{

return f.getName().toLowerCase().endsWith("*.gif");

}

public String getDescription()

{

return "GIF Images";

}

});

int r = ch.showOpenDialog(this);

if( r == JFileChooser.APPROVE_OPTION)

{

String name = ch.getSelectedFile().getName();

label.setIcon(new ImageIcon(name));

}

}

else

if(arg.equals("Exit"))

System.exit(0);

}

public static void main(String a[])

{

JFrame fra = (JFrame) new imgview();

fra.show();

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/*<applet code=jcolor width=400 height=400>

</applet>

*/

public class jcolor extends JApplet

{

Container cp;

DrawingPanel dp;

JColorChooser cc;

JDialog dialog ;

int oldx,oldy,newx,newy;

JButton b;

Color color;

public void init()

{

cp = getContentPane();

dp = new DrawingPanel();

cp.add(dp);

b = new JButton("Show Color Chooser");

b.addActionListener(new buttlist());

Box hBox = Box.createHorizontalBox();

hBox.add(Box.createHorizontalGlue());

hBox.add(b);

hBox.add(Box.createHorizontalGlue());

cp.add(hBox,BorderLayout.SOUTH);

cc= new JColorChooser();

dialog = JColorChooser.createDialog(cp,"Color Chooser",false,cc,new buttlist(),new buttlist());

}

class DrawingPanel extends Panel

{

public DrawingPanel()

{

setBackground(Color.white);

mselist mselist1 = new mselist();

addMouseListener(mselist1);

addMouseMotionListener(mselist1);

}

public void update(Graphics g)

{

g.setColor(color);

paint(g);

}

public void paint(Graphics g)

{

g.drawLine(oldx,oldy,newx,newy);

}

}

class buttlist implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

JButton jb = (JButton) e.getSource();

if( jb.getText().equals("Show Color Chooser"))

{

dialog.show();

}

if(jb.getText().equals("OK"))

{

color = cc.getColor();

}

else if(jb.getText().equals("Cancel"))

{

dialog.dispose();

}

}

}

class mselist extends MouseAdapter implements MouseMotionListener

{

public void mousePressed(MouseEvent e)

{

oldx=e.getX(); oldy = e.getY();

newx = e.getX(); newy=e.getY();

dp.repaint();

}

public void mouseDragged(MouseEvent e)

{

oldx=newx;oldy=newy;

newx=e.getX(); newy=e.getY();

dp.repaint();

}

public void mouseMoved(MouseEvent e)

{}

}

}
 
 

import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

/* <applet code=jmenu1.class width=400 height=500>

</applet>

*/

public class jmenu1 extends JApplet

{

public void init()

{

JMenuBar mb = new JMenuBar();

JMenu m1 = new JMenu();

JMenu m2 = new JMenu("Second Alt-S");

JMenu m3 = new JMenu("Third",false);

JMenu m4 = new JMenu("fourth",true);

JMenuItem mi11 = new JMenuItem("second one Alt-s");

JMenuItem mi12 = new JMenuItem("second two");

JMenuItem mi13 = new JMenuItem("second three",new ImageIcon("cup1.gif"));

JMenuItem mi21 = new JMenuItem(new ImageIcon("cup3.gif"));

JMenuItem mi22 = new JMenuItem(new ImageIcon("cup4.gif"));

JMenuItem mi23 = new JMenuItem(new ImageIcon("cup5.gif"));

JMenuItem mi31 = new JMenuItem("Fourth One",'F');

JMenuItem mi32 = new JMenuItem("Fourth Two",'o');

JMenuItem mi33 = new JMenuItem("Fourth Three",'u');

mb.add(m1); mb.add(m2); mb.add(m3); mb.add(m4);

m4.add(mi31); m4.add(mi32); m4.add(mi33);

m3.add(mi21); m3.add(mi22); m3.add(mi23);

m2.add(mi11); m2.add(mi12); m2.addSeparator(); m2.add(mi13);

Container cp = this.getContentPane();

cp.add(mb,BorderLayout.NORTH);

}

}
 
 

import java.awt.*;

import javax.swing.*;

import javax.swing.border.*;

/* <applet code=jmenu2.class width=400 height=500>

</applet>

*/

public class jmenu2 extends JApplet

{

public void init()

{

Container cp = this.getContentPane();

JMenuBar mb = new JMenuBar();

mb.setBorder(new BevelBorder(BevelBorder.RAISED));

cp.add(mb,BorderLayout.NORTH);

JMenu jm1 = new JMenu("File",true);

JMenu jm2 = new JMenu("Edit");

JMenu jm3 = new JMenu("Format");

JMenu jm4 = new JMenu("Options");

mb.add(jm1);

mb.add(jm2);

mb.add(jm3);

mb.add(jm4);

JMenu m = mb.getMenu(0);

m.setMnemonic('F');

mb.getMenu(1).setMnemonic('d');

mb.getMenu(2).setMnemonic('x');

jm4.setMnemonic('o');
 
 

/*

for(int i=0; i<mb.getMenuCount(); i++)

{

JMenu m = mb.getMenu(i);

m.setIcon(new ImageIcon("red.gif"));

String tx = m.getText();

m.setMnemonic(tx.charAt(0));

}

*/ }

}
 
 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;

/*

<Applet code=jpopup width=400 height=500>

</applet>

*/

public class jpopup extends JFrame

{

JPopupMenu jpm;

JMenuItem mi1, mi2, mi3,mi4;

JTextArea jta;

Container cp;

public void init()

{

jpm = new JPopupMenu();

mi1 = new JMenuItem("Cut");

mi2 = new JMenuItem("Copy");

mi3 = new JMenuItem("Paste");

mi4 = new JMenuItem("Save");

cp = this.getContentPane();

jta = new JTextArea("Click ;the mouse right button inside "

+ " \nthe frame");

cp.add(jta);

jpm.add(mi1); jpm.add(mi2); jpm.add(mi3);

jpm.addSeparator(); jpm.add(mi4);

jta.addMouseListener(new pml());

this.addWindowListener(new FrameClosing());

}

class pml extends MouseAdapter

{

public void mousePressed(MouseEvent me)

{

showpop(me);

}

public void mouseReleased(MouseEvent me)

{

showpop(me);

}

private void showpop(MouseEvent me)

{

// showStatus(me.getY());

if(me.isPopupTrigger())

{

jpm.show(me.getComponent(), me.getX(), me.getY());

// showStatus("pop");

}

}

}

class FrameClosing extends WindowAdapter

{

public void windowClosing(WindowEvent we)

{

System.exit(0);

}

}

public static void main(String a[])

{

Frame fram = new jpopup();

fram.setTitle("Jpopupmenu");

fram.setSize(400,400);

fram.setVisible(true);

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;

import javax.swing.event.*;

/*<applet code=jtimer width=400 height=500>

</applet>

*/

/* JTimer(delay,new c())

start() stop() restart()

*/

public class jtimer extends JApplet

{

int i=0,j=255;

Container cp =null;

Timer t=null;

JLabel label;

public void init()

{

label = new JLabel("1");

cp = this.getContentPane();

cp.setLayout(null);

t = new Timer(1000,new TimerListener());

t.setInitialDelay(20);

label.setBounds(100,100,50,100);

cp.add(label);

t.start();

}

class TimerListener implements ActionListener

{

public void actionPerformed(ActionEvent ae)

{

label.setText(i+" ");

i++;j--;

Color c = new Color(i,j,i);

label.setBackground(c);

setBackground(c);

if (i>255) i=0;

if(j<1) j=255;

}

}

}
 
 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.border.*;

import javax.swing.event.*;

/*<applet code=jtimer1 width=400 height=500>

</applet>

*/

public class jtimer1 extends JApplet

{

int i=0;

Container cp =null;

Timer t=null;

JLabel label;

public void init()

{

label = new JLabel("1");

cp = this.getContentPane();

t = new Timer(20,new TimerListener());

t.setInitialDelay(20);

cp.add(label);

t.start();

}

class TimerListener implements ActionListener

{

public void actionPerformed(ActionEvent ae)

{

label.setText(i+" ");

i++;

}

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Thread Program

// Creating a Thread by extending the thread class

class th1 extends Thread

{

th1( )

{

super("test thread") ;

System.out.println("Child thread : " + this) ;

start( ) ;

}

public void run( )

{

try{

for(int I=5; I>0; I--)

{

System.out.println("child thread"+I);

Thread.sleep(500);

}

} catch(InterruptedException e) { }

System.out.println("exiting child thread");

}
 
 

public static void main(String g[ ])

{

new th1( );

try{

for(int j=5;j>0;j--)

{

System.out.println("Main thread : "+ j);

Thread.sleep(1000);

}

} catch (InterruptedException e) { }

System.out.println("Main thread exiting ");

}

}
 
 

/* A simple animation using thread*/

import java.applet.*;

import java.awt.*;

/*<applet code=th10 width=400 height=500>

</applet>

*/

public class th10 extends Applet implements Runnable

{

Thread t;

int i=0;

public void start()

{

t = new Thread(this);

t.start();

}

public void run()

{

for(; ;)

{

i++;

repaint();

try {

Thread.sleep(1000);

}

catch(InterruptedException e)

{ }

}

}

public void paint(Graphics g)

{

String s= i+" ";

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

g.drawString(s,20,20);

}

}
 
 

// Creating a Thread by implementing the Runnable interface

class th2 implements Runnable

{

String name;

Thread t;

th2 (String threadname)

{

name=threadname;

t = new Thread(this,name);

System.out.println("New thread " + t);

t.start();

}

public void run()

{

try {

for(int i=5;i>0;i--)

{

System.out.println(name+i );

Thread.sleep(500);

}

} catch(InterruptedException e)

{

System.out.println(name+"interrupted");

}

System.out.println(name + "exiting");

}

public static void main(String g[ ])

{

th2 tt = new th2("childthread");

try{

for(int j=20;j>10;j--)

{

System.out.println("Main thread : "+ j);

Thread.sleep(1000);

}

} catch (InterruptedException e) { }

System.out.println("Main thread exiting ");

}

}
 
 

// program for multiple threads using join() methods

class newthread implements Runnable

{

String name;

Thread t;

newthread(String threadname)

{

name=threadname;

t = new Thread(this,name);

System.out.println("New thread " + t);

t.start();

}

public void run()

{

try {

for(int i=5;i>0;i--)

{

System.out.println(name+i );

Thread.sleep(500);

}

}catch(InterruptedException e)

{

System.out.println(name+"interrupted");

}

System.out.println(name + "exiting");

}

}

class th3

{

public static void main(String arg[])

{

newthread ob1 = new newthread("One");

newthread ob2 = new newthread("Two");

newthread ob3 = new newthread("Three");

System.out.println("thread one is alive" + ob1.t.isAlive());

System.out.println("thread two is alive" + ob2.t.isAlive());

System.out.println("thread three is alive" + ob3.t.isAlive());

try{

System.out.println("Waiting for threads to finish");

ob1.t.join();

ob2.t.join();

ob3.t.join();

} catch(InterruptedException e)

{ System.out.println("Main thread interrupted");

}

System.out.println("thread one is alive" + ob1.t.isAlive());

System.out.println("thread two is alive" + ob2.t.isAlive());

System.out.println("thread three is alive" + ob3.t.isAlive());

System.out.println("main thread exits");

}

}
 
 

// program for setting prioirty

class th4 implements Runnable

{

Thread t;

th4(int n)

{

t = new Thread(this);

t.setPriority(n);

System.out.println("Child thread : " + this) ;

t.start() ;

}

public void run( )

{

try

{

for(int I=5; I>0; I--)

{

System.out.println("child thread"+I);

Thread.sleep(500);

}

} catch(InterruptedException e) { }

System.out.println("exiting child thread");

}
 
 

public static void main(String g[ ])

{

th4 t1 = new th4(3);

th4 t2 = new th4(8);

try{

for(int j=5;j>0;j--)

{

System.out.println("Main thread : "+ j);

Thread.sleep(1000);

}

} catch (InterruptedException e) { }

System.out.println("Main thread exiting …");

}

}
 
 

class th1 implements Runnable

{

Thread t;

th1()

{

t = new Thread(this,"childone");

t.setPriority(3);

System.out.println("Child thread one: " + this) ;

t.start() ;

}

public void run( )

{

try

{

for(int I=5; I>0; I--)

{

System.out.println("child thread one"+I);

Thread.sleep(500);

}

} catch(InterruptedException e) { }

System.out.println("exiting child thread one");

}

}

class th2 implements Runnable

{

Thread t;

th2()

{

t = new Thread(this,"childtwo");

t.setPriority(7);

System.out.println("Child thread two: " + this) ;

t.start() ;

}

public void run( )

{

try

{

for(int I=55; I>50; I--)

{

System.out.println("child thread two "+I);

Thread.sleep(500);

}

} catch(InterruptedException e) { }

System.out.println("exiting child thread two");

}

}

class th5

{

public static void main(String g[ ])

{

th1 t1 = new th1();

th2 t2 = new th2();

try{

for(int j=5;j>0;j--)

{

System.out.println("Main thread : "+ j);

Thread.sleep(1000);

}

} catch (InterruptedException e) { }

System.out.println("Main thread exiting ");

}

}
 
 

class callme

{

void call(String msg)

{

System.out.println(msg);

try

{

Thread.sleep(1000);

}

catch(InterruptedException e)

{

System.out.println("Interrupted");

}

}

}

class caller implements Runnable

{

String msg;

callme target;

Thread t;

public caller(callme targ , String s)

{

target = targ;

msg =s;

t = new Thread(this);

t.start();

}

public void run()

{

target.call(msg);

}

}

class th6

{

public static void main(String arg[])

{

callme target = new callme();

caller ob1 = new caller(target,"Hello");

caller ob2 = new caller(target,"Synchronized");

caller ob3 = new caller(target,"World");

try

{

ob1.t.join();

ob2.t.join();

ob3.t.join();

}catch(InterruptedException e)

{

}

}

}
 
 

class callme

{

void call(String msg)

{

System.out.println(msg);

try

{

Thread.sleep(5000);

}

catch(InterruptedException e)

{

System.out.println("Interrupted");

}

}

}

class caller implements Runnable

{

String msg;

callme target;

Thread t;

public caller(callme targ , String s)

{

target = targ;

msg =s;

t = new Thread(this);

t.start();

}

public void run()

{

synchronized(target) // synchronized block

{

target.call(msg);

}

}

}

class th7

{

public static void main(String arg[])

{

callme target = new callme();

caller ob1 = new caller(target,"Hello");

caller ob2 = new caller(target,"synchronized");

caller ob3 = new caller(target,"World");

try

{

ob1.t.join();

ob2.t.join();

ob2.t.join();

}catch(InterruptedException e)

{

}

}

}
 
 

// Creating a Thread by implementing the Runnable interface in Java 1.2

class th2 implements Runnable

{

String name;

Thread t;

th2 (String threadname)

{

name=threadname;

t = new Thread(this,name);

System.out.println("New thread " + t);

t.start();

}

public void run()

{

try {

for(int i=5;i>0;i--)

{

System.out.println(name+i );

Thread.sleep(500);

}

} catch(InterruptedException e)

{

System.out.println(name+"interrupted");

}

System.out.println(name + "exiting");

}

}
 
 

class th8

{

public static void main(String g[ ])

{

th2 ob1 = new th2("childthread one");

th2 ob2 = new th2("childthread two");

try{

Thread.sleep(1000);

ob1.t.suspend();

System.out.println("Suspending thread one");

Thread.sleep(1000);

ob1.t.resume();

System.out.println("Resuming thread one");

ob2.t.suspend();

System.out.println("Suspending thread two");

Thread.sleep(1000);

ob2.t.resume();

System.out.println("Resuming thread two");

}

catch(InterruptedException e)

{

System.out.println("Main thread interupted");

}

System.out.println("Main thread exiting");

}

}

// Creating a Thread by implementing the Runnable interface in Java2

class th2 implements Runnable

{

String name;

Thread t;

boolean flag;

th2 (String threadname)

{

name=threadname;

t = new Thread(this,name);

System.out.println("New thread " + t);

flag=false;

t.start();

}

public void run()

{

try {

for(int i=5;i>0;i--)

{

System.out.println(name+i );

Thread.sleep(500);

synchronized(this)

{ while(flag)

wait();

}

}

} catch(InterruptedException e)

{

System.out.println(name+"interrupted");

}

System.out.println(name + "exiting");

}

void mysuspend()

{

flag=true;

}

synchronized void myresume()

{

flag=false;

notify();

}

}

class th9

{

public static void main(String g[ ])

{

th2 ob1 = new th2("childthread one");

th2 ob2 = new th2("childthread two");

try{

Thread.sleep(1000);

ob1.mysuspend();

System.out.println("Suspending thread one");

Thread.sleep(1000);

ob1.myresume();

System.out.println("Resuming thread one");

ob2.mysuspend();

System.out.println("Suspending thread two");

Thread.sleep(1000);

ob2.myresume();

System.out.println("Resuming thread two");

}

catch(InterruptedException e)

{

System.out.println("Main thread interupted");

}

System.out.println("Main thread exiting");

}

}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Utility Program

import java.util.*;

class a

{

}

class arraylist extends a

{

public static void main(String arg[])

{

// Integer i = new Integer[12];

ArrayList a = new ArrayList();

System.out.println("Size of array " + a.size());

a.add("A");

a.add("B");

a.add("C");

a.add("D");

System.out.println(a);

a.add(2,"P");

System.out.println("Size of array " + a.size());

System.out.println(a);

a.remove("C");

a.remove(3);

System.out.println("Size of array " + a.size());

System.out.println(a);

}

}
 
 

import java.util.*;

class bitset

{

public static void main(String arg[])

{

int i;

BitSet b1 = new BitSet(16);

BitSet b2 = new BitSet(16);

for(i=0;i<8;i++)

b1.set(i);

for(i=0;i<16;i=i+2)

b2.set(i);

b2.set(9);

System.out.println(b1);

System.out.println(b2);

b2.and(b1);

System.out.println(b2);

b2.set(9);

b2.xor(b1);

System.out.println(b2);

b2.or(b1);

System.out.println(b2);

}

}
 
 

import java.util.*;

class cc

{

int a,b;

}

class comp implements Comparator

{

public static void main(String arg[])

{

cc ob1 = new cc();

cc ob2 = new cc();

int r = compare(ob1,ob2);

System.out.println(r);

}

}
 
 

import java.util.*;

class dict extends Dictionary

{

public static void main(String a[])

{

/* Dictionary d = new Dictionary( );

d.put(new Integer(10),100);

System.out.println(d.get());

*/

}

}
 
 

import java.util.*;

class hash

{

public static void main(String a[])

{

Hashtable h = new Hashtable();

Integer i= new Integer(300);

h.put("John",i);

h.put("Smith",new Integer(400));

System.out.println(h.get("John"));

}

}
 
 
 
 

import java.util.*;

class stack

{

public static void main(String a[])

{

Integer i = new Integer(10);

Stack s = new Stack();

s.push(i);

s.push(new Integer(100));

System.out.println(s.pop());

System.out.println(s.peek());

System.out.println(s.pop());

System.err.println("d");

}

}
 
 

class str

{

public static void main(String arg[])

{

String s1 = "rad" ;

String s2 = "rad" ;

String s3 = new String("rad");

System.out.println(s1+" " + s3);

if(s1==s3)

System.out.println("Equal");

else

System.out.println("Not equal");

if ( s1.equals(s3))

System.out.println("Equals");

if ( s1.equals(s2))

System.out.println("s1 s2 Equals");

}

}
 
 

import java.util.*;

class strtokens

{

public static void main(String a[])

{

StringBuffer s =new StringBuffer("tend");

s.toUpperCase();

System.out.println(s);

}

}
 
 

import java.util.*;

class strtokens

{

public static void main(String a[])

{

String s = "this . is . sample. text";

StringTokenizer st = new StringTokenizer(s,".");

while(st.hasMoreTokens())

{

String key = st.nextToken();

System.out.println(key);

}
 
 

}

}
 
 

import java.util.*;

class sys

{

public static void main(String s[])

{

String a[]={ "aa","bb","cc","dd","ee"};

String b[]={"xx","yy"};

System.arraycopy(a,2,b,0,2);

System.out.println(b);

}

}
 
 

import java.util.*;

class token

{

public static void main(String arg[])

{

String str = "This is a sample message";

StringTokenizer st = new StringTokenizer(str,"m");

while(st.hasMoreTokens())

{

String key = st.nextToken();

System.out.println(st.countTokens());

System.out.println(key);

}

}

}
 
 

import java.util.*;

class data

{

String name;

int age;

data(String n,int age1)

{

name=n;age=age1;

}

}

class vector

{

public static void main(String a[])

{

data ob1 = new data("Pal",26);

Vector v = new Vector(3,2);

Vector v1 = new Vector(3,2);

v1.addElement("s");

System.out.println(v.capacity());

v.addElement(ob1);

System.out.println("capa " +v.capacity());

System.out.println("size "+ v.size());

System.out.println("last ele "+ v.lastElement());

Iterator i = v.iterator();

while(i.hasNext())

{

data e = (data) i.next();

System.out.print(e.name + " " + e.age);

}

System.out.println("bef capa" + v.capacity());
 
 

}

}
 
 

import java.util.*;

class vector

{

public static void main(String a[])

{

Vector v = new Vector(3,2);

System.out.println(v.capacity());

v.add(new Integer(1));

v.addElement(new Integer(2));

v.addElement(new Integer(3));

v.addElement(new Integer(4));

v.addElement(new Integer(5));

v.addElement(new Integer(6));

v.addElement(new Integer(7));

v.addElement(new Integer(8));

System.out.println(v.elementAt(1));

System.out.println("capa" + v.capacity());

System.out.println("size" + v.size());

v.removeElementAt(3);

System.out.println("capa " +v.capacity());

System.out.println("size "+ v.size());

System.out.println("last ele "+ v.lastElement());

Iterator i = v.iterator();

while(i.hasNext())

{

Object e = i.next();

System.out.print(e);

}

System.out.println("bef capa" + v.capacity());

v.removeElementAt(3);

v.removeElementAt(3);

v.removeElementAt(3);

v.removeElementAt(3);

System.out.println("aft capa" + v.capacity());

v.trimToSize();

System.out.println("aft trim capa" + v.capacity());
 
 

}

}