Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
922 views

Java Lab Manual

This Java Lab Manual was used for all UG( B.Sc Computer Science, Information Technology, Computer Application) and PG(M.Sc Computer Science, Information Technology), MCA students.

Uploaded by

lakshmi.s
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
922 views

Java Lab Manual

This Java Lab Manual was used for all UG( B.Sc Computer Science, Information Technology, Computer Application) and PG(M.Sc Computer Science, Information Technology), MCA students.

Uploaded by

lakshmi.s
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 120

INDEX

S no: topics

FLOW CONTROLS
1. Odd Or Even
2. Biggest of Three Numbers
3. Fibonacci Series
4. Factorial of Numbers
5. Printing the Numbers
6. Arithmetic Operation Using Switch Case
CLASSES AND OBJECTS
7. Classes And Objects
8. Command line Arguments
9. Method Overloading
ARRAY
10. Sorting a List of Numbers – one Dimensional Array
11. Multiplication Table using Two Dimensional Array
STRINGS
12. Alphabetical ordering of Strings
INHERITANCE
14. Multilevel Inheritance

15. Multiple inheritance


EXCEPTION
16. Arithmetic Exception
17. Multiple catch Exception
18. User Defined Exception
THREAD

1
19. Multithread
LAYOUT
20. Border Layout
21. Grid Layout
GRAPHICAL USER INTERFACE
22. Text Event Using GUI
23. Button Event Using GUI
24. Label Event Using GUI
EVENT HANDLING
25. Key Event
26. Mouse Event
27. Event Handler Using Applet
IMAGES AND ANIMATION
28. Images
29. Animation
APPLET
30. Traffic Signal
31. Moving Ball
32. Bar Chart
33. Moon
34. Digital Clock
FILES MANAGEMENT
35. Creating a File
36. Deleting a File
37. Reading a File
SWINGS
38. Swings
JDBC

2
39. JDBC Connectivity
JAVASCRIPT
40. Arithmetic Operation
41. Prime Number
42. Largest Among Three Numbers
43. Palindrome

ODD OR EVEN
Source code:
import java.io.*;
class oddoreven
3
{
public static void main(String args[])
{
int a= 6;
if(a%2==0)
{
System.out.println("The number is a even");
}
else
{
System.out.println("The number is a odd ");
}
}
}

Output:

4
BIGGEST OF THREE NUMBERS

Source code:

5
import java.io.*;
class largest
{
public static void main(String args[])
{
int a=20,b=47,c=10;
if((a>b) && (a>c))
{
System.out.println("\t\t OUTPUT");
System.out.println("\t\t -------");
System.out.println(" ");
System.out.println("a is the largest number");
}
if((b>a) && (b>c))
{
System.out.println("\t\t OUTPUT");
System.out.println("\t\t -------");
System.out.println(" ");
System.out.println("b is the largest number");
}
else
{
System.out.println("\t\t OUTPUT");
System.out.println("\t\t -------");
System.out.println(" ");
System.out.println("c is the largest number");
}
6
}
}

Output:

FIBBONACCI SERIES

Source code:
import java.io.*;

7
class fibo
{
public static void main(String args[])
{
int n=50,t1=0,t2=1;
System.out.println(" ");
System.out.println("Numbers upto" +n+ ":");
System.out.println(" ");
while(t1<=n)
{
System.out.print(t1 +"\t");
int sum=t1+t2;
t1=t2;
t2=sum;
}
}
}

Output:

8
FACTORIAL OF NUMBERS

Source code:
import java.io.*;

9
class facto
{
public static void main(String args[])
{
int i,fact=1;
int num=6;
for(i=1;i<=num;i++)
{
fact=fact*i;
}
System.out.println("Factorial of"+num+"is:"+fact);
}
}

Output:

10
PRINTING THE NUMBERS
Source code:
import java.io.*;

11
public class printnumbers
{
public static void main(String[] args)
{
int i=1;
do{
System.out.println(i);
i++;
}
while(i<=10);
}
}

Output:

12
ARITHMETIC OPERATION USING SWITCH CASE
Source code:
import java.io.*;
class arithmetic

13
{
public static void main(String args[])
{
int a=5,b=3,c;
char choice;
System.out.println("choice----");
try
{
switch(choice = (char) System.in.read())
{
case '+':
c=a+b;
System.out.println("c:"+c);
break;
case '-':
c=a-b;
System.out.println("c:"+c);
break;
case '*':
c=a*b;
System.out.println("c:"+c);
break;
case '/':
c=a/b;
System.out.println("c:"+c);
break;
default:
14
System.out.println("not a number");
break;
}
}
catch (Exception e)
{
System.out.println("I/O error");
}
}
}

Output:

15
CLASSES AND OBJECTS
Source code:
class Rect1
{
int length,width;

16
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectarea()
{
int area=length*width;
return(area);
}
}
class rectarea
{
public static void main(String args[])
{
int area1,area2;
Rect1 R1=new Rect1();
Rect1 R2=new Rect1();
R1. length=15;
R1. width=10;
area1=R1.length*R1.width;
R2. getdata(20,12);
area2= R2.rectarea();
System.out.println("Area1= "+area1);
System.out.println("Area2= "+area2);
}
}
17
Output:

Command line arguments


Source code:
import java.io.*;
class commandline
{
public static void main(String args[])

18
{
int count,i=0;
String string;
count=args.length;
System.out.println("Number of Arguments="+count);
while(i<count)
{
string=args[i];
i=i+1;
System.out.println(i+":"+"java is "+string+"!");
}
}
}

Output:

19
Method overloading
Source code:
import java.io.*;
class Myclass
20
{
int height;
Myclass()
{
System.out.println("House");
height=8;
}
Myclass(int i)
{
System.out.println("It's very"+i);
height=i;
}
void info()
{
System.out.println("House is"+height+"feet tall");
}
void info(String s)
{
System.out.println(s+":House is"+height+"feet fall");
}
}
class Mainclass
{
public static void main(String args[])
{
Myclass t=new Myclass(0);
t.info();
21
t.info("Overloaded method");
new Myclass();
}
}

Output:

22
Sorting a list of numbers using one dimensional array
Source code:
import java.io.*;
class sort

23
{
public static void main(String args[])
throws IOException
{
int a[]=new int[10];
int n,i,j,t;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter n value:");
n=Integer.parseInt(br.readLine());
for(i=0;i<n;i++)
{
System.out.print("Enter a["+i+"]:");
a[i]=Integer.parseInt(br.readLine());
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
System.out.println("Ascending order:");

24
for(i=0;i<n;i++)
System.out.println(a[i]);
System.out.println();
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]<a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
System.out.println("Descending order:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}

Output:

25
Multiplication table using 2d array
Source code:
Import java.io.*;
class mul
{
final static int ROWS=20;

26
final static int COLUMNS=20;
public static void main(String args[])
{
int product[][]=new int[ROWS][COLUMNS];
int row,column;
System.out.println("MULTIPLICATION TABLE");
System.out.println("************************");
System.out.println(" ");
int i,j;
for(i=10;i<ROWS;i++)
{
for(j=10;j<COLUMNS;j++)
{
product[i][j]=i*j;
System.out.print(" "+product[i][j]);
}
System.out.println(" ");
}
}
}

Output:

27
Alphabetical ordering of strings
Source code:
import java.io.*;
class stringordering
{

28
static String name[]={"apple
","orange","pineapple","mango","pomegranate","kiwi","dragon fruit"};
public static void main(String args[])
{
int size=name.length;
String temp=null;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[j].compareTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}

Output:

29
Single inheritance
Source code:
import java.io.*;
class Room
{
int length;

30
int breadth;
Room(int x,int y)
{
length=x;
breadth=y;
}
int area()
{
return(length*breadth);
}
}
class BedRoom extends Room
{
int heigth;
BedRoom(int x,int y,int z)
{
super(x,y);
heigth=z;
}
int volume()
{
return(length*breadth*heigth);
}
}
class inhertest
{
public static void main(String args[])

31
{
BedRoom room1=new BedRoom(14,12,10);
int area1=room1.area();
int volume1=room1.volume();
System.out.println("Area1="+area1);
System.out.println("volume1="+volume1);
}
}

Output:

32
Multilevel inheritance
Source code:
import java.io.*;
class student
33
{
int rollnumber;
void getnumber(int a)
{
rollnumber=a;
}
void putnumber()
{
System.out.println("Rollno:"+rollnumber);
}
}
class test extends student
{
float sub1,sub2;
void getmarks(float x,float y)
{
sub1=x;
sub2=y;
}
void putmarks()
{
System.out.println("Marks Obtained");
System.out.println("sub1="+sub1);
System.out.println("sub2="+sub2);
}
}
class results extends test

34
{
float total;
void display()
{
total=sub1+sub2;
putnumber();
putmarks();
System.out.println("Total="+total);
}
}
class multilevel
{
public static void main(String args[])
{
results student1=new results();
student1.getnumber(111);
student1.getmarks(90.5f,95.6f);
student1.display();
}
}

Output:

35
Multiple inheritance
Source code:
import java.io.*;
class student
{

36
int rollnumber;
void getnumber(int n)
{
rollnumber=n;
}
void putnumber()
{
System.out.println("Rollno:"+rollnumber);
}
}
class test extends student
{
float part1,part2;
void getmarks(float m1,float m2)
{
part1=m1;
part2=m2;
}
void putmarks()
{
System.out.println("Marks Obtained");
System.out.println("part1="+part1);
System.out.println("part2="+part2);
}
}
interface Sports
{
float sportswt=6.0f;
void putwt();

37
}
class results extends test implements Sports
{
float total;
public void putwt()
{
System.out.println("Sports Wt="+sportswt);
}
void display()
{
total=part1+part2+sportswt;
putnumber();
putmarks();
putwt();
System.out.println("Total Score="+total);
}
}
class multiple
{
public static void main(String args[])
{
results student1=new results();
student1.getnumber(1234);
student1.getmarks(25.8f,33.0f);
student1.display();
}
}

38
Output:

Arithmetic exception

Source code:
import java.io.*;
class exception
{
public static void main(String args[])
{

39
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a/(b+c);
System.out.println("y="+y);
}
}

Output:

40
Multiple catch exception
Source code:
import java.io.*;
class exception1

41
{
public static void main(String args[])throws IOException
{
System.out.println("EXCEPTION HANDLINGS");
System.out.println("***************************");
try
{
int a=Integer.parseInt(args[0]);
int b=Integer.parseInt(args[1]);
System.out.println("QUOTIENT="+a/b);
}
catch(ArithmeticException e)
{
System.out.println("ERROR IN INDEX VALUE");
}
catch(NumberFormatException n)
{
System.out.println("DATA TYPE ERROR");
}
finally
{
System.out.println("FINALLY BLOCKED");
System.out.println("*****END*****");
}
}
}
Output:

42
User defined exception
Source code:
Import java.lang.Exception;

43
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5,y=1000;
try
{
float z=(float) x/(float) y;
if(z<0.01)
{
throw new MyException("Number is too small");
}
}
catch(MyException e)
{
System.out.println("Caught my Exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I am always here");
}

44
}
}

Output:

multithreaded

Source code:
45
import java.io.*;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("\t Form thread A:i="+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("\tForm thread B:j="+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
for(int k=1;k<=5;k++)
{

46
System.out.println("\tForm thread C:k="+k);
}
System.out.println("Exit from C");
}
}
class multithread
{
public static void main(String args[])
{
System.out.println("\n");
new A().start();
new B().start();
new C().start();
}
}

Output:

47
Border layout
Source code:
import java.awt.*;
import java.applet.*;

48
import java.awt.event.*;
public class border extends Applet
{
Button b1,b2,b3,b4;
public void init()
{
setBackground(Color.pink);
setLayout(new BorderLayout(5,6));
b1=new Button("Welcome to north");
b2=new Button("Welcome to south");
b3=new Button("Welcome to east");
b4=new Button("Welcome to west");
add((b1),BorderLayout.NORTH);
add((b2),BorderLayout.SOUTH);
add((b3),BorderLayout.EAST);
add((b4),BorderLayout.WEST);
}
public Insets getInset()
{
return new Insets(12,13,14,15);
}
}
HTML CODING

<html>
<head>
<applet code="border.class" height="200" width="200">
</applet>
</head>

49
</html>

Output:

grid layout
Source code:
import java.awt.*;
import java.applet.*;
public class gridlayout extends Applet
{

50
static final int n=4;
public void init()
{
setLayout(new GridLayout(n,n));
setFont(new Font("Times New Roman",Font.BOLD,26));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
int k=i*n+j;
if(k>0)
add(new Button(" "+k));
}
}
}
}

HTML CODING
<html>
<head>
<applet code="gridlayout.class" width="400" height="400">
</applet>
</head>
</html>

51
Output:

Text event using gui


Source code:
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements ActionListener
{
TextField tf1,tf2,tf3;

52
Button b1,b2,b3;
TextFieldExample()
{
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);
add(tf2);
add(tf3);
add(b1);
add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String s1=tf1.getText();
String s2=tf2.getText();

53
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1)
{
c=a+b;
}
else if(e.getSource()==b2)
{
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String args[])
{
new TextFieldExample();
}
}

Output:

54
Button event using gui
Source code:
import java.awt.*;
import java.awt.event.*;

55
public class ButtonDemo extends Frame implements ActionListener
{
Button rb,gb,bb;
public ButtonDemo()
{
FlowLayout fl=new FlowLayout();
setLayout(fl);

rb=new Button("Red");
gb=new Button("Green");
bb=new Button("Blue");

rb.addActionListener(this);
gb.addActionListener(this);
bb.addActionListener(this);

add(rb);
add(gb);
add(bb);

setTitle("Button in action");
setSize(300,300);
setVisible(true);
}

public void actionPerformed(ActionEvent e)


{

56
String str=e.getActionCommand();
System.out.println("you clicked"+str+"button");

if(str.equals("Red"))
{
setBackground(Color.red);
}
else if(str.equals("Green"))
{
setBackground(Color.green);
}
else if(str.equals("Blue"))
{
setBackground(Color.blue);
}
}

public static void main(String args[])


{
new ButtonDemo();
}
}

Output:

57
58
Lable event using gui
Source code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class Applet3 extends Applet implements ActionListener, ItemListener


{
Label label1,label2,label3;
TextField tf1,tf2,tf3;
59
public void init()
{
System.out.println("Initializing an applet");
label1=new Label("\n\n\t Enter your name");
tf1=new TextField(10);

label2=new Label("\n\t Enter your city");


tf2=new TextField(10);

add(label1);
add(tf1);

add(label2);
add(tf2);

tf1.addActionListener(this);
tf2.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)


{
repaint();
}

public void itemStateChanged(ItemEvent ie)


{
repaint();
}
public void paint(Graphics g)

60
{
g.drawString("Your name is"+tf1.getText(),10,150);
g.drawString("Your city is"+tf2.getText(),10,170);
}}

HTML CODING
<html>
<head>
<applet code="Applet3.class" width="300" height="300">
</applet>
</head>
</html>

Output:

61
Key event
Source code:
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Adapkey extends Applet
{
public void init()
{
addKeyListener(new MyKeyAdapter(this));
}
}
62
class MyKeyAdapter extends KeyAdapter
{
Adapkey ak;
public MyKeyAdapter(Adapkey ak)
{
this.ak=ak;
}
public void keyReleased(KeyEvent ke)
{
ak.showStatus("keyReleased");
}
public void keyPressed(KeyEvent ke)
{
ak.showStatus("keyPressed");
}
}import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
public class Adapkey extends Applet
{
public void init()
{
addKeyListener(new MyKeyAdapter(this));
}
}
class MyKeyAdapter extends KeyAdapter
{
63
Adapkey ak;
public MyKeyAdapter(Adapkey ak)
{
this.ak=ak;
}
public void keyReleased(KeyEvent ke)
{
ak.showStatus("keyReleased");
}
public void keyPressed(KeyEvent ke)
{
ak.showStatus("keyPressed");
}
}

HTML CODING
<html>
<head>
<applet code="Adapkey.class" height=200 width=250>
</applet>
</head>
</html>

Output:

64
Mouse event
Source code:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseEvents extends Applet implements
MouseListener,MouseMotionListener
{
String msg="";
int MouseX=0;

65
int MouseY=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
MouseX=0;
MouseY=10;
msg="Mouse Clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
MouseX=0;
MouseY=10;
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
MouseX=0;
MouseY=10;
msg="Mouse Exited";
repaint();
}
66
public void mousePressed(MouseEvent me)
{
MouseX=me.getX();
MouseY=me.getY();
msg="Down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
MouseX=me.getX();
MouseY=me.getY();
msg="Up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
MouseX=me.getX();
MouseY=me.getY();
msg="*";
showStatus("Dragging mouse at"+me.getX()+","+me.getY());
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("Moving mouse at"+me.getX()+","+me.getY());
}
public void paint(Graphics g)
67
{
g.drawString(msg,MouseX,MouseY);
}
}

HTML CODING
<html>
<head>
<applet code="MouseEvents.class"height=200 width=250>
</applet>
</head>
</html>

Output:

68
images
Source code:
69
/*<applet code="ImageDemo.class" width="1250"height="800"> </applet>*/

import java.awt.*;
import java.applet.*;

public class ImageDemo extends Applet


{
Image picture;
public void init()
{
picture=getImage(getDocumentBase(),"Penguins.jpg");
}

public void paint(Graphics g)


{
g.drawImage(picture,50,50,this);
}

70
Output:

71
animation
Source code:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class tutorial extends JPanel implements ActionListener
{
Timer tm = new Timer(10,this);
int x = 90,velX = 120;
public void paintComponent(Graphics g)
{
super.paintComponent(g);

g.setColor(Color.RED);
g.fillRect(100,x,50,160);
tm.start();
}
public void actionPerformed(ActionEvent e)
{
if(x < 90|| x > 540)
velX = -velX;

x = x + velX;
repaint();
}
public static void main(String[] args)
{
tutorial t= new tutorial();
JFrame jf=new JFrame();
jf.setTitle("Tutorial");
jf.setSize(900,600);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}

72
Output:

73
74
Event handler using applet
Source code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);
add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
HTML CODING
<html>
<head>
<applet code="EventApplet.class" width="300" height="300">
</applet>
</head>

75
</html>
Output:

76
Traffic signal
Source code:
import java.applet.*;
import java.awt.*;
import java.applet.Applet;
public class traffic extends Applet
{
public void paint(Graphics g)
{
int n=4;
int x[]={160,160,300,300};
int y[]={20,450,450,20};
g.setColor(Color.black);
g.fillPolygon(x,y,n);
g.setColor(Color.red);
g.fillOval(180,50,100,100);
g.setColor(Color.yellow);
g.drawString("STOP",210,105);
g.setColor(Color.orange);
g.fillOval(180,175,100,100);
g.setColor(Color.white);
g.drawString("LISTEN",210,230);
g.setColor(Color.green);
g.drawOval(180,300,100,100);
g.fillOval(180,300,100,100);
g.setColor(Color.white);
g.drawString("PROCEED",200,360);
g.setColor(Color.black);

77
int a[]={255,255,250,250};
int b[]={450,575,575,450};
g.fillPolygon(a,b,n);
g.setColor(Color.black);
int c[]={200,250,250,200};
int d[]={400,575,400,575};
g.fillPolygon(c,d,n);
}
}

HTML CODING
<html>
<head>
<applet code="traffic.class" width="250" height="200">
</applet>
</head>
</html>

78
Output:

79
Moving ball
Source code:
import java.applet.*;
import java.awt.*;
public class ball extends Applet implements Runnable
{
Thread t;
int x=0;
int y=0;
public void start()
{
t=new Thread(this);
t.start();
}
public void paint(Graphics g)
{
g.fillOval(x,y,100,100);
}
public void run()
{
try
{
for(;;)
{
for(;;)
{
if(y==120)

80
{
break;
}
else if(x==390)
{
x=0;
y=0;
repaint();
}
else
{
y=y+3;
x=x+3;
Thread.sleep(100);
repaint();
}
}
for(;;)
{
if(y==0)
{
break;
}
else if(x==390)
{
x=0;
y=0;
repaint();
}

81
else
{
y=y-3;
x=x+3;
Thread.sleep(100);
repaint();
}
}
run();
}
}
catch (InterruptedException e)
{
}
}
}

HTML CODING
<html>
<head>
<applet code="ball.class" height="200" width="200">
</applet>
</head>
</html>

Output:
82
Bar chart
83
Source code:
import java.awt.*;
import java.applet.*;
public class barchart extends Applet
{
int n=0;
String label[];
int value[];
public void init()
{
try
{
n=Integer.parseInt(getParameter("Columns"));
label=new String[n];
value=new int[n];
label[0]=getParameter("label1");
label[1]=getParameter("label2");
label[2]=getParameter("label3");
label[3]=getParameter("label4");
value[0]=Integer.parseInt(getParameter("c1"));
value[1]=Integer.parseInt(getParameter("c2"));
value[2]=Integer.parseInt(getParameter("c3"));
value[3]=Integer.parseInt(getParameter("c4"));
}
catch(NumberFormatException e){}
}
public void paint(Graphics g)
{
for(int i=0;i<n;i++)

84
{
g.setColor(Color.red);
g.drawString(label[i],20,i*50+30);
g.fillRect(50,i*50+10,value[i],40);
}
}
}

HTML CODING
<html>
<head>
<applet code="barchart.class" width="200" height="200">
<param name="Columns" value="4">
<param name="c1" value="110">
<param name="c2" value="150">
<param name="c3" value="100">
<param name="c4" value="170">
<param name="label1" value="91">
<param name="label2" value="92">
<param name="label3" value="93">
<param name="label4" value="94">>
</applet>
</head>
</html>

85
Output:

moon
Source code:
import java.awt.*;

86
import java.applet.*;
import java.awt.event.*;
public class moon extends Applet implements Runnable
{
int a1,a=400,b=100;
char c1;
Thread th;
public void init()
{
setBackground(Color.black);
th=new Thread(this);
th.start();
}
public void run()
{
while(true)
{
try
{
th.sleep(1000);
}
catch(Exception e)
{
}
repaint();
}
}
public void paint(Graphics g)
{

87
g.setColor(Color.white);
g.fillOval(350,150,50,50);
g.drawString("*",50,50);
g.drawString("*",50,50);
g.drawString("*",75,100);
g.drawString("*",120,120);
g.drawString("*",90,230);
g.drawString("*",550,200);
g.drawString("*",650,300);
g.drawString("*",310,150);
g.drawString("*",650,150);
g.setColor(Color.black);
g.fillOval(a,b,50,50);
if(a<=350)
a=400;
else
a=a-5;
if(b<=150)
b=100;
else
b=b+5;
}
}

HTML CODING
<html>
<head>
<applet code="moon.class" height=400 width=400>
88
</applet>
</head>
</html>

Output:

Digital clock
Source code:
import java.applet.*;
import java.awt.*;
import java.util.*;
89
import java.text.*;
public class digitalclock extends Applet implements Runnable
{
Thread t=null;
int hours=0,minutes=0,seconds=0;
String timeString="";
public void init()
{
setBackground(Color.pink);
}
public void start()
{
t=new Thread(this);
t.start();
}
public void run() {
try {
while(true) {
Calendar cal=Calendar.getInstance();
hours=cal.get(Calendar.HOUR_OF_DAY);
if(hours>12)hours-=12;
minutes=cal.get(Calendar.MINUTE);
seconds=cal.get(Calendar.SECOND);
SimpleDateFormat formatter=new SimpleDateFormat("hh:mm:ss");
Date date=cal.getTime();
timeString=formatter.format(date);
repaint();
t.sleep(1000);
}

90
}
catch(Exception e){}
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawString(timeString,50,50);
}
}

HTML CODING
<html>
<head>
<applet code="digitalclock.class" width="300" height="300">
</applet>
</head>
<html>

Output:

91
Creating a file
Source code:
import java.io.File;

92
import java.io.IOException;

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("java.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

Output:

93
deleting a file
Source code:

import java.io.File;

94
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("java.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}

Output:

Reading a file
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

95
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("cs.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Output:

swings
Source code:

import javax.swing.*;
import java.awt.*;

96
import java.awt.event.*;

class MyFrame
extends JFrame
implements ActionListener {

private Container c;
private JLabel title;
private JLabel name;
private JTextField tname;
private JLabel mno;
private JTextField tmno;
private JLabel gender;
private JRadioButton male;
private JRadioButton female;
private ButtonGroup gengp;
private JLabel dob;
private JComboBox date;
private JComboBox month;
private JComboBox year;
private JLabel add;
private JTextArea tadd;
private JCheckBox term;
private JButton sub;
private JButton reset;
private JTextArea tout;
private JLabel res;
private JTextArea resadd;

97
private String dates[]
= { "1", "2", "3", "4", "5",
"6", "7", "8", "9", "10",
"11", "12", "13", "14", "15",
"16", "17", "18", "19", "20",
"21", "22", "23", "24", "25",
"26", "27", "28", "29", "30",
"31" };
private String months[]
= { "Jan", "feb", "Mar", "Apr",
"May", "Jun", "July", "Aug",
"Sup", "Oct", "Nov", "Dec" };
private String years[]
= { "1995", "1996", "1997", "1998",
"1999", "2000", "2001", "2002",
"2003", "2004", "2005", "2006",
"2007", "2008", "2009", "2010",
"2011", "2012", "2013", "2014",
"2015", "2016", "2017", "2018",
"2019" };

public MyFrame()
{
setTitle("Registration Form");
setBounds(300, 90, 900, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);

98
c = getContentPane();
c.setLayout(null);

title = new JLabel("Registration Form");


title.setFont(new Font("Arial", Font.PLAIN, 30));
title.setSize(300, 30);
title.setLocation(300, 30);
c.add(title);

name = new JLabel("Name");


name.setFont(new Font("Arial", Font.PLAIN, 20));
name.setSize(100, 20);
name.setLocation(100, 100);
c.add(name);

tname = new JTextField();


tname.setFont(new Font("Arial", Font.PLAIN, 15));
tname.setSize(190, 20);
tname.setLocation(200, 100);
c.add(tname);

mno = new JLabel("Mobile");


mno.setFont(new Font("Arial", Font.PLAIN, 20));
mno.setSize(100, 20);
mno.setLocation(100, 150);
c.add(mno);

tmno = new JTextField();

99
tmno.setFont(new Font("Arial", Font.PLAIN, 15));
tmno.setSize(150, 20);
tmno.setLocation(200, 150);
c.add(tmno);

gender = new JLabel("Gender");


gender.setFont(new Font("Arial", Font.PLAIN, 20));
gender.setSize(100, 20);
gender.setLocation(100, 200);
c.add(gender);

male = new JRadioButton("Male");


male.setFont(new Font("Arial", Font.PLAIN, 15));
male.setSelected(true);
male.setSize(75, 20);
male.setLocation(200, 200);
c.add(male);

female = new JRadioButton("Female");


female.setFont(new Font("Arial", Font.PLAIN, 15));
female.setSelected(false);
female.setSize(80, 20);
female.setLocation(275, 200);
c.add(female);

gengp = new ButtonGroup();


gengp.add(male);
gengp.add(female);

100
dob = new JLabel("DOB");
dob.setFont(new Font("Arial", Font.PLAIN, 20));
dob.setSize(100, 20);
dob.setLocation(100, 250);
c.add(dob);

date = new JComboBox(dates);


date.setFont(new Font("Arial", Font.PLAIN, 15));
date.setSize(50, 20);
date.setLocation(200, 250);
c.add(date);

month = new JComboBox(months);


month.setFont(new Font("Arial", Font.PLAIN, 15));
month.setSize(60, 20);
month.setLocation(250, 250);
c.add(month);

year = new JComboBox(years);


year.setFont(new Font("Arial", Font.PLAIN, 15));
year.setSize(60, 20);
year.setLocation(320, 250);
c.add(year);

add = new JLabel("Address");


add.setFont(new Font("Arial", Font.PLAIN, 20));
add.setSize(100, 20);
add.setLocation(100, 300);
c.add(add);

101
tadd = new JTextArea();
tadd.setFont(new Font("Arial", Font.PLAIN, 15));
tadd.setSize(200, 75);
tadd.setLocation(200, 300);
tadd.setLineWrap(true);
c.add(tadd);

term = new JCheckBox("Accept Terms And Conditions.");


term.setFont(new Font("Arial", Font.PLAIN, 15));
term.setSize(250, 20);
term.setLocation(150, 400);
c.add(term);

sub = new JButton("Submit");


sub.setFont(new Font("Arial", Font.PLAIN, 15));
sub.setSize(100, 20);
sub.setLocation(150, 450);
sub.addActionListener(this);
c.add(sub);

reset = new JButton("Reset");


reset.setFont(new Font("Arial", Font.PLAIN, 15));
reset.setSize(100, 20);
reset.setLocation(270, 450);
reset.addActionListener(this);
c.add(reset);

tout = new JTextArea();

102
tout.setFont(new Font("Arial", Font.PLAIN, 15));
tout.setSize(300, 400);
tout.setLocation(500, 100);
tout.setLineWrap(true);
tout.setEditable(false);
c.add(tout);

res = new JLabel("");


res.setFont(new Font("Arial", Font.PLAIN, 20));
res.setSize(500, 25);
res.setLocation(100, 500);
c.add(res);

resadd = new JTextArea();


resadd.setFont(new Font("Arial", Font.PLAIN, 15));
resadd.setSize(200, 75);
resadd.setLocation(580, 175);
resadd.setLineWrap(true);
c.add(resadd);

setVisible(true);
}

public void actionPerformed(ActionEvent e)


{
if (e.getSource() == sub) {
if (term.isSelected()) {
String data1;

103
String data
= "Name : "
+ tname.getText() + "\n"
+ "Mobile : "
+ tmno.getText() + "\n";
if (male.isSelected())
data1 = "Gender : Male"
+ "\n";
else
data1 = "Gender : Female"
+ "\n";
String data2
= "DOB : "
+ (String)date.getSelectedItem()
+ "/" + (String)month.getSelectedItem()
+ "/" + (String)year.getSelectedItem()
+ "\n";

String data3 = "Address : " + tadd.getText();


tout.setText(data + data1 + data2 + data3);
tout.setEditable(false);
res.setText("Registration Successfully..");
}
else {
tout.setText("");
resadd.setText("");
res.setText("Please accept the"
+ " terms & conditions..");
}

104
}

else if (e.getSource() == reset) {


String def = "";
tname.setText(def);
tadd.setText(def);
tmno.setText(def);
res.setText(def);
tout.setText(def);
term.setSelected(false);
date.setSelectedIndex(0);
month.setSelectedIndex(0);
year.setSelectedIndex(0);
resadd.setText(def);
}
}
}

class Registration {

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


{
MyFrame f = new MyFrame();
}
}
Output:

105
Jdbc connectivity
Source code:

106
import java.awt.*;
import java.awt.event.*;
import.java.sql.*;
public class INS extends Frame implements ActionListener{
Frame f;
Label l1,l2;
TextField t1,t2;
Button b1,b2,b3,b4,b5;
Connection c;
Statement s;
ResultSet r;
INS(){
try{
f=new Frame();
f.setLayout(null);
f.setVisible(true);
f.setSize(800,600);
l1=new Label("ID");
l1.setBounds(50,100,100,50);
f.add(l1);
l2=new Label("Name");
l2.setBounds(50,150,100,50);
f.add(l2);
t1=new TextField();
t1.setBounds(150,100,100,40);
f.add(t1);
t2=new TextField();

107
t2.setBounds(150,150,100,40);
f.add(t2);
b1=new Button("INSERT");
b1.setBounds(200,300,75,50);
f.add(b1);
b1.addActionListener(this);
b2=new Button("UPDATE");
b2.setBounds(300,300,75,50);
f.add(b2);
b2.addActionListener(this);
b3=new Button("DELETE");
b3.setBounds(400,300,75,50);
f.add(b3);
b3.addActionListener(this);
b5=new Button("EXIT");
b5.setBounds(600,300,75,50);
f.add(b5);
b5.addActionListener(this);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
c=DriverManager.getConnection("jdbc:odbc:ADB");
s=c.createStatement();
}catch(Exception e){}
}
public void actionPerformed(ActionEvent ae){
try{
if(ae.getSource()==b1){
String s1="INSERT INTO USER(id,name)VALUES("+t1.getText()
+",'"+t2.getText() + "')";

108
System.out.println(s1);
s.executeUpdate(s1);
r=s.excuteQuery("SELECT * FROM USER");
t1.setText("");
t2.setText("");
}else if(ae.getSource()==b2){
String s2="UPDATE USER SET NAME=' "+t2.getText()+" 'WHERE
ID="+t1.getText();
System.out.println(s2);
s.executeUpdate(s2);
r=s.excuteQuery("SELECT * FROM USER");
t1.setText("");
t2.setText("");
}else if(ae.getSource()==b3){
String s3="DELETE FROM USER WHERE ID="+t1.getText();
System.out.println(s3);
s.executeUpdate(s3);
r=s.excuteQuery("SELECT * FROM USER");
t1.setText("");
t2.setText("");
}else if(ae.getSource()==b5){
c.clpose();
f.dispose();
}
}catch(Exception e){}
}
public static void main(String args[]){
new INS();

109
}
}

Output:

Arithmetic operation using java script


Source code:
<!DOCTYPE html>

110
<html>
<head>
<title>JAVASCRIPT ARITHMETIC OPERATORS</title>
</head>
<body>
<h1>Performing Arithmetic Operation</h1>
<script>
var a=12,b=3;
var addition,subtraction,multiplication,division,modulus;
addition = a+b;
subtraction = a-b;
division = a/b;
multiplication = a*b;
modulus = a%b;
document.write("Addition of " +a+ "and" +b+ "is=" +addition+ "<br>");
document.write("subtraction of " +a+ "and" +b+ "is=" +subtraction+ "<br>");
document.write("multiplication of "+a+"and"+b+"is=" +multiplication+
"<br>");
document.write("division of " +a+ "and" +b+ "is=" +division+ "<br>");
document.write("modulus of " +a+ "and" +b+ "is=" +modulus+ "<br>");
</script>
</body>
</html>

Output:

111
Prime number using javascript
Source code:

112
<!DOCTYPE html>
<html>
<head>
<title>
Check a number is Prime or
not using JavaScript
</title>

<script type="text/javascript">

function p() {

var n, i, flag = true;

n = document.myform.n.value;
n = parseInt(n)
for(i = 2; i <= n - 1; i++)
if (n % i == 0) {
flag = false;
break;
}

if (flag == true)
alert(n + " is prime");
else
alert(n + " is not prime");
113
}
</script>
</head>

<body>
<center>
<h1>JAVASCRIPT</h1>

<h4>check number is prime or not</h4>

<hr color="Green">

<form name="myform">
Enter the number:
<input type="text" name=n value="">

<br><br>

<input type="button" value="Check" onClick="p()">


<br>
</form>
</center>
</body>

</html>

Output:

114
Largest among three numbers
Source code:
<html>

115
<head>
<script>
function largest()
{
var num1, num2, num3;
num1 = Number(document.getElementById("N").value);
num2 = Number(document.getElementById("M").value);
num3 = Number(document.getElementById("O").value);

if(num1>num2 && num1>num3)


{
window.alert(num1+"-is greatest");
}
else if(num2>num1 && num2>num3)
{
window.alert(num2+"-is greatst");
}
else if(num3>num1 && num3>num1)
{
window.alert(num3+"is greatest");
}
}
</script>
</head>
<body>
<h1>Calculate largest among three numbers</h1>
<hr color="cyan">
<br>
Enter number 1: <input type="text" id="N"></input><br>

116
Enter number 2: <input type="text" id="M"></input><br>
Enter number 3: <input type="text" id="O"></input><br>
<hr color="cyan">
<center><button onclick="largest()">OK</button>
</body>
</html>

Output:

Palindrome using javascript


Source code:
<!doctype html>
<html>

117
<head>
<script>
function palin()
{
var a,no,b,temp=0;

no=Number(document.getElementById("no_input").value);

b=no;
while(no>0)
{
a=no%10;
no=parseInt(no/10);
temp=temp*10+a;
}
if(temp==b)
{
alert("Palindrome number");
}
else
{
alert("Not Palindrome number");
}
}
</script>
</head>
<body>
Enter any Number: <input id="no_input">
<button onclick="palin()">Check</button></br></br>

118
</body>
</html>

Output:

119
120

You might also like