Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
CHATANYA BHARATHI INSTITUTE OF TECHNOLOGY Object Oriented Programming Through Java Lab Record For I Yr. MCA II Semester Compiled by Mrs. G.KALPANA, Asst.Professor in MCA Department 2014-2015 [Pick the date] Department of MASTER OF COMPUTER APPLICATIONS Chaitanya Bharathi Institute of Technology (Autonomous) Gandipet, Hyderabad-75. Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem Object Oriented Programming Through Java Laboratory Record INDEX S.NO I PROGRAMME NAME Basic Programs 4 1)Write java program to print Biggest of 3 Numbers using Logical Operators 4 2) write a java program to print first 10 numbers in fibonacci series 5 3) Write a java program to print Factorial of a given number 6 4)Write java program to print the following o/p 5) Write a java program to print sum of Sum of Digits II III P.NO. 7 8 6) Write a java Program for swapping two numbers 9 7)Wrte a java program to print primes up to the given prime number 10 8) Write java program to check given string is a palindrome or not 11 9) wajp to print sum of n terms in the series 1/1! +1/2!+1/3!..... 12 10) Write A Java Program to print Quadratic roots using command line arguments 13 11) Write a java program to print the names in sorted order using arrays 14 12) Write a java program to print multiplication table using arrays 15 Method Overloading 18 1)Write a java program to demonstrate method overloading 18 2)Write a java program to find the volume of a Box using method overloading with different number of perameters. 19 Constructor overloading : 22 1) Write a java program to illustrate the concept of constructors and its overloading. 22 2) Write a java program for Rectangle class using constructor overloading with different no. of parameter list 24 3) Wajp to copy the values of one object into another using constructor. 26 Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 1 Object Oriented Programming Through Java Laboratory Record S.NO IV V VI VII VIII IX X PROGRAMME NAME P.NO Inheritence 28 1) Wajp for Rectange class using Simple Inheritance 28 2) Write a Java program to demonstrate multilevel inheritance. 30 3) Write a Java program to implement the following hierarchy and find area and perimeter Abstract 31 Method Overriding 35 1)Write a java program for Bank class using Method Overriding. 36 2) Write a java program to demonstrate Method overriding (use super keyword) 38 Dynamic Method Dispatch 39 1)Write a Java program to demonstrate dynamic dispatch. 40 2) Wajp for Bank class using Dynamic Method Dispatch 41 Abstract Class: 43 1) Write a Java program to implement a Vehicle Abstract class. 43 2)Wajp to demonstrate the concept of abstract class 46 Packages: 48 1)Write a Java program to demonstrate use of user defined packages. 49 2) write a java package for book class and then import and display the result. 50 3) write a java program to find the cube of a number for various data types using package and then import and display the results. 51 Interfaces: 53 1) Write a Java program to illustrate the multiple inheritance by using Interfaces. 53 Super , Static, final key words : 56 1)Write a java program to illustrate the keywords i)super ii)static iii)final 56 Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 2 Object Oriented Programming Through Java Laboratory Record S.NO XI PROGRAMME NAME P.NO Exception handling: 57 1)wajp to demonstrate simple example for exception handling 57 2)Wajp to demonstrate exception handling with multiple catch blocks 58 3) wajp using NumberFormat exception 60 4)Wajp for user defined exception 61 XII How to make executable jar files in JDK1.3.1? 63 XIII Multithreading 64 1) Write a Java program to demonstrate the concept of daemon threads 64 2) Write a Java program to demonstrate the concept of synchronization by suitable example 66 3) Write a Java program to demonstrate the concept of Inter thread communication by Suitable example 68 4) Write a program to demonstrate string tokenizer. 70 File I/O and Streams 73 1)Wajp to Demonstration of FileOutputStream and PrintStream classes 74 2) Write a java program to Write bytes to a file 75 3) Write a java program to copy bytes from one file to another. 76 Applets 79 1) Wajp for Sum of Two Numbers using Applet 79 2)Wajp for Applet using drawstring(), drawRect() and drawOval() 80 3) Write a Java program to demonstrate banner applet. 81 4) wajp for Bouncing of a Ball using applet 83 XIV) XV XIV AWT: 1 ) Wajp that prints a message by clicking on the button using AWT 2) Wajp to demonstrate Grid Layout manager using AWT 3) GUI with controls menus and event handling using SWING Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 87 3 Object Oriented Programming Through Java Laboratory Record Java lab programmes I. Basic programs: 1) Write java program to print Biggest of 3 Numbers using Logical Operators Importjava.util.*; class Biggest3 { public static void main(String args[]) { int n1, n2, n3, big; Scanner scan= new Scanner(System.in); System.out.print("Please Enter No 1: "); n1=scan.nextInt(); System.out.print("Please Enter No 2: "); n2=scan.nextInt(); System.out.print("Please Enter No 3: "); n3=scan.nextInt(); if(n1>n2 && n1>n3) big=n1; else if(n2>n1 && n2>n3) big=n2; else big=n3; System.out.println("Biggest No: " + big); } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 4 Object Oriented Programming Through Java Laboratory Record } O/P: 2) write a java program to print first 10 numbers in fibonacci series classFibo { public static void main(String args[]) { inta,b,temp,n; a=0; b=1; for(n=1;n<=10;n++) { System.out.println(a); temp=a+b; a=b; b=temp; } } }s o/p : Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 5 Object Oriented Programming Through Java Laboratory Record 3) Write a java program to print Factorial of a given number Importjava.util.*; class Factorial { public static void main(String args[]) { int n, i, fact=1; Scanner scan= new Scanner(System.in); System.out.print("Please Enter a No."); n=scan.nextInt(); for(i=n;i>=1;i--) { fact=fact*i ; } System.out.println("Factorial of " + n + " is " + fact); } } O/P: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 6 Object Oriented Programming Through Java Laboratory Record 4)Write java program to print the following o/p Following star pattern is printed * ** *** **** ***** class Stars { Public static voidmain(String[]args) { int row, numberOfStars; for(row =1; row <=10; row++) { for(numberOfStars=1;numberOfStars<=row; numberOfStars++) { System.out.print("*"); } System.out.println();// Go to next line } } } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 7 Object Oriented Programming Through Java Laboratory Record Output of program: 5) Write a java program to print sum of Sum of Digits Logic: 513 -> 5+1+3=9 n res n sum 513 513%10 0 3 513/10 51%10 51 1 51/10 5%10 3 4 5 5 5/10 3 4 9 0 9 importjava.util.*; classSumDigits { public static void main(String args[]) { int n, res,sum=0; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 8 Object Oriented Programming Through Java Laboratory Record Scanner scan= new Scanner(System.in); System.out.print("Please Enter No. = "); n=scan.nextInt(); System.out.print("Sum of digits of a number" +n+ "is = "); { res=n%10; n=n/10; sum=sum+res; } System.out.print(+sum); while(n>0) } } o/p: 6) Write a java Program for swapping two numbers importjava.util.*; class Swap { public static void main(String args[]) { int n1, n2, temp; Scanner scan= new Scanner(System.in); System.out.print("Please Enter No 1:="); n1=scan.nextInt(); System.out.print("Please Enter No 2: ="); n2=scan.nextInt(); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 9 Object Oriented Programming Through Java Laboratory Record temp=n1; n1=n2; n2=temp; System.out.println("First No: " + n1); System.out.println("Second No: " + n2); } } o/p: 7)Wrte a java program to print primes up to the given prime number importjava.util.*; public class Prime { public static void main(String args[]) { inti,j,p=1; Scanner sc =new Scanner(System.in); System.out.print("enter a number up to which u want print primes ="); int n=sc.nextInt(); for(i=2;i<=n;i++) { p=1; for(j=2;j<i;j++) { if(i%j==0) { p=0; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 10 Object Oriented Programming Through Java Laboratory Record }} if(p==1) System.out.println(j); } } } o/p: 8) Write java program to check given string is a palindrome or not importjava.util.*; public class Palin { public static void main(String args[]) { System.out.print("enter strings = "); Scanner sc=new Scanner(System.in); String s=sc.next(); StringBuffer tmp=new StringBuffer(s); tmp.reverse(); String str2; str2=new String(tmp); if(s.equals(str2)) System.out.println("the given string " + s + " is palindrome"); else System.out.println("the given string " + s + " is not palindrome"); } } O/P: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 11 Object Oriented Programming Through Java Laboratory Record 9) wajp to print sum of n terms in the series 1/1! +1/2!+1/3!..... importjava.util.Scanner; classSeriesfact { public static void main(String args[]) { int i; float sum=0,f=1; System.out.println("enter number of terms in the series"); Scanner sc=new Scanner(System.in); int n=sc.nextInt(); for(i=1;i<=n;i++) { for(f=1;f<=i;f++) { f=f*i; sum=sum + (float)1/f; } } System.out.println("sum of" +n +"terms is = " +sum); } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 12 Object Oriented Programming Through Java Laboratory Record 10) Write A Java Program to print Quadratic roots using command line arguments importjava.lang.*; class Quadratic { public static void main(String args[]) { inta,b,c,d; double r1,r2; a=Integer.parseInt(args[0]); b=Integer.parseInt(args[1]); c=Integer.parseInt(args[2]); d=b*b-4*a*c; if(d==0) { r1=r2=-(float)b/(2*a); System.out.println("the roots are real equal =" +r1 + " and r2 = " +r2); } else if(d>0) { double t=Math.sqrt(d); r1=(-b+t)/(2*a); r2=(+b+t)/(2*a); System.out.println("the roots are real and distict \n r=" +r1 +" and r2=" +r2); } else if(d<0) { System.out.println("the roots are imaginary and there is no real solution "); } }} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 13 Object Oriented Programming Through Java Laboratory Record 11) Write a java program to print the names in sorted order using arrays import java.lang.*; class Stringsort { static String name[]={"Bombay" , "Madras" ,"Delhi" ,"Pune"}; 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; } } } System.out.println("soted names are "); for(int i=0;i<size;i++) { System.out.println(name[i]); } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 14 Object Oriented Programming Through Java Laboratory Record } } o/p 12) Write a java program to print multiplication table using arrays import java.util.Scanner; import java.io.*; import java.lang.*; class MatrixMul { public static void main(String[] args) { int i= 0,j=0,k=0,p,q,m,n; int a[][] = new int[10][10]; int b[][] = new int[10][10],c[][] = new int[10][10]; Scanner sc = new Scanner(System.in); System.out.print("Enter no of rows in the A matrix= "); p=sc.nextInt(); System.out.print("Enter a no of columns in the A matrix = "); q=sc.nextInt(); System.out.print("Enter no of rows in the B matrix= "); m = sc.nextInt(); System.out.print("Enter no of columns in the B matrix= "); n = sc.nextInt(); if(q==m) { System.out.print ("Enter A matrix values :"); for(i=0;i<p;i++) { for(j=0; j<q ;j++) { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 15 Object Oriented Programming Through Java Laboratory Record a[i][j] = sc.nextInt() ; } } System.out.println("\nMatrix A values are "); for(i=0;i<p;i++) { for(j=0;j<q;j++) { System.out.print(" "+a[i][j]) ; } System.out.println(); } System.out.println("Enter matrxi B values :"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { b[i][j] = sc.nextInt() ; } } System.out.println("\nMatrix B values "); for(i=0;i<m;i++) { for(j=0;j<n;j++) { System.out.print(" "+b[i][j]) ; } System.out.println(); } System.out.println("\n C Matrix is C = A * B Result"); if(q == m) { for(i=0;i<p;i++) { for(j=0;j<n;j++) { c[i][j]= 0 ; for(k=0;k<q;k++) { c[i][j] = c[i][j] + (a[i][k] * b[k][j]) ; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 16 Object Oriented Programming Through Java Laboratory Record } } } } // for C matrix Printing for(i=0;i<p;i++) { for(j=0;j<n;j++) { System.out.print(" "+c[i][j]) ; } System.out.println(); } }else { System.out.println("Matrix multiplication not possible"); } } } O/P: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 17 Object Oriented Programming Through Java Laboratory Record II. Method Overloading Method overloading means when two or more methods have the same name but a different signature. Signature of a method is nothing but a combination of its name and the sequence of its parameter types. 1) Write a java program to demonstrate method overloading Program: class OverloadDemo { void max(float a, float b) { System.out.println("\nmax method with float argument invoked"); if(a>b) System.out.println(a+" is Greater"); else System.out.println(b+" is Greater"); } void max(double a, double b) { System.out.println("max method with double arg invoked"); if(a>b) System.out.println(a+" a is Greater"); else System.out.println(b+" b is Greater"); } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 18 Object Oriented Programming Through Java Laboratory Record max(long a, long b) { System.out.println("\nmax method with long arg invoked"); if(a>b) System.out.println(a+" a is Greater"); else System.out.println(b+" b is Greater"); } public static void main(String[] args) { OverloadDemo o=new OverloadDemo(); o.max(23L,12L); o.max(2,3); o.max(54.0,35f); } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 19 Object Oriented Programming Through Java Laboratory Record 2)Write a java program to find the volume of a Box using method overloading with different number of perameters. Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 20 Object Oriented Programming Through Java Laboratory Record class Box { int width,breadth,height; void getdata(int length) { width=breadth=height=length; } void getdata(int a,int b) { width=a; breadth=height=b; } void getdata(int x,int y, int z) { width=x; breadth=y; height=z; } int volume() Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 21 Object Oriented Programming Through Java Laboratory Record { System.out.println(" "); return width*breadth*height; }} class MainBox { public static void main(String args[]) { int vol; Box mybox1=new Box(); Box mybox2=new Box(); Box mybox3=new Box(); mybox1.getdata(10,20,30); vol=mybox1.volume(); System.out.println("volume of my box with 3 perameters is = " +vol); mybox2.getdata(10,20); vol=mybox2.volume(); System.out.println("volume of my box with 2 perameters is = " +vol); mybox3.getdata(5); vol=mybox3.volume(); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 22 Object Oriented Programming Through Java Laboratory Record System.out.println("volume of my box with 1 perameter is = " +vol); } } o/p: III. Constructor overloading : Constructor is a special type of method which is having the same class name that is used to initialize the object. Constructor is invoked at the time of object creation. Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. The compiler differentiates these constructors by taking into account the number of parameters in the list and their type. 1) Write a java program to illustrate the concept of constructors and its overloading. import java.lang.*; class TestOl { int hrs,mins,scnds; TestOl(int h,int m,int s) { hrs=h; mins=m; scnds=s; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 23 Object Oriented Programming Through Java Laboratory Record } public TestOl(int h) { hrs=h; mins=0; scnds=0; } public TestOl(int h,int m) { hrs=h; mins=m; scnds=0; } public TestOl() { hrs=0; mins=0; scnds=0; } void primetime() { System.out.println("hrs:"+hrs+"\t mins:"+mins+"\t scnds:"+scnds); } } class OverLoad { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 24 Object Oriented Programming Through Java Laboratory Record public static void main(String args[]) { TestOl obj1=new TestOl(); obj1.primetime(); TestOl obj2=new TestOl(5); obj2.primetime(); TestOl obj3=new TestOl(7,6); obj3.primetime(); }} O/P: 2) Write a java program for Rectangle class using constructor overloading with different no. of parameter list class Rectangle { int length; int width; int area() { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 25 Object Oriented Programming Through Java Laboratory Record return length*width; } void perimeter() { int p=2*length+2*width; System.out.println("perimeter of rectangle is " +p); } Rectangle() { length=10; width=10; } Rectangle(int a) { length=width=a; } Rectangle(int a, int b) { length=a; width=b; } } class MainForRectangle { public static void main(String args[]) { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 26 Object Oriented Programming Through Java Laboratory Record Rectangle r1= new Rectangle(); r1.length=5; r1.width=5; Rectangle r2=new Rectangle(10); Rectangle r3=new Rectangle(20,10); System.out.println(" "); r1.perimeter(); r2.perimeter(); r3.perimeter(); float area1= r1.area(); float area2=r2.area(); System.out.println(" "); System.out.println("area of Rectangle 1 and 2 are " +area1+", " +area2); System.out.println("area of Rectangle objcet3 is" +r3.area()); } } O/P: 3) Wajp to copy the values of one object into another using constructor. Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 27 Object Oriented Programming Through Java Laboratory Record class Student { int id; String name; int age; Student(int i,String n,int a) { id = i; name = n; age=a; } Student(Student s) { id = s.id; name =s.name; age=s.age; } void display() { System.out.println(id+" "+name+" "+age); } public static void main(String args[]) { Student s1 = new Student(111,"Kalpana",39); Student s2 = new Student(s1); Faculty name : G.kalpana //copy contents from s1 in to s2 Course: M.C.A Year/Sem : I st year /2nd sem 28 Object Oriented Programming Through Java Laboratory Record s1.display(); s2.display(); } } o/p: IV) Inheritance is a mechanism in which one object acquires all the properties and behaviours of parent object. The following kinds of inheritance are there in java. Simple Inheritance : When a subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. Multilevel Inheritance: When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance Multiple Inheritance is achieved in java by using Interfaces. 1) Wajp for Rectange class using Simple Inheritance class Rectangle { int length; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 29 Object Oriented Programming Through Java Laboratory Record int width; void area() { System.out.println("area of Rectangle is " +(length*width)); } } class Cuboid extends Rectangle { int height; void volume() { System.out.println("Volume of cuboid is " +(length*width*height)); } } class Simpleinheritance1 { public static void main(String args[]) { Rectangle r=new Rectangle(); Cuboid c=new Cuboid(); r.length=10; r.width=5; r.area(); c.length=15; c.width=10; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 30 Object Oriented Programming Through Java Laboratory Record c.height=5; c.volume(); } } o/p: 2) Write a Java program to demonstrate multilevel inheritance. class Name { String name="swathi"; int age=20; } class Mark extends Name { int m1=30,m2=30,m3=30; } class Student extends Mark { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 31 Object Oriented Programming Through Java Laboratory Record int total; void calc() { total=m1+m2+m3; } void show() { System.out.println("\n NAME: " +name+"\n AGE:"+age+"\n MARK1="+m1+"\n MARK2=" +m2+"\n MARK3="+m3+"\n TOTAL:"+total); } } class MultilevelInheritence { public static void main(String args[]) { Student ob=new Student(); ob.calc(); ob.show(); } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 32 Object Oriented Programming Through Java Laboratory Record 3) Write a Java program to implement the following hierarchy and find area and perimeter Abstract abstract class shape { abstract double calcar(); abstract double calcper(); abstract void display(); }; class circle extends shape { double r; circle(double a) Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 33 Object Oriented Programming Through Java Laboratory Record { r=a; } void display() { System.out.println("\nradius="+r); } double calcar() { double arc=(3.14*r*r); return arc; } double calcper() { double per=(2*3.14*r); return per; }} class square extends shape { double a; square(double s) { a=s; } void display() { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 34 Object Oriented Programming Through Java Laboratory Record System.out.println("\nside="+a); } double calcar() { double ars=a*a; return ars; } double calcper() { double per=2*a; return per; }} class triangle extends shape { double b,h; triangle(double p, double q) { b=p; h=q; } void display() { System.out.println("\nbreadth="+b+"\t height="+h); } double calcar() { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 35 Object Oriented Programming Through Java Laboratory Record double art=(0.5*b*h); return art; } double calcper() { return 0; } }; class Classhierarchy { public static void main(String s[]) { circle c=new circle(5.2f); c.display(); System.out.println("\nArea of circle ="+c.calcar()); System.out.println("\nPerimeter of circle ="+c.calcper()); square sq=new square(2.3f); sq.display(); System.out.println("\nArea of square ="+sq.calcar()); System.out.println("\nPerimeter of square ="+sq.calcper()); triangle t=new triangle(1.3f,4.5f); t.display(); System.out.println("\nArea of triangle ="+t.calcar()); }} Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 36 Object Oriented Programming Through Java Laboratory Record o/p: V) Method Overriding: When there are two methods with same name and prototypes in super class and subclass then it is called Method overriding. Advantages of Java Method Overriding: Method Overriding is used to provide specific implementation of a method that is already provided by its super class. Method Overriding is used for Runtime Polymorphism 1)Write a java program for Bank class using Method Overriding. class Bank { int getRateOfInterest() Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 37 Object Oriented Programming Through Java Laboratory Record { return 0; } } class SBI extends Bank{ int getRateOfInterest() { return 8; } } class ICICI extends Bank { int getRateOfInterest() { return 7; } } class AXIS extends Bank { int getRateOfInterest() { return 9; } } class Test{ public static void main(String args[]){ Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 38 Object Oriented Programming Through Java Laboratory Record SBI s=new SBI(); ICICI i=new ICICI(); AXIS a=new AXIS(); System.out.println("SBI Rate of Interest: "+s.getRateOfInterest()); System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest()); System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest()); } } o/p: 2) Write a java program to demonstrate Method overriding (use super keyword) class Sup { int x; Sup (int x) //constructor { this.x=x; } void display() { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 39 Object Oriented Programming Through Java Laboratory Record System.out.println("x in Super= "+x); }} class sub extends Sup { int y; sub(int x,int y) { super(x); this.y=y; } void display() { System.out.println("\nX in Super Class="+x); System.out.println("Y in Sub Class="+y); }} class TestOverride { public static void main(String naren[]) { sub obj=new sub(100,200); obj.display(); }} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 40 Object Oriented Programming Through Java Laboratory Record VI) Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable. 1)Write a Java program to demonstrate dynamic dispatch. Program: abstract class Shape { protected final static double PI = 22.0/7.0; protected double length; public abstract double area(); } class Square extends Shape { Square(double side) { length=side; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 41 Object Oriented Programming Through Java Laboratory Record } public double area() { return length*length; }} class Circle extends Shape { Circle(double radius) { length=radius; } public double area() { return PI*length*length; }} public class DynamicDispatch { public static void main(String[] args) { Shape sh; Square sq = new Square(10.0); Circle circ = new Circle(10.0); sh=sq; System.out.println("\n Area of Square = " + sh.area()); sh=circ; System.out.println("Area of circle = " + sh.area()); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 42 Object Oriented Programming Through Java Laboratory Record }} o/p: 2) Wajp for Bank class using Dynamic Method Dispatch class Bank { int getRateOfInterest() { return 0; } } class SBI extends Bank{ int getRateOfInterest() { return 8; } } class ICICI extends Bank { int getRateOfInterest() Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 43 Object Oriented Programming Through Java Laboratory Record { return 7; } } class AXIS extends Bank { int getRateOfInterest() { return 9; } } class DynamicDispatch{ public static void main(String args[]){ Bank b1=new SBI(); Bank b2=new ICICI(); Bank b3=new AXIS(); System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest()); System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest()); System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest()); } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 44 Object Oriented Programming Through Java Laboratory Record VII) Abstract Class: Abstraction is the mechanism of exhibiting the necessary things by hiding the unnecessary things. An abstract class is a class that may have at least one abstract method.(ie without body) we cannot create an object for abstract class. Abstract class may have reference variables but may not have memory for it. 1) Write a Java program to implement a Vehicle Abstract class. /* Write a Java program to implement an Vehicle Abstract class.*/ abstract class Vehicle { public abstract void wheels(); public abstract void seating(); public abstract void brakes(); } class Car extends Vehicle { public void wheels() { System.out.println("\nCar Has Four Wheels"); } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 45 Object Oriented Programming Through Java Laboratory Record public void seating() { System.out.println("Car Has Four Seating Capacity"); } public void brakes() { System.out.println("Car Has Power Brakes\n"); }} class Bike extends Vehicle { public void wheels() { System.out.println("Bike Has Two Wheels"); } public void seating() { System.out.println("Bike Has Two Seating Capacity"); } public void brakes() { System.out.println("Bike Has Disk Brakes"); }} class VehicleDemo { public static void main(String args[]) { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 46 Object Oriented Programming Through Java Laboratory Record Vehicle v=new Car(); Vehicle v1=new Bike(); v.wheels(); v.seating(); v.brakes(); v1.wheels(); v1.seating(); v1.brakes(); }} o/p: 2)Wajp to demonstrate the concept of abstract class abstract class Shape { int length; int width; Shape(int a, int width) { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 47 Object Oriented Programming Through Java Laboratory Record length=a; this.width=width; } abstract void area(); } class Rectangle extends Shape { Rectangle(int length, int width) { super(length,width); } void area() { System.out.println("area of reactange is " +(length*width)); } } class Cuboid extends Shape { int height; Cuboid(int length, int width, int height) { super(length,width); this.height=height; } void area() { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 48 Object Oriented Programming Through Java Laboratory Record System.out.println("Surface area of cuboid is " +(2*length*width+2*width*height+2*height*length)); } void volume() { System.out.println("volume of cuboid is"+(length*width*height)); } } class Mainforshape { public static void main(String args[]) { Rectangle r=new Rectangle(10,20); r.area(); Cuboid c=new Cuboid(5,10,15); c.area(); c.volume(); Shape s; s=r; s.area(); s=c; s.area(); } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 49 Object Oriented Programming Through Java Laboratory Record VIII) Packages: A package is a group of similar types of classes, interfaces and sub-packages. Package can be categorized in two form, built-in package and user-defined package. Advantage of Package : Package is used to categorize the classes and interfaces so that they can be easily maintained. Package provids access protection. Package removes naming collision. 1)Write a Java program to demonstrate use of user defined packages. I) // save below file Sum.java package pack; public class Sum { public void getSum(int a,int b) { System.out.println("\nSum Of Two Numbers"+a+" and "+b+"="+(a+b)); } } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 50 Object Oriented Programming Through Java Laboratory Record II) // save below file PackDemo.java import pack.Sum; class PackDemo { public static void main(String[] args) { Sum s=new Sum(); s.getSum(10,20); }} o/p: 2) write a java package for book class and then import and display the result. 1) // Save below file Book.java package packagetest; public class Book { int book_no,book_id,book_pages; public Book(int a,int b, int c) { book_no=a; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 51 Object Oriented Programming Through Java Laboratory Record book_id=b; book_pages=c; } public void book_info() { System.out.println("The Book No"+book_no); System.out.println("The Book Id "+book_id); System.out.println("The Book Pages"+book_pages); } } 2. //Save below file BookMain.java import packagetest.Book; class BookReader { public static void main(String[] args) { Book b=new Book(12,15,86); b.book_info(); } } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 52 Object Oriented Programming Through Java Laboratory Record o/p: 3) write a java program to find the cube of a number for various data types using package and then import and display the results. //1.program to create package package mathematics; public class Mathmethods { public static float Cube(float n) { return(n*n*n); } public static int Cube(int n) { return(n*n*n); } public static double Cube(double n) { return(n*n*n); } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 53 Object Oriented Programming Through Java Laboratory Record public static long Cube(long n) { return(n*n*n); } } //2. program to import import mathematics.Mathmethods; //import java.io.*; import java.util.Scanner; class Cube { public static void main(String S[]) { //int a=20; Scanner m=new Scanner(System.in); System.out.println("the given number is "); int a=m.nextInt(); Mathmethods mm = new Mathmethods(); int b = Mathmethods.Cube(a); System.out.println("cube is " +b); } } o/p: javac –d . Mathmethods.java javac Cube.java java Cube Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 54 Object Oriented Programming Through Java Laboratory Record IX ) MultipleInheritance: we cannot use multiple inheritance means one class cannot be inherited from more than one classes. To use this process, Java provides an alternative approach known as “Interface”. Interface: An Interface is usually a kind of class. Interface contain only Abstract methods and Final variable. A java class cannot be a sub class of more than one class, but a class can implements more than one Interfaces. 1) Write a Java program to illustrate the multiple inheritance by using Interfaces. import java.lang.*; import java.io.*; interface Exam { void percent_cal(); } class Student { String name; int roll_no,mark1,mark2; Student(String n, int r, int m1, int m2) { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 55 Object Oriented Programming Through Java Laboratory Record name=n; roll_no=r; mark1=m1; mark2=m2; } void display() { System.out.println ("\nName of Student: "+name); System.out.println ("Roll No. of Student: "+roll_no); System.out.println ("Marks of Subject 1: "+mark1); System.out.println ("Marks of Subject 2: "+mark2); }} class Result extends Student implements Exam { Result(String n, int r, int m1, int m2) { super(n,r,m1,m2); } public void percent_cal() { int total=(mark1+mark2); float percent=total*100/200; System.out.println ("Percentage: "+percent+"%"); } void display() { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 56 Object Oriented Programming Through Java Laboratory Record super.display(); }} class MultipleInheritenceDemo { public static void main(String args[]) { Result R = new Result("Anoop reddy",12,93,84); R.display(); R.percent_cal(); }} o/p: X) Super , Static, final key words 1)Write a java program to illustrate the keywords i)super ii)static iii)final class Super { static final int a=20; static int b; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 57 Object Oriented Programming Through Java Laboratory Record int c=100; } class SuperDemo extends Super { void display() { System.out.println("\nFinal Variable=" +super.a); System.out.println("Super class Variable=" +super.c); System.out.println("Static Variable="+b); } public static void main(String[] args) { SuperDemo s=new SuperDemo(); s.display(); }} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 58 Object Oriented Programming Through Java Laboratory Record XI) Exception handling: Exception is an abnormal condition.The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be maintained. 1)wajp to demonstrate simple example for exception handling import java.lang.*; class Error2 { public static void main(String args[]) { 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); } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 59 Object Oriented Programming Through Java Laboratory Record 2)Wajp to demonstrate exception handling with multiple catch blocks class ExcHandling { public static void main(String ar[]) { int a[]={5,10}; int b=5; try { int x=a[2]/(b-a[0]); } catch(ArithmeticException e) { System.out.println("div by zero"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array out of bound Error"); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 60 Object Oriented Programming Through Java Laboratory Record } int y=a[1]/a[0]; System.out.println("y value is " +y); } } o/p: 3) wajp using NumberFormat exception import java.lang.Exception; class ExHan2 { public static void main(String args[]) { int invalid=0,number,count=0; for(int i=0;i<args.length;i++) { try { number=Integer.parseInt(args[i]); } catch(NumberFormatException e) { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 61 Object Oriented Programming Through Java Laboratory Record invalid=invalid + 1; System.out.println("\n Invalid Number= " +args[i]); continue; } count=count +1; } System.out.println("\n Valid Number= " +count); System.out.println("\n Invalid Number= " +invalid); } } o/p: 4)Wajp for user defined exception class InsufBalance extends Exception { InsufBalance(String s) { super(s); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 62 Object Oriented Programming Through Java Laboratory Record } } class Mainbalance { public static void main(String s[]) { int bal=5000; try { int withdraw=Integer.parseInt(s[0]); if(bal<withdraw) { InsufBalance i= new InsufBalance("No susch bance exist"); throw i; } else { bal=bal-withdraw;= System.out.println("balance is "+bal); } } catch(InsufBalance i) { System.out.println(i); } catch(Exception e) Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 63 Object Oriented Programming Through Java Laboratory Record { System.out.println(e); } } } o/p: XII) How to make executable jar files in JDK1.3.1? Instructions for creating an Executable .jar file Make or modify the Manifest.Mf to yourManifest.MF 1) Your Class name with main is the class name without .class exentension. 2) No extra spaces following the your class name with main. Manifest-Version:1.0 Main-Class: YourClassNameWithMain Created-by:1.2(Sun Microsystems Inc.) On Command line : type the following jar cvfm YourJarFileName.jar YourManifest.MF* (or) Jar cvfm yourJarFileName.jar YourManifest.MF –C classes yourClassPath Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 64 Object Oriented Programming Through Java Laboratory Record Drag-drop the YourJarFileName.jar to your desktop double click it, it runs if your p rogram only has System.out.println(“whatever”); statements, it will displaynothing. The same will happen when you run it using java at commandline. Instructions for creating a .jar file. jar utility comes with your JDK1.2.2 It compresses your file similar to zip utility, and more Java. You need some windows code to see it run. You can use it on any machine installed JDK Create a folder name it anything.Make that folder your current directory Put all your files turning in that directory. Be sure to put your html file, if there is one At your dos prompt, while you are in the directory that you created , type in: jar cvf Prj02.jar* This will take ALL the files in the directory including subdirectories and place them in a .jar file Prj02 that can be replaced by any of your desired jar file name. To test it, you can extract the contents of jar file by typing: jar xvf Prj02.jar XIII) Multithreading: Multithreading is a conceptual programming paradigm where a program(process) is divided into 2 or more sub programs(processes) , which can be implemented at the same time in parallel. 1) Write a Java program to demonstrate the concept of daemon threads class DaemonThread extends Thread { int i; public void run() { for(i=0;i<5;i++); { System.out.println(this.getName()+" "+i); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 65 Object Oriented Programming Through Java Laboratory Record } } public static void main(String[] args) { DaemonThread d=new DaemonThread(); DaemonThread d1=new DaemonThread(); d.setName("\nDAEMON THREAD"); d1.setName("NORMAL THREAD"); d.setPriority(Thread.MIN_PRIORITY); d.start(); d1.start(); } } o/p: 2) Write a Java program to demonstrate the concept of synchronization by suitable example class Addition { Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 66 Object Oriented Programming Through Java Laboratory Record synchronized void add() { int a=99,b=1; System.out.println("c="+(a+b)); try { Thread.sleep(3000); System.out.println("After Sleep()"); } catch (InterruptedException e) { } } } class Synchro extends Thread { Addition obj1; public Synchro(Addition a) { obj1=a; Thread t1=new Thread(this); Thread t2=new Thread(this); Thread t3=new Thread(this); t1.start(); t2.start(); t3.start(); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 67 Object Oriented Programming Through Java Laboratory Record } public void run() { obj1.add(); { System.out.println("ThreadNameis"+Thread.currentThread(). getName()); } } } class TestSynchro { public static void main(String[] args) { Addition d=new Addition(); Synchro s=new Synchro(d); } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 68 Object Oriented Programming Through Java Laboratory Record 3) Write a Java program to demonstrate the concept of Inter thread communication by Suitable example public class ThreadDemo2 extends Thread { public void run() { for(int i=0;i<20;i++) { System.out.println(getName()+":"+i); } } public static void main(String[] args) { System.out.println("main started"); ThreadDemo2 td=new ThreadDemo2(); ThreadDemo2 td1=new ThreadDemo2(); td.setName("Thread1"); td1.setName("Thread2"); td.start(); td1.start(); td.yield(); System.out.println("Main Exited"); } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 69 Object Oriented Programming Through Java Laboratory Record 4) Write a program to demonstrate string tokenizer. import java.util.StringTokenizer; import java.io.*; class StringTockenizerDemo { public static void main(String naren[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter All String Digits with Spaces"); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 70 Object Oriented Programming Through Java Laboratory Record String str=br.readLine(); StringTokenizer st=new StringTokenizer(str); int a,sum=0; String s; while(st.hasMoreTokens()) { s=st.nextToken(); a=Integer.parseInt(s); sum=sum+a; } System.out.println("Sum of The given Integers"+sum); } } o/p: 5) Example of MultiThreads using Thread Class import java.io.*; class A extends Thread { public void run() { System.out.println("Start A"); for(int i=1; i<=5; i++) System.out.println("Thread A i :"+i); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 71 Object Oriented Programming Through Java Laboratory Record System.out.println("Exit A"); } } class B extends Thread { public void run() { System.out.println("Start B"); for(int j=1; j<=5; j++) System.out.println("Thread B j :"+j); System.out.println("Exit B"); } } class C extends Thread { public void run() { System.out.println("Start C"); for(int k=1; k<=5; k++) System.out.println("Thread C k :"+k); System.out.println("Exit C"); } } class D extends Thread { public void run() { System.out.println("Start D"); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 72 Object Oriented Programming Through Java Laboratory Record for(int l=1; l<=5; l++) System.out.println("Thread A l :"+l); System.out.println("Exit D"); }} class threadtest { public static void main(String S[])throws IOException { new A().start(); new B().start(); new C().start(); new D().start(); }} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 73 Object Oriented Programming Through Java Laboratory Record XIV) File I/O and Streams: A file is a collection of related records placed in a particular area on disk. Storing and managing data using files is known as file processing which includes creating,updating files and manipulation of data.Reading and writing of data in a file can be done at the level of bytes or characters or fields. Input refers to the flow of data into a program and output means the flow of data out of a program. A stream in java is a path along which data flows. The java.io package contains a large number of stream classes that provide capabilities for processing all type of data. 1) Wajp to Demonstration of FileOutputStream and PrintStream classes import java.io.*; class FileOutput { public static void main(String args[]) { FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object try { // Create a new file output stream connected to "myfile.txt" out = new FileOutputStream("myfile.txt"); // Connect print stream to the output stream p = new PrintStream( out ); p.println ("This is written to a file myFile.txt"); p.close(); } catch (Exception e) { System.err.println ("Error writing to the file myFile.txt"); }}} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 74 Object Oriented Programming Through Java Laboratory Record 2) Wajp to Write bytes to a file import java.io.*; class WriteBytes { public static void main(String args[]) { // declare and initialize a byte array byte cities[]={'D','E','L','H','I','\n','C','H','E','N','N','A','I','\n','L','O','N','D','O','N','\n'}; //create an output file stream FileOutputStream outfile=null; try { //connect the outfile stream to city.txt outfile=new FileOutputStream("city.txt"); //write data to the stream outfile.write (cities); outfile.close( ); } catch(IOException ioe) { System.out.println(ioe); System.exit(-1); } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 75 Object Oriented Programming Through Java Laboratory Record } } o/p: 3) Wajp to copy bytes from one file to another //copy bbytes from one to another import java.io.*; class CopyBytes { public static void main(String args[]) { //declare input and output file streams FileInputStream infile=null; FileOutputStream outfile=null; //declare a varible to hold a byte byte byteRead; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 76 Object Oriented Programming Through Java Laboratory Record try { //Connect infile to in.dat infile = new FileInputStream("in.dat"); //Connect outfile to in.dat outfile=new FileOutputStream("out.dat"); //Reading bytes from in.dat and writing to out.dat do { byteRead=(byte)infile.read( ); outfile.write(byteRead); } while(byteRead !=-1); } catch(FileNotFoundException e) { System.out.println("File not fopund"); } catch(IOException e) { System.out.println(e.getMessage( )); } finally //close files Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 77 Object Oriented Programming Through Java Laboratory Record { try { infile.close( ); outfile.close( ); } catch(IOException e) { } } } } o/p: XV) GUI and Event driven programming Applets: Applets are small java programs that are primarily used in internet computing. They can be transported over the internet from one computer to another and run using applet viewer or any web browser. Applets can perform arithmetic operations, display graphics, play sounds, accept user input , create animation, and play interactive games. Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 78 Object Oriented Programming Through Java Laboratory Record 1) Wajp for Sum of Two Numbers using Applet import java.awt.*; import java.applet.*; /*Coding of HTML File <applet code = abc1.class width= 200 height=200> </applet> */ public class abc1 extends Applet { public void paint(Graphics g) { int a=100; int b=200; int sum = a+b; String s = "The Sum is :" + String.valueOf(sum); g.drawString( s, 200,100); }} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 79 Object Oriented Programming Through Java Laboratory Record 2)Wajp for Applet using drawstring(), drawRect() and drawOval() import java.awt.*; import java.applet.*; /*<applet code= "Objectdraw.class" height=400 width=400> </applet>*/ public class Objectdraw extends Applet { public void paint(Graphics g) { g.drawString("Hello World",20,20); g.drawRect(40,40,30,50); g.drawOval(150,150,40,50); }} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 80 Object Oriented Programming Through Java Laboratory Record 3) Write a Java program to demonstrate banner applet. import java.awt.*; import java.applet.*; /*<HTML> <BODY> <APPLET CODE = "SampleBanner" WIDTH = "460" HEIGHT = "220"></APPLET> </BODY> </HTML> */ public class SampleBanner extends Applet implements Runnable { String str = "This is a simple Banner developed by Class Naren "; Thread t ; boolean b; Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 81 Object Oriented Programming Through Java Laboratory Record public void init() { setBackground(Color.gray); setForeground(Color.yellow); } public void start() { t = new Thread(this); b = false; t.start(); } public void run () { char ch; for( ; ; ) { try { repaint(); Thread.sleep(250); ch = str.charAt(0); str = str.substring(1, str.length()); str = str + ch; } catch(InterruptedException e) {} } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 82 Object Oriented Programming Through Java Laboratory Record } public void paint(Graphics g) { g.drawRect(1,1,300,150); g.setColor(Color.green); g.fillRect (1,1,300,150); g.setColor(Color.red); g.drawString(str, 1, 150); }} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 83 Object Oriented Programming Through Java Laboratory Record 4) wajp for Bouncing of a Ball using applet import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; /*<applet code= "Bounce.class" height=900 width=900> </applet>*/ class Ball { int x,y,radius,dx,dy; Color BallColor; public Ball(int x,int y,int radius,int dx,int dy,Color bColor) { this.x=x; this.y=y; this.radius=radius; this.dx=dx; this.dy=dy; BallColor=bColor; }} public class Bounce extends Applet implements Runnable { Ball redBall; public void init() { redBall=new Ball(250,80,50,2,4,Color.red); Thread t=new Thread(this); t.start(); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 84 Object Oriented Programming Through Java Laboratory Record } public void paint(Graphics g) { g.setColor(redBall.BallColor); setBackground(Color.pink); //g.setcolor(redBall.BallColor); g.fillOval(redBall.x, redBall.y, redBall.radius,redBall.radius); g.drawLine(150,400,50,500); g.drawLine(150,400,450,400); g.drawLine(50,500,350,500); g.drawLine(450,400,350,500); g.drawRect(50,500,20,100); g.drawRect(330,500,20,100); g.drawLine(450,400,450,500); g.drawLine(430,500,450,500); g.drawLine(430,500,430,420); } public void run() { while(true) { try { displacementOperation(redBall); Thread.sleep(20); repaint(); } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 85 Object Oriented Programming Through Java Laboratory Record catch(Exception e) { } } } public void displacementOperation(Ball ball) { if(ball.y >= 400 || ball.y <= 0) { ball.dy=-ball.dy; } ball.y=ball.y+ball.dy; } } o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 86 Object Oriented Programming Through Java Laboratory Record XVI) Abstract WindowToolkit(AWT): Awt contains numerous classes and methods that allow you to create and manage windows. A common use of the AWT is in applets , its is also used to sreate stand-alone windows that run in a GUI environment , such as Windows. 1) Wajp that prints a message by clicking on the button using AWT events and applets 1. import java.applet.*; 2. import java.awt.*; 3. import java.awt.event.*; 4. public class EventApplet extends Applet implements ActionListener 5. { 6. Button b; 7. TextField tf; 8. public void init() 9. { 10. tf=new TextField(); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 87 Object Oriented Programming Through Java Laboratory Record 11. tf.setBounds(30,40,150,20); 12. 13. b=new Button("Click"); 14. b.setBounds(80,150,60,50); 15. 16. add(b);add(tf); 17. b.addActionListener(this); 18. 19. setLayout(null); 20. } 21. 22. public void actionPerformed(ActionEvent e) 23. { 24. tf.setText("Welcome"); 25. } 26. } In the above example, we have created all the controls in init() method because it is invoked only once. myapplet.html 1. 2. 3. 4. 5. 6. <html> <body> <applet code="EventApplet.class" width="300" height="300"> </applet> </body> </html> Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 88 Object Oriented Programming Through Java Laboratory Record 2) Write a java program to Demonstrate GridLayout import java.awt.*; import java.applet.*; /* <applet code="GridLayoutDemo" width=300 height=200> </applet> */ public class GridLayoutDemo extends Applet { static final int n = 4; public void init() { setLayout(new GridLayout(n, n)); setFont(new Font("SansSerif", Font.BOLD, 24)); 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)); } } } } Output: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 89 Object Oriented Programming Through Java Laboratory Record Example of GridLayout class: 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. import java.awt.*; import javax.swing.*; public class MyGridLayout{ JFrame f; MyGridLayout(){ f=new JFrame(); JButton b1=new JButton("1"); JButton b2=new JButton("2"); JButton b3=new JButton("3"); JButton b4=new JButton("4"); JButton b5=new JButton("5"); JButton b6=new JButton("6"); JButton b7=new JButton("7"); JButton b8=new JButton("8"); JButton b9=new JButton("9"); f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); f.add(b6);f.add(b7);f.add(b8);f.add(b9); f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns f.setSize(300,300); f.setVisible(true); } public static void main(String[] args) { new MyGridLayout(); } } Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 90 Object Oriented Programming Through Java Laboratory Record 3) Write a Java program to demonstrate an application involving GUI with controls menus and event handling. import javax.swing.*; public class SwingMenu { public static void main(String[] args) { SwingMenu s = new SwingMenu(); } public SwingMenu() { JFrame frame = new JFrame("Creating a JMenuBar, JMenu, JMenuItem and seprator Component"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menubar = new JMenuBar(); JMenu filemenu = new JMenu("File"); filemenu.add(new JSeparator()); JMenu editmenu = new JMenu("Edit"); editmenu.add(new JSeparator()); JMenuItem fileItem1 = new JMenuItem("New"); JMenuItem fileItem2 = new JMenuItem("Open"); JMenuItem fileItem3 = new JMenuItem("Close"); fileItem3.add(new JSeparator()); JMenuItem fileItem4 = new JMenuItem("Save"); JMenuItem editItem1 = new JMenuItem("Cut"); JMenuItem editItem2 = new JMenuItem("Copy"); Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 91 Object Oriented Programming Through Java Laboratory Record editItem2.add(new JSeparator()); JMenuItem editItem3 = new JMenuItem("Paste"); JMenuItem editItem4 = new JMenuItem("Insert"); filemenu.add(fileItem1); filemenu.add(fileItem2); filemenu.add(fileItem3); filemenu.add(fileItem4); editmenu.add(editItem1); editmenu.add(editItem2); editmenu.add(editItem3); editmenu.add(editItem4); menubar.add(filemenu); menubar.add(editmenu); frame.setJMenuBar(menubar); frame.setSize(400,400); frame.setVisible(true); }} o/p: Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 92 Object Oriented Programming Through Java Laboratory Record Faculty name : G.kalpana Course: M.C.A Year/Sem : I st year /2nd sem 93