1-D
1class D1
2{
3public static void main(String[] args)
4{
5int month_days[];
6month_days=new int[12];
7month_days[0]=31;
8month_days[1]=28;
9month_days[2]=31;
10month_days[3]=30;
11month_days[4]=31;
12month_days[5]=30;
13month_days[6]=31;
14month_days[7]=31;
15month_days[8]=30;
16month_days[9]=31;
17month_days[10]=30;
18month_days[11]=31;
19System.out.println("january has:"+month_days[0]+"days");
20}
21}
2-D
1class TwoDArray
2{
3
4public static void main(String [] args)
5{
6int twoD[][]=new int[4][5];
7int i,j,k=0;
8for(i=0;i<4;i++)
9for(j=0;j<5;j++)
10{
11twoD[i][j]=k;
12k++;
13}
14for(i=0;i<4;i++)
15{
16for(j=0;j<5;j++)
17{
18System.out.print(twoD[i][j]+" ");
19}
20System.out.println( );
21}
22}
3-D
1class ThreeDArray
2{
3public static void main(String[] args)
4{
5int threeD[][][]=new int[3][4][5];
6int i,j,k;
7for(i=0;i<3;i++)
8for(j=0;j<4;j++)
9for(k=0;k<5;k++)
10threeD[i][j][k]=i*j*k;
11for(i=0;i<3;i++)
12{
13for(j=0;j<4;j++)
14{
15for(k=0;k<5;k++)
16{
17System.out.print(threeD[i][j][k]+" ");
18}
19System.out.println();
20
21}
22System.out.println();
23}
24}
25}
Abstract class
1abstract class Figure
2{
3double dim1,dim2;
4Figure(double a,double b)
5{
6dim1=a;
7dim2=b;
8}
9
10//area is now an abstract method
11abstract double area();
12}
13class Rectangle extends Figure
14{
15Rectangle(double a,double b)
16{
17super(a,b);
18}
19//override area for rectangle
20double area()
21{
22System.out.println("Inside Area for Rectangle:");
23return dim1*dim2;
24}
25}
26class Triangle extends Figure
27{
28Triangle(double a, double b)
29{
30super(a,b);
31}
32//override area for right triangle
33double area()
34
35{
36System.out.println("Inside Area for Triangle");
37return dim1*dim2/2;
38}
39}
40class AbstractAreas
41{
42public static void main(String args[])
43{
44//Figure f=new Figure(10,10);//illegal now
45Rectangle r=new Rectangle(9,5);
46Triangle t=new Triangle(10,8);
47Figure figref;//this is OK,no object is created
48figref=r;
49System.out.println("Area is:"+figref.area());
50figref=t;
51System.out.println("Area is"+figref.area());
52}
53}
Adapter Class
1/*6. Write a Java program to illustrate adapter class. */
2Import java.awt.*;
3Import java.awt.event.*;
4Import java.applet.*;
5/*<applet code=”AdapterDemo” width=500 height=500>
6</applet>
7*/
8Public class AdapterDemo extends Applet
9{
10Public void init()
11{
12addMouseListener(new MyMouseAdapter(this));
13addMouseMotionListener(new MyMouseMotionAdapter(this));
14}
15}
16
17Class MyMouseAdapter extends MouseAdapter
18{
19AdapterDemo adapterDemo;
20Public MyMouseAdapter(AdapterDemo adapterDemo)
21{
22this.adapterDemo=adapterDemo;
23}
24Public void mouseClicked(MouseEvent me)
25{
26adapterDemo.showStatus(“Mouse Clicked”);
27}
28}
29Class MyMouseMotionAdapter extends MouseMotionAdapter
30{
31AdapterDemo adapterDemo;
32Public MyMouseMotionAdapter(AdapterDemo adapterDemo)
33{
34this.adapterDemo=adapterDemo;
35}
36Public void mouseDragged(MouseEvent me)
37{
38adapterDemo.showStatus(“Mouse Dragged”);
39}
40}
Classes and Objects in Java
1class Box
2{
3double w,h,d;
4}
5class BoxDemo
6{
7public static void main(String[] args)
8{
9Box mybox=new Box();
10double volume;
11mybox.w=10;
12mybox.h=10;
13mybox.d=10;
14
15volume=mybox.h*mybox.d*mybox.w;
16System.out.println("volume=:"+volume);
17}
18
19}
Methods in Java
1class Box
2{
3double width,height,depth;
4void volume()
5{
6System.out.println("volume is:");
7System.out.println(width*height*depth);
8}}
9class BoxDemo3
10{
11public static void main(String[] args)
12{
13Box mybox1=new Box();
14Box mybox2=new Box();
15mybox1.width=10;
16mybox1.height=20;
17mybox1.depth=15;
18mybox2.width=3;
19
20mybox2.height=6;
21mybox2.depth=9;
22mybox1.volume();
23mybox2.volume();
24
25}
26}
Inner Class
1class Outer
2{
3int outer_x=100;
4void test()
5{
6Inner inner=new Inner();
7inner.display();
8}
9class Inner
10{
11void display()
12{
13System.out.println("display:outer_x="+outer_x);
14}
15}
16}
17class InnerClass
18{
19public static void main(String[] args)
20{
21Outer outer =new Outer();
22outer.test();
23}
24
25}
MultiLevel Inheritance
1class A
2{
3 int a;
4 void showA()
5 {
6 System.out.println("a:"+a);
7 }
8}
9class B extends A
10{
11 int b;
12 void showB()
13 {
14 System.out.println("b:"+b);
15 }
16}
17class C extends B
18{
19 int c;
20 void showC()
21 {
22 System.out.println("c:"+c);
23 }
24}
25class MultiLvlInheritance
26{
27 public static void main(String args[])
28 {
29 A ob = new A();
30 ob.a = 10;
31 ob.showA();
32 C ob1 = new C();
33 ob1.a= 12;
34 ob1.b = 15;
35 ob1.c = 18;
36 ob1.showA();
37 ob1.showB();
38 ob1.showC();
39 }
40}
Overriding
1class A
2{
3
4int i,j;
5A(int a,int b)
6{
7i=a;
8j=b;
9}
10void show()
11{
12System.out.println("i and j:"+i+""+j);
13}
14}
15class B extends A
16{
17int k;
18B(int a,int b,int c)
19{
20super(a,b);
21k=c;
22}
23void show()
24{
25super.show();
26System.out.println("k:"+k);
27}
28
29}
30class Override
31{
32public static void main(String[] args)
33{
34B subob=new B(1,2,3);
35subob.show();
36}
37}
Overload
1class OverLoad
2{
3void test()
4 {System.out.println("No parameters");
5 }
6void test(int a)
7{
8 System.out.println("a="+a);
9}
10void test(int a , int b)
11{
12 System.out.println("a and b:"+a+" & "+b);
13}
14double test(double a)
15{
16 System.out.println("double a :"+a);
17 return a*a;
18}
19}
20class OverLoadDemo
21{
22 public static void main(String args[])
23 {
24 OverLoad ob = new OverLoad();
25 double result;
26 ob.test();
27 ob.test(10);
28 ob.test(10,20);
29 result= ob.test(123.4);
30 System.out.println("Result of ob.test(123.4:)"+result);
31 }
32}
Call By Reference
1class Test
2{
3 int a,b;
4 Test(int i, int j)
5 {
6 a=i;
7 b=j;
8 }
9 void meth(Test o)
10 {o.a*=2;
11 o.b/=2;
12 }
13}
14class CallByRef
15{
16 public static void main(String args[])
17 {
18 Test ob = new Test(15,20);
19 System.out.println("ob.a and ob.b before call:"+ob.a+" "+ob.b);
20 ob.meth(ob);
21 System.out.println("ob.a and ob.b after call:"+ob.a+" "+ob.b);
22 }
23
24}
Return an Object
1class Test
2{
3 int a;
4 Test(int i)
5 {
6 a=i;
7 }
8 Test incrByten()
9 {
10 Test temp = new Test(a+10);
11 return temp;
12 }
13}
14class RetrOb
15{
16 public static void main(String args[])
17 {
18 Test ob1 = new Test(2);
19 Test ob2;
20 ob2 = ob1.incrByten();
21 System.out.println("ob1.a:"+ob1.a);
22 System.out.println("ob2.a:"+ob2.a);
23 ob2 = ob2.incrByten();
24 System.out.println("ob2.a after second increment:"+ob2.a);
25 }
26}
Reccursion
1class factorial{
2 int fact(int n)
3 {
4 if(n==1)
5 return 1;
6
7 else
8 return (fact(n-1)*n);
9 }
10 public static void main(String args[]){
11 factorial f=new factorial();
12 System.out.println("factorial of 3 is:"+f.fact(3));
13 System.out.println("factorial of 10 is:"+f.fact(10));
14 }
15}
Passing object as a Parameter
1class Test {
2 int a, b;
3
4 Test(int i, int j) {
5 a = i;
6 b = j;
7
8 }
9
10 Boolean equals(Test o) {
11 if (o.a == a && o.b == b) {
12 return true;
13 } else {
14 return false;
15 }
16 }
17}
18
19class Passob {
20 public static void main(String[] args) {
21 Test ob1 = new Test(100, 22);
22 Test ob2 = new Test(100, 22);
23 Test ob3 = new Test(-1, -1);
24 System.out.println("ob1==ob2" + ob1.equals(ob2));
25 System.out.println("ob1==ob3" + ob1.equals(ob3));
26 }
27}
Multiple Inheritance Using Interface
1interface I {
2 void meth();
3}
4
5class A {
6 void meth1() {
7 System.out.println("defined in class A");
8 }
9
10}
11
12class B extends A implements I {
13 public void meth() {
14 System.out.println("defined in class B");
15 }
16}
17
18class MultiInheritance {
19 public static void main(String[] args) {
20 B ob = new B();
21 ob.meth();
22 ob.meth1();
23 }
24}
Single Level Inheritance
1class A
2{
3int i,j;
4void showij()
5{
6System.out.println("i and j:"+i+" "+j);
7}
8}
9//create a subclass by extending class A
10class B extends A
11{
12int k;
13
14void showk()
15{
16System.out.println("k:"+k);
17}
18void sum()
19{
20System.out.println("i+j+k:"+(i+j+k));
21}
22}
23class SimpleInheritance
24{
25public static void main(String args[])
26{
27A superob=new A();
28B subob=new B();
29//The superclass may be used by itself
30superob.i=10;
31superob.j=20;
32System.out.println("Contents of superob:");
33superob.showij();
34System.out.println();
35/*The subclass has access to all public members of its
36superclass*/
37subob.i=7;
38
39subob.j=8;
40subob.k=9;
41System.out.println("Contents of subob:");
42subob.showij();
43subob.showk();
44System.out.println("Sum of i,j&k in subob");
45subob.sum();
46}
47}
Static Keyword
1class StaticDemo
2{
3static int a=10;
4
5static int b;
6static void meth(int x)
7{
8System.out.println("x="+x);
9System.out.println("a="+a);
10System.out.println("b="+b);
11}
12static
13{
14System.out.println("static block initialized");
15b=a*4;
16}
17public static void main(String[] args)
18{
19meth(20);
20}
21}
String class
1class stringTest {
2 public static void main(String[] args) {
3 String s = "welcome to java programming";
4 System.out.println(s);
5 System.out.println("string length=" + s.length());
6 System.out.println("character at 3rd position=" + s.charAt(3));
7 System.out.println(s.substring(3));
8 System.out.println("substring=" + s.substring(2, 5));
9 String s1 = "java";
10 String s2 = "programming";
11 System.out.println("concatenated string=" + s1.concat(s2));
12 String s4 = "learn code learn";
13 System.out.println("Index of Learn" + s4.indexOf("Learn"));
14 System.out.println("Index of a=" + s4.indexOf('a', 3));
15 Boolean out = "java".equals("java");
16 System.out.println("checking equality" + out);
17 out = "Java".equalsIgnoreCase("java");
18 System.out.println("checking equality" + out);
19 int out1 = s1.compareTo(s2);
20 System.out.println("the difference between ASCII values is" + out1);
21 String word1 = "JAVA PROGRAMMING";
22 System.out.println("changing to lower case" + word1.toLowerCase());
23 String word2 = "java programming";
24 System.out.println("changing to upper case:" + word2.toUpperCase());
25 String str1 = "frogramming";
26 System.out.println("original string" + str1);
27 String str2 = "frogramming".replace('f', 'p');
28 System.out.println("replaced f with p" + str2);
29
30 }
31}
Super Keyword(to access super class constructor.)
1class SuperTest
2
3{
4int a;
5char c;
6float f;
7SuperTest(int a,char c,float f)
8{
9this.a=a;
10this.c=c;
11this.f=f;
12}
13void print()
14{
15System.out.println("a="+a+""+"c="+c+""+"f="+f);
16}
17}
18class SubTest extends SuperTest
19{
20SubTest()
21{
22Super(12,'N',12.3f);
23public static void main(String[] args)
24{
25SubTest st=new SubTest();
26st.print();
27
28}
29}
30}
Super keyword another program
1class A
2{
3int i;
4}
5//create a subclass by extending class A
6class B extends A
7{
8int i;//this i hides the i in A
9B(int a,int b)
10{
11super.i=a;//i in A
12i=b;//i in B
13
14}
15void show()
16{
17System.out.println("i in superclass:"+super.i);
18System.out.println("i in subclass:"+i);
19}
20}
21class UseSuper
22{
23public static void main(String args[])
24{
25B subob=new B(1,2);
26subob.show();
27}
28}
This Keyword
1class This
2{
3int a=12;
4void meth(int a)
5{
6System.out.println(a);
7System.out.println(this.a);
8}
9public static void main(String[] args)
10{
11This td=new This();
12td.meth(10);
13System.out.println(td.a);
14}}
Typecasting
1class TypeCasting
2{
3public static void main(String[] args)
4{
5int i=257;
6
7byte b;
8double d=323.123;
9System.out.println("int to byte conversion");
10b=(byte)i;
11System.out.println("i and b are:"+i+" "+b);
12System.out.println("double to int conversion");
13i=(int)d;
14System.out.println("i and d are:"+i+" "+d);
15System.out.println("double to byte conversion");
16b=(byte)d;
17System.out.println("b and d are:"+b+" "+d);
18}
19}
Abstract Class
1abstract class Figure
2{
3double dim1,dim2;
4Figure(double a,double b)
5{
6dim1=a;
7dim2=b;
8}
9
10//area is now an abstract method
11abstract double area();
12}
13class Rectangle extends Figure
14{
15Rectangle(double a,double b)
16{
17super(a,b);
18}
19//override area for rectangle
20double area()
21{
22System.out.println("Inside Area for Rectangle:");
23return dim1*dim2;
24}
25}
26class Triangle extends Figure
27{
28Triangle(double a, double b)
29{
30super(a,b);
31}
32//override area for right triangle
33double area()
34
35{
36System.out.println("Inside Area for Triangle");
37return dim1*dim2/2;
38}
39}
40class AbstractAreas
41{
42public static void main(String args[])
43{
44//Figure f=new Figure(10,10);//illegal now
45Rectangle r=new Rectangle(9,5);
46Triangle t=new Triangle(10,8);
47Figure figref;//this is OK,no object is created
48figref=r;
49System.out.println("Area is:"+figref.area());
50figref=t;
51System.out.println("Area is"+figref.area());
52}
53}
LAB CYCLE:
Traffic light
1/*10. Write a Java program that simulates a traffic light. The program lets the user select one of three
2lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message with
3“Stop” or “Ready” or “Go” should appear above the buttons in selected color. Initially, there is no
4message shown.*/
5import java.awt.*;
6import java.awt.event.*;
7import javax.swing.*;
8class TrafficLight1 extends JFrame implements ActionListener
9{
10String msg=" " ;
11private JLabel label;
12private JTextField display;
13private JRadioButton r1,r2,r3;
14private ButtonGroup bg;
15private Container c;
16public TrafficLight1()
17{
18setLayout(new FlowLayout());
19c=getContentPane();
20label=new JLabel(" Traffic Light");
21display =new JTextField(10);
22r1=new JRadioButton("RED");
23r2=new JRadioButton("GREEN");
24r3=new JRadioButton("YELLOW");
25bg=new ButtonGroup();
26c.add(label);
27c.add(r1);
28c.add(r2);
29c.add(r3);
30c.add(display);
31bg.add(r1);
32bg.add(r2);
33bg.add(r3);
34r1.addActionListener(this);
35r2.addActionListener(this);
36r3.addActionListener(this);
37setSize(400,400);
38setVisible(true);
39c.setBackground(Color.pink);
40}
41public void actionPerformed(ActionEvent ie)
42{
43msg=ie.getActionCommand();
44if (msg.equals("RED"))
45{
46c.setBackground(Color.RED);
47display.setText(msg+ " :TURN ON");
48}
49else if (msg.equals("GREEN"))
50{
51c.setBackground(Color.GREEN);
52display.setText(msg+ " :TURN ON");
53}
54else if (msg.equals("YELLOW"))
55{
56c.setBackground(Color.YELLOW);
57display.setText(msg+ " :TURN ON");
58}
59}
60public static void main(String args[])
61{
62TrafficLight1 light=new TrafficLight1();
63light.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
64}
65}
Table
1/*12. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the
2header, and the remaining lines correspond to rows in the table. The elements are separated by
3commas. Write a java program to display the table using Labels in Grid Layout.*/
4import java.io.*;
5import java.util.*;
6import java.awt.*;
7import java.awt.event.*;
8import javax.swing.*;
9import javax.swing.event.*;
10class A extends JFrame
11{
12public A()
13{
14setSize(400,400);
15setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16GridLayout g=new GridLayout(0,3);
17setLayout(g);
18try
19{
20FileInputStream fin = new FileInputStream("D:/java/emp.txt");
21Scanner sc = new Scanner(fin).useDelimiter(",");
22String[] arrayList;
23String a;
24while (sc.hasNextLine())
25{
26a=sc.nextLine();
27arrayList=a.split(",");
28for (String i:arrayList)
29{
30add(new JLabel(i));
31}
32}
33}
34catch (Exception ex)
35{
36}
37setDefaultLookAndFeelDecorated(true);
38pack();
39setVisible(true);
40}
41}
42public class Tb2
43{
44public static void main(String[] args)
45{
46A a = new A();
47}
48}
PC Fixed
1/*2. Correct implementation of Producer-Consumer*/
2class Q {
3int n;
4boolean available = false;
5synchronized int get() {
6while(available==false)
7try {
8wait();
9} catch(InterruptedException e) {
10System.out.println("InterruptedException caught");
11}
12System.out.println("Got: " + n);
13available = false;
14notify();
15return n;
16}
17synchronized void put(int n) {
18while(available==true)
19try {
20wait();
21} catch(InterruptedException e) {
22System.out.println("InterruptedException caught");
23}
24this.n = n;
25available = true;
26System.out.println("Put: " + n);
27notify();
28}
29}
30class Producer implements Runnable {
31Q q;
32Producer(Q q) {
33this.q = q;
34new Thread(this, "Producer").start();
35}
36public void run() {
37int i = 0;
38while(true) {
39q.put(i++);
40}
41}
42}
43class Consumer implements Runnable {
44Q q;
45Consumer(Q q) {
46this.q = q;
47new Thread(this, "Consumer").start();
48}
49public void run() {
50while(true) {
51q.get();
52}
53}
54}
55class PCFixed1 {
56public static void main(String args[]) {
57Q q = new Q();
58new Producer(q);
59new Consumer(q);
60System.out.println("Press Control-C to stop.");
61}
62}
multi thread application
1 /*1. Write a java Program that implements a multi-thread application that has three threads. First
2thread generates random integer every 1 second and if the value is even, second thread computes the
3square of the number and prints. If the value is odd, the third thread will print the value of cube of the
4number.*/
5 import java.util.Random;
6class Square extends Thread
7{
8int x;
9Square(int n)
10 {
11 x = n;
12 }
13 public void run()
14 {
15 int sqr = x * x;
16 System.out.println("Square of " + x + " = " + sqr );
17 }
18}
19class Cube extends Thread
20{
21 int x;
22 Cube(int n)
23 {
24 x = n;
25 }
26 public void run()
27 {
28 int cub = x * x * x;
29 System.out.println("Cube of " + x + " = " + cub );
30}
31}
32class Number extends Thread
33{
34public void run()
35 {
36 Random random = new Random();
37 for(int i =0; i<10; i++)
38 {
39 int randomInteger = random.nextInt(100);
40 System.out.println("Random Integer generated : " + randomInteger);
41if(randomInteger%2==0)
42{
43Square s = new Square(randomInteger);
44 s.start();
45 }
46 else
47 {
48 Cube c = new Cube(randomInteger);
49 c.start();
50 }
51try
52{
53 Thread.sleep(1000);
54 }
55catch (InterruptedException ex)
56{
57System.out.println(ex);
58}
59 }
60 }
61}
62public class MultipleThreads
63{
64public static void main(String args[])
65 {
66 Number n = new Number();
67 n.start();
68 }
69}
Mouse Events
1/*Write a Java program to handle mouse events.*/
2import java.awt.*;
3import java.awt.event.*;
4import java.applet.*;
5/*<applet code="MouseEvents" width=100 height=100>
6</applet>
7*/
8public class MouseEvents extends Applet implements
9MouseListener,MouseMotionListener{
10String msg=" ";
11int mouseX=0,mouseY=0;
12public void init(){
13addMouseListener(this);
14addMouseMotionListener(this);
15}
16public void mouseClicked(MouseEvent me){
17mouseX=0;
18mouseY=10;
19msg="Mouseclicked";
20repaint();
21}
22public void mouseEntered(MouseEvent me){
23mouseX=0;
24mouseY=10;
25msg="Mouseentered";
26repaint();
27}
28public void mouseExited(MouseEvent me){
29mouseX=0;
30mouseY=10;
31msg="Mouseexited";
32repaint();
33}
34public void mousePressed(MouseEvent me){
35mouseX=me.getX();
36mouseY=me.getY();
37msg="down";
38repaint();
39}
40public void mouseReleased(MouseEvent me){
41mouseX=me.getX();
42mouseY=me.getY();
43msg="up";
44repaint();
45}
46public void mouseDragged(MouseEvent me){
47mouseX=me.getX();
48mouseY=me.getY();
49msg="*";
50showStatus("dragging mouse at"+mouseX+","+mouseY);
51repaint();
52}
53public void mouseMoved(MouseEvent me){
54showStatus("movingmouse at"+me.getX()+","+me.getY());
55}
56public void paint(Graphics g){
57g.drawString(msg,mouseX,mouseY);
58}
59}
Keyboards Events
1/*5. Write a Java program to handle keyboard events.*/
2import java.awt.*;
3import java.awt.event.*;
4import java.applet.*;
5/*<applet code="SimpleKey" width=300 height=100>
6</applet> */
7public class SimpleKey extends Applet implements KeyListener{
8String msg=" ";
9int X=10,Y=20;
10public void init(){
11addKeyListener(this);
12}
13public void keyPressed(KeyEvent ke){
14showStatus("key down");
15}
16public void keyReleased(KeyEvent ke){
17showStatus("Key up");
18}
19public void keyTyped(KeyEvent ke){
20msg+=ke.getKeyChar();
21repaint();
22}
23public void paint(Graphics g){
24g.drawString(msg,X,Y);
25} }
Integer Division
1/*9. Write a Java program that creates a user interface to perform integer divisions. The user enters
2two numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 is displayed in the
3Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program
4would throw a Number Format Exception. If Num2 were Zero, the program would throw an
5Arithmetic Exception. Display the exception in a message dialog box.*/
6import javax.swing.*;
7import java.awt.*;
8import java.awt.event.*;
9public class Division extends JFrame
10implements ActionListener
11{
12Container c;
13JButton btn;
14JLabel lbl1,lbl2,lbl3;
15JTextField tf1,tf2,tf3;
16JPanel p;
17Division()
18{
19super("Exception Handler");
20c=getContentPane();
21c.setBackground(Color.red);
22btn=new JButton("DIVIDE");
23btn.addActionListener(this);
24tf1=new JTextField(30);
25tf2=new JTextField(30);
26tf3=new JTextField(30);
27lbl1=new JLabel("NUM 1");
28lbl2=new JLabel("NUM 2");
29lbl3=new JLabel("RESULT");
30p=new JPanel();
31p.setLayout(new GridLayout(3,2));
32p.add(lbl1); p.add(tf1);
33p.add(lbl2); p.add(tf2);
34p.add(lbl3); p.add(tf3);
35c.add(new JLabel("Division"),"North");
36c.add(p,"Center");
37c.add(btn,"South");
38}
39public void actionPerformed(ActionEvent e)
40{
41if(e.getSource()==btn)
42{
43try
44{
45int a=Integer.parseInt(tf1.getText());
46int b=Integer.parseInt(tf2.getText());
47int c=a/b;
48tf3.setText(""+c);
49}
50catch(NumberFormatException ex)
51{
52tf3.setText("--");
53JOptionPane.showMessageDialog(this,"Only Integer Division");
54}
55catch(ArithmeticException ex)
56{
57tf3.setText("--");
58JOptionPane.showMessageDialog(this,"Division by zero");
59}
60catch(Exception ex)
61{
62tf3.setText("--");
63JOptionPane.showMessageDialog(this,"Other Err "+ex.getMessage());
64}
65}
66}
67public static void main(String args[])
68{
69Division b=new Division();
70b.setSize(300,300);
71b.setVisible(true);
72}
73}
Files
1/*14. Write a Java program to list all the files in a directory including the files present in all its
2subdirectories.Note:the directory what I have taken is event handling try with your own directories*/
3import java.io.*;
4class DirList1
5{
6public static void main(String args[])
7{
8String dname="/event handling";
9File myDir=new File(dname);
10if(myDir.isDirectory())
11{
12File arr[]=myDir.listFiles();
13RecursivePrint(arr, 0);
14}
15}
16static void RecursivePrint(File[] arr, int level)
17{
18for (File f : arr)
19{
20// tabs for internal levels
21for (int i = 0; i < level; i++)
22System.out.print("\t");
23if(f.isFile())
24System.out.println(f.getName()+"is a file");
25else if(f.isDirectory())
26{
27System.out.println(f.getName()+"is a directory");
28// recursion for sub-directories
29RecursivePrint(f.listFiles(), level + 1);
30}
31}
32}
33}
Factorial
1/*8. Develop an applet in Java that receives an integer in one text field, and computes its factorial
2Value and returns it in another text field, when the button named “Compute” is clicked.*/
3import java.awt.*;
4import java.awt.event.*;
5import java.applet.*;
6/* <applet code="Compute1" width=300 height=300>
7</applet>
8*/
9public class Compute1 extends Applet implements
10ActionListener
11{
12Button btn,cbtn;
13Label lb1,lb2;
14TextField tf1,tf2;
15public void init()
16{
17btn=new Button("Compute");
18cbtn=new Button("Clear");
19btn.addActionListener(this);
20cbtn.addActionListener(this);
21tf1=new TextField(30);
22tf2=new TextField(30);
23lb1=new Label("Number");
24lb2=new Label("Result");
25setLayout(new GridLayout(3,2));
26add(lb1);
27add(tf1);
28add(lb2);
29add(tf2);
30add(btn);
31add(cbtn);
32}
33public void actionPerformed(ActionEvent ae)
34{
35if(ae.getSource()==btn)
36{
37int a=Integer.parseInt(tf1.getText());
38int fact=1;
39for(int i=1;i<=a;i++)
40{
41fact=fact*i;
42}
43tf2.setText(""+fact);
44}
45else
46{
47tf1.setText("");
48tf2.setText("");
49}
50}
51}
Calculator
1/*7. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for
2the digits and for the +, -,*, % operations. Add a text field to display the result. Handle any possible
3exceptions like divided by zero.*/
4/* <applet code="Math1" width=500 height=500>
5</applet>
6*/
7import java.awt.*;
8import java.awt.event.*;
9import java.applet.*;
10public class Math1 extends Applet implements ActionListener
11{ Button
12b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,clear,add,minus,mul,div,clc,equal;
13TextField tf;
14String msg="",op="-";
15int b,a,count;
16public void init()
17{
18b1=new Button("1");
19b2=new Button("2");
20b3=new Button("3");
21b4=new Button("4");
22b5=new Button("5");
23b6=new Button("6");
24b7=new Button("7");
25b8=new Button("8");
26b9=new Button("9");
27b0=new Button("0");
28clear=new Button("C");
29add=new Button("+");
30minus=new Button("-");
31mul=new Button("*");
32div=new Button("/");
33equal=new Button("=");
34b1.addActionListener(this);
35b2.addActionListener(this);
36b3.addActionListener(this);
37b4.addActionListener(this);
38b5.addActionListener(this);
39b6.addActionListener(this);
40b7.addActionListener(this);
41b8.addActionListener(this);
42b9.addActionListener(this);
43b0.addActionListener(this);
44add.addActionListener(this);
45minus.addActionListener(this);
46mul.addActionListener(this);
47div.addActionListener(this);
48clear.addActionListener(this);
49equal.addActionListener(this);
50tf=new TextField(30);
51setLayout(new GridLayout(5,5));
52add(tf);
53add(clear);
54add(equal);
55add(div);
56add(b0);
57add(b1);
58add(b2);
59add(b3);
60add(add);
61add(b4);
62add(b5);
63add(b6);
64add(minus);
65add(b7);
66add(b8);
67add(b9);
68add(mul);
69}
70public void actionPerformed(ActionEvent ae)
71{ switch(ae.getActionCommand())
72{ case "1": msg=msg+"1";
73tf.setText(msg);
74break;
75case "2": msg=msg+"2";
76tf.setText(msg);
77break;
78case "3": msg=msg+"3";
79tf.setText(msg);
80break;
81case "4": msg=msg+"4";
82tf.setText(msg);
83break;
84case "5": msg=msg+"5";
85tf.setText(msg);
86break;
87case "6": msg=msg+"6";
88tf.setText(msg);
89break;
90case "7": msg=msg+"7";
91tf.setText(msg);
92break;
93case "8": msg=msg+"8";
94tf.setText(msg);
95break;
96case "9": msg=msg+"9";
97tf.setText(msg);
98break;
99case "0": msg=msg+"0";
100tf.setText(msg);
101break;
102case "+": if(count==0)
103{ b=Integer.parseInt(tf.getText());
104op="+";
105tf.setText("");
106msg="";
107count++;
108}
109else
110{ a=Integer.parseInt(tf.getText());
111Math2(b,a,op);
112op="+";
113tf.setText("");
114msg="";
115}
116break;
117case "-": if(count==0)
118{
119b=Integer.parseInt(tf.getText());
120op="-";
121tf.setText("");
122msg="";
123count++;
124}
125else
126{
127a=Integer.parseInt(tf.getText());
128Math2(b,a,op);
129op="-";
130tf.setText("");
131msg="";
132}
133break;
134case "*": if(count==0)
135{
136b=Integer.parseInt(tf.getText());
137op="*";
138tf.setText("");
139msg="";
140count++;
141}
142else
143{
144a=Integer.parseInt(tf.getText());
145Math2(b,a,op);
146op="*";
147tf.setText("");
148msg="";
149}
150break;
151case "/": if(count==0)
152{
153b=Integer.parseInt(tf.getText());
154op="/";
155tf.setText("");
156msg="";
157count++;
158}
159else
160{
161a=Integer.parseInt(tf.getText());
162Math2(b,a,op);
163op="/";
164tf.setText("");
165}
166msg="";
167break;
168case "C": tf.setText("");
169b=0;
170msg="";
171count=0;
172break;
173case "=": a=Integer.parseInt(tf.getText());
174Math2(b,a,op);
175tf.setText(""+b);
176count=0;
177msg="";
178break;
179}
180}
181public void Math2(int b1,int a1,String op1)
182{
183switch(op1)
184{
185case "+": b=b1+a1;
186break;
187case "-": b=b1-a1;
188break;
189case "*": b=b1*a1;
190break;
191case "/": b=b1/a1;
192break;
193}
194}
195}
Double Linked List
1public class ddl
2{
3class node
4{
5int data;
6node prev;
7node next;
8public node(int data)
9{
10this.data=data;
11}
12}
13node head,tail=null;
14public void addNode(int data)
15{
16node newNode= new node(data);
17if(head==null)
18{
19head=tail=newNode;
20head.prev=null;
21tail.next=null;
22}
23else
24{
25tail.next=newNode;
26newNode.prev=tail;
27tail=newNode;
28tail.next=null;
29}
30}
31public void displayF()
32{
33node current=head;
34if(head==null)
35{
36System.out.println("List is empty");
37return;
38}
39System.out.println("nodes of ddl FORWARD:");
40while(current!=null)
41{
42System.out.print(current.data+" ");
43current=current.next;
44}
45System.out.println();
46}
47public void displayB()
48{
49node current=tail;
50if(tail==null)
51{
52System.out.println("List is empty");
53return;
54}
55System.out.println("nodes of ddl BACKWARD:");
56while(current!=null)
57{
58System.out.print(current.data+" ");
59current=current.prev;
60}
61System.out.println();
62}
63public void deletenode(int key)
64{
65node temp = head, prev = null;
66if (temp != null && temp.data == key)
67{
68head = temp.next;
69return;
70}
71while (temp != null && temp.data != key)
72{
73prev = temp;
74temp = temp.next;
75}
76if (temp == null)
77return;
78prev.next = temp.next;
79}
80public static void main(String args[])
81{
82ddl d = new ddl();
83d.addNode(1);
84d.addNode(2);
85d.addNode(3);
86d.addNode(4);
87d.addNode(5);
88d.displayF();
89d.displayB();
90d.deletenode(2);
91System.out.println("after deletion");
92d.displayF();
93}
94}