Sunteți pe pagina 1din 45

Object Oriented Programming using JAVA Lab

Laboratory manual for

OBJECT ORIENTED PROGRAMMING USING JAVA

II B. Tech II Semester for CSE

Prepared By B. BALAKRISHNA

Turbomachinery Institute of Technology & Sciences

Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Certificate

This is to certify that Mr. / Ms. .. RollNo.. of I/II/III/IV B.Tech I / II Semester of ...branch has completed the laboratory work satisfactorily in ........ Lab for the academic year 20 to 20 as prescribed in the curriculum.

Place: .. Date: ...

Lab In charge

Head of the Department

Principal

Turbomachinery Institute of Technology & Sciences

Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

INSTRUCTIONS TO STUDENTS
Students shall read the points given below for understanding the theoretical concepts and Practical applications. 1. Listen carefully to the lecture given by teacher about importance of subject, curriculum philosophy, Learning structure, skills to be developed, information about equipment, instruments, procedure, method of continuous assessment, tentative plan of work in Laboratory and total amount of work to be done in a semester 2. Students shall undergo study visit of the laboratory for types of equipment, instruments and material to be used, before performing experiments. 3. Read the write up of each experiment to be performed, a day in advance. 4. Organize the work in the group and make a record of all observations. 5. Understand the purpose of experiment and its practical implications. 6. Student should not hesitate to ask any difficulty faced during conduct of practical / exercise. 7. Student shall develop maintenance skills as expected by the industries. 8. Student should develop the habit of pocket discussion / group discussion related to the experiments/ exercises so that exchanges of knowledge / skills could take place. 9. Student should develop habit to submit the practical, exercise continuously and progressively should get the assessment done. 10. Student shall attempt to develop related hands - on - skills and gain confidence. 11. Student shall focus on development of skills rather than theoretical or codified knowledge. 12. Student shall visit the nearby workshops, workstation, industries, laboratories, technical exhibitions trade fair etc. even not included in the Lab Manual. In short, students should have exposure to the area of work right in the student hood. 13. Student shall develop the habit of evolving more ideas, innovations, skills etc. those included in the scope of the manual. 14. Student shall refer to technical magazines, proceedings of the Seminars, refer websites related to the scope of the subjects and update their knowledge and skills. 15. The student shall study all the questions given in the laboratory manual and practice to write the answers to these questions. on the scheduled dates and

INDEX
Turbomachinery Institute of Technology & Sciences 3 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

S.NO

NAME OF THE EXERCISE

Page No

Date of Performa nce

Date of Submission

Assessment of Marks (10 Marks)

Sign of Faculty

CYCLE - I a) Find the roots of quadratic equation ax2+bx+c = 0 b) Find the Fibonacci Sequences (Recursive and Non-Recursive) a) Print the all Prime numbers Week 2 b) Multiply two given Matrices c) Sum of all integer Using StringTokenizer class a) To find given string is Palindrome or not Week 3 b) Sorting names in ascending order a) Read the file, display and check read/write, find the length of the file Week 4 b) Read the file, display file with lines before each line c) Display the file number of character, lines and words in the text file a) Implement Stack ADT Week 5 b) Convert Infix expression to Postfix expression c) Evaluate Postfix Expression a) Display Simple message using Applet b) Compute Factorial value using Applet CYCLE - II Write program for simple calculator. Use a grid layout to arrange buttons for the digits and for the + - x / % operations Program for handling mouse events and key events 4 Department of Computer Science & Engg.

Week 1

Week 6

Week 7

Week 8

Turbomachinery Institute of Technology & Sciences

Object Oriented Programming using JAVA Lab

Week 9

a) Create three threads. 1 thread displays Good Morning every one second, 2 thread displays Hello every 2 seconds and the 3 thread displays Welcome every 3 seconds b) Implements ProducerConsumer problem using the concept of Inter Thread communication Create a user interface to perform integer divisions. The user enters two numbers in the text field, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a Number Format Exception. If Num2 were Zero, the program would an Arithmetic Exception Display the exception in a message dialog box. a) Write a java program that simulates traffic lights. The program lets the user select one of three lights: red, yellow, or green. When a radio button is selected, the light is turned on, and only one light can be on at a time No light is on when the program starts b) Write a Java program that allows the user to draw lines, rectangles and ovals. a) Write a java program to create an abstract class named shape that contains an empty method named number of sides (). Provide three classes named trapezoid, triangle and Hexagon such that each one of the classes extends the class shape. Each one of the class contains only the method number of sides () that shows the number of sides in the given geometrical figures b) Display a table using JTable component.(Table named table.txt)

Week 10

Week 11

Week 12

Week 1 a) : Program To check the nature of the roots of the Quadratic equation 1. AIM: Write a java program to generate the quadratic equation. Turbomachinery Institute of Technology & Sciences 5 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

2. Algorithm: 1. Start the program. Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. Read a string with InputStreamReader (System. in). 5. convert the string into Integer.parseInt(stdin.readLine()); 6. By using if(d==0) Roots are Equalent loop rotating the integer value. 7. if(d>0) Roots are Real otherwise ("Roots are Imaginary"); 8. Repeats enter the value until end of loop. 9. End of class and main method. 10. Stop the program. 3. PROGRAM: import java.io.*; import java.math.*; class quadratic { public static void main (String s[]) throws IOException { int a,b,c,d; double r1,r2; Buffered Reader bf=new BufferedReader (new InputStreamReader (System. in)); System.out.println ("Enter value of a:"); a=Integer.parseInt (br.readLine ()); System.out.println ("Enter value of b:"); b=Integer.parseInt (br.readLine ()); System.out.println ("Enter value of c:"); c=Integer.parseInt (br.readLine ()); d=b*b-4*a*c; if (d==0) { System.out.println ("Roots are Equivalent"); r1=-b/(2*a); r2=-b/(2*a); System.out.println ("Root1 = "+r1); System.out.println ("Root2 = "+r2); } else if (d>0) { System.out.println ("Roots are Real"); r1=(-b+Math.sqrt(d))/(2*a); r2=(-b-Math.sqrt(d))/(2*a); System.out.println ("Root1 = "+r1); System.out.println ("Root2 = "+r2); } else System.out.println ("Roots are Imaginary"); } 4. OUTPUT: Enter value of a:1 Enter value of b:2 Enter value of c:1 Turbomachinery Institute of Technology & Sciences 6 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Roots are Equalent Enter value of a:2 Enter value of b:3 Enter value of c:2 Roots are Imaginary Week 1 b) : Program to find the series of Fibonacci by using both Recursive and Non-Recursive 1. AIM: Write a java program to generate the Fibonacci series of given no. using Non-Recursive. Write a java program to generate the Fibonacci series of given no. using Recursive. Algorithm: 1. Start the program. Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. Read a string with Scanner object (System. in). 5. convert the string into sc.nextInt(); 6. call the method fibonacci. 7. declare the method fibonacci with parameters f1,f2 and n. 8. Initialize the values f1=0,f2=1 and add f1&f2. 9. now check the condition until n!=0. 10. call the method Fibonacci() repeateadly until the above condition is false the 11. End of class and main method. 12. Stop the program. 3. PROGRAM: // using Non-Recursive import java.io.*; import java.util.*; class Fibonacci { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter the Fibonacci series of:"); int n=Integer.parseInt(br.readLine()); long f1,f2,f; f1=0; f2=1; System.out.println(f1); System.out.println(f2); f=f1+f2; System.out.println(f); int count=3; while(count<n) { f1=f2; f2=f; f=f1+f2; System.out.println(f); count++; }}} // using Recursive import java.lang.*; import java.util.Scanner; class Fiborecursion { Turbomachinery Institute of Technology & Sciences 7 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

public static void main(String args[]) { int n; Scanner sc=new Scanner(System.in); System.out.println("enter the no."); n=sc.nextInt(); fibonacci(0,1,n); } static void fibonacci(int f1,int f2,int n) { if(n!=0) { System.out.println(f1 + "\t"); fibonacci(f2,f1+f2,n-1); } } } 4. OUTPUT: Enter first number: 5 Enter second number: 3 Addition of a and b = 8 Subtraction of a and b=2 Multiplication of a and b=15 Division of a and b=1.0

Turbomachinery Institute of Technology & Sciences

Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Week 2 a) : Program To find the series of prime no.s upto a given no. 1. AIM: Write a java program to generate the prime series of given no. 2. Algorithm: 1. Start the program. Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. Read a value through commandline arguments. 5. Declare the for loop for i and j values. 6. check the condition if(i%j==0) 7. if it is true then flag=1, so it is prime. 8. if it is not true ,so it is prime, then again set flag=0 then continue until the i for loop will be fails. 9. End of class and main method. 10. Stop the program. 3. PROGRAM: class Prime { public static void main(String args[]) { int i,j,n,flag=0; // Accepting the value at run time. n=args.length; // Loop to find whether the number is prime or not. for(i=1;i<=n;i++) { for(j=2;j<=i-1;j++) { if(i%j==0) { flag=1; } } // Display whether the number is prime or not. if(flag==1) System.out.println(i+"is not prime"); else System.out.println(i+"is prime"); flag=0; } } } 4. OUTPUT: java Prime 1 2 3 4 5 6 7 8 9 10 // total n=args.length=10 1is prime 2is prime 3is prime 4is not prime 5is prime 6is not prime 7is prime 8is not prime 9is not prime 10is not prime Turbomachinery Institute of Technology & Sciences 9 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Week 2 b) : Program to multiply two given matrices 1. AIM: Write a java program to multiplication of given two matrices. 2. Algorithm: 1. Start the program. Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. Read m & n values through command line arguments. 5. initialize the integer array a[] []& b[][] &c[][] variables 6. read the values into a[][] &b[][] in matrix form 7. then multiply a[][] & b[][], result stored into c[][]. 8. display the values of c[][] in matrix form. 9. End of class and main method. 10. Stop the program. 3. PROGRAM: int[ ][ ] findMul(int a[ ][ ],int import java.util.*; class Test { int r1,c1,r2,c2; Test(int r1,int c1,int r2,int c2) { this.r1=r1; this.c1=c1; this.r2=r2; this.c2=c2; } int[ ][ ] getArray(int r,int c) { int arr[][]=new int[r][c]; System.out.println("Enter the elements for "+r+"X"+c+" Matrix:"); Scanner input=new Scanner(System.in); for(int i=0;i<r;i++) for(int j=0;j<c;j++) arr[i][j]=input.nextInt(); return arr; } ul(int a[ ][ ],in t bt b[ b[ ][ ]) { int c[][]=new int[r1][c2]; for (int i=0;i<r1;i++) for (int j=0;j<c2;j++) { c[i][j]=0; for (int k=0;k<r2;k++) c[i][j]=c[i][j]+a[i][k]*b[k][j]; } return c; } void putArray(int res[ ][ ]) { System.out.println ("The resultant "+r1+"X"+c2+" Matrix is:"); for (int i=0;i<r1;i++) { Turbomachinery Institute of Technology & Sciences 10 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

for (int j=0;j<c2;j++) System.out.print(res[i][j]+" "); System.out.println(); } } } //end of Test class class MatrixMul { public static void main(String args[ ])throws IOException { Test obj1=new Test(2,3,3,2); Test obj2=new Test(2,3,3,2); int x[ ][ ],y[ ][ ],z[ ][ ]; System.out.println("MATRIX-1:"); x=obj1.getArray(2,3); //to get the matrix from user System.out.println("MATRIX-2:"); y=obj2.getArray(3,2); z=obj1.findMul(x,y); //to perform the multiplication obj1.putArray(z); // to display the resultant matrix } } 4. OUTPUT MATRIX-1: Enter the elements for 2*3 matrix: 111111 MATRIX-2: Enter the elements for 2*3 matrix: 111111 The resultant 2*2 matrix is: 3 3 3 3 Week 2 c) : Program To find sum of given line of integers and display the line of integers 1. AIM: Write a java program to find sum of given line of integers 2. Algorithm: 1. Start the program. Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. Read string value by using BufferedReader class and convert into integer,then stored into n 5. check the while loop as if n>=0 6. take the modulo of given integer &then add reminder to sum variable. 7. divide n by 10 and check while loop 8. repeat the while loop until the condition is false 9. End of class and main method. 10. Stop the program.

Turbomachinery Institute of Technology & Sciences

11

Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

3. PROGRAM: \\sum of individual integers // Using StringTokenizer class import java.lang.*; import java.util.*; class tokendemo { public static void main(String args[ ]) { String s="10,20,30,40,50"; int sum=0; StringTokenizer a=new StringTokenizer(s,",",false); System.out.println("integers are "); while(a.hasMoreTokens()) { int b=Integer.parseInt(a.nextToken()); sum=sum+b; System.out.println(" "+b); } System.out.println("sum of integers is "+sum); } } // Alternate solution using command line arguments class Arguments { public static void main(String args[ ]) { int sum=0; int n=args.length; System.out.println("length is "+n); int arr[]=new int[n]; for(int i=0;i<n;i++) arr[i]=Integer.parseInt(args[i]); System.out.println("The enterd values are:"); for(int i=0;i<n;i++) System.out.println(arr[i]); System.out.println("sum of enterd integers is:"); for(int i=0;i<n;i++) sum=sum+arr[i]; System.out.println(sum); } }

4. OUTPUT Integers are 10 20 30 40 50 Sum of integers is 150 Turbomachinery Institute of Technology & Sciences 12 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Week 3 a): Program To find given string is palindrome or not 1. AIM: Write a java program to find the given string is palindrome or not. 2. Algorithm: 1. Start the program. Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. Read string value by using BufferedReader class and assign into temporary variable. 5. convert String variable str into StringBuffer class object(sb). 6. to reverse the contents of StringBuffer object by using reverse method.. 7. again convert the StringBuffer object into String object. 8. then compare the temporary variable temp and String variable str. 9. both are equal then print the relavent statement. 10. End of class and main method. 11. Stop the program. 3. PROGRAM: import java.io.*; class Palindromestring { public static void main(String args[])throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter a string:"); String str=br.readLine(); String temp=str; StringBuffer sb=new StringBuffer(str); sb.reverse(); str=sb.toString(); if(temp.equalsIgnoreCase(str)) System.out.println(temp+ "is a palindrome"); else System.out.println(temp+ " is not a palindrome"); } } 4. OUTPUT: enter a string: liril lirilis a palindrome enter a string: mech mech is not a palindrome

Week 3 b) : Program To sort the given strings 1. AIM: Write a java program to sort the given strings in Ascending order. 2. Algorithm: 1. Start the program. Import the packages. 2. create the implementation class of the Comparator interface with generic data type. Turbomachinery Institute of Technology & Sciences 13 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

3. then implement the method of Comparator interface in implementation class. 4. Create another class and variables with data types. 5. Declaration of the main class. 6. Read string value by using BufferedReader class and convert into integer variable. 7. then declare the String array variable Str[] 8. then read the strings one by one using for loop into str[] 9. then create the object for the implementation class of interface 10. then sort the elements by the method Arrays.sort() and sent all the sorted elements to implementation class 11. to check all the elements are sorted or not by using compare() method of interface. 12. then display all the elements by using the method of display() 13. End of class and main method. 14. Stop the program 3. PROGRAM: import java.io.*; import java.util.*; class Ascend implements Comparator<String> { public int compare(String s1,String s2) { return s1.compareTo(s2); } } class ArraySorting { public static void main(String args[]) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("how many string:"); int size=Integer.parseInt(br.readLine()); String str[]=new String[size]; for(int i=0;i<size;i++) { System.out.println("enter the string:"); str[i]=br.readLine(); } Ascend str1=new Ascend(); Arrays.sort(str,str1); System.out.println("sorted elements in ascending order are:"); display(str); } static void display(String str[]) { for(String i:str) System.out.println(i+"\t"); } } 4. OUTPUT: how many string: 5 enter the string: ram enter the string: raj enter the string: syam enter the string: rakesh enter the string: sai sorted elements in ascending order are: raj Turbomachinery Institute of Technology & Sciences 14 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

rakesh ram sai syam

Week 4 a): Write a Java program to check the file properties. 1. AIM: Write a java program to check the file properties like... it is exist, is it readable, writable, its type, its length in terms of bytes. 2. Algorithm: 1. Start the program. 2. Import the packages. 3. Create a class variable to read the file name through command prompt. 4. Create the File class object and assign the file name to file class object. 5. Then get all the properties of file using File class methods. 6. Then print all the properties (sb). 7. End of class and main method. 8. stop the program 3. PROGRAM: import java.io.*; class Fileprop { public static void main(String args[]) { String fname=args[0]; File f=new File(fname); System.out.println("filename:"+f.getName()); System.out.println("path:"+f.getPath()); System.out.println("absolute path:"+f.getAbsolutePath()); System.out.println("parent:"+f.getParent()); System.out.println("exists:"+f.exists()); if(f.exists()) { System.out.println("is writable:"+f.canWrite()); System.out.println("is readable:"+f.canRead()); System.out.println("is a directory:"+f.isDirectory()); System.out.println("file size in bytes:"+f.length()); } } } 4. OUTPUT: filename:Prime.java path:Prime.java absolute path:D:\ramsir\546\Prime.java parent:null exists:true is writable:true is readable:true is a directory:false file size in bytes:489 Turbomachinery Institute of Technology & Sciences 15 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Week 4 b): Write a Java program that reads a file and displays the file on the screen, with a line number before each line. 1. AIM: Write a java program to read the file and displays its contents with line no.s before each line 2. Algorithm: 1. Start the program. Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. Read a string with inputstreamReader(System.in). 5. convert the string into Integer.parseInt(stdin.readLine()); 6. By using for loop rotating the integer value. 7. Repeats enter the value until end of loop. 8. End of class and main method. 9. Stop the program. 3. PROGRAM: // Import the packages to access FileStream classes. import java.io.*; class file2 { public static void main(String args[]) throws Exception { // Creating FileInputStream and read the data in abc.java. FileInputStream f1=new FileInputStream("abc.java"); int n=f1.available(); System.out.println(n); int j=1; // Loop to read the contents of file and display the content. for(int i=0;i<n;i++) { char ch=(char)f1.read(); char c='\n'; // loop to check whether it is the end of the line if(c==ch) { System.out.print(""+j); j++; } System.out.print(ch); } } } // The data in abc.java. abc.java class abc { public static void main(String args[]) { } } Turbomachinery Institute of Technology & Sciences 16 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

4. OUTPUT 1 class abc 2{ 3 public static void main(String args[]) 4 { 5 } 6}

Week 4 c): Write a Java program that displays the number of characters, lines and words in a text file. 1. AIM: Write a java program to read the file and displays no. of characters, words and lines in that.. 2. Algorithm: 1. Start the program and Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. Read filename into FileInputStream through command prompt 5. take the characters one by one from the file and stored into ch. 6. count the no. of characters if ch is not space character 7. count the no. of words if ch is space character and previous character is not space character. 8. count the no. lines if ch is new line character (or) if ch is newline character and ch is . 9. print the no. of characters, words and lines.. 10. close the main and class. 11. Stop the program. 3. PROGRAM: import java.io.*; public class Countcwl { public static void main(String args[]) throws IOException { int ch; boolean prev=true; int char_count=0; int word_count=0; int line_count=0; FileInputStream fin=new FileInputStream(args[0]); while((ch=fin.read())!=-1) { if(ch!=' ')++char_count; if(!prev && ch==' ')++word_count; if(ch==' ')prev=true; else prev=false; if(ch=='\n'||(ch=='.'&&ch=='\n')) } char_count -=line_count*2; word_count +=line_count; System.out.println("no of chars:"+char_count); System.out.println("no of words:"+word_count); System.out.println("no of lines:"+line_count); fin.close(); } } 4. OUTPUT: Turbomachinery Institute of Technology & Sciences 17 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

java Countcwl abc.java no of chars:52 no of words:9 no of lines:5 Week 5 a) : program implementation of stack ADT 1. AIM: Write a java program to implement the stack ADT(Abstract Data Type). 2. Algorithm: 1. Start the program. Import the packages. 2. Create a class and variables with data types. 3. Declaration of the main class. 4. create and implements the methods for push(), pop(), and search() 5. then read the particular option from the keyboard 6. then the relevant task will be executed 7. if u select choice1 then the push operation will be executed 8. if u select choice2 then the pop operation will be executed 9. if u select choice3 then the search operation will be executed 10. if u select choice4 then exit from the stack and from the program 11. Close the main and class. 12. Stop the program. 3. PROGRAM: // Import the packages. import java.io.*; import java.lang.*; import java.util.*; // Class to perform operations of push, pop,search an element. class stack { public static void main(String args[]) throws Exception { Stack<Integer> st=new Stack<Integer>(); int choice=0; int position,element; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); while(choice<4) { System.out.println("Stack Operations"); System.out.println("1. Push an element"); System.out.println("2.Pop an element"); System.out.println("3.Search an element"); System.out.println("Enter your choice"); // Assigning the value to perform the operation. choice=Integer.parseInt(br.readLine()); // Switch case to perform the operation. switch(choice) { // Operation to be performed when entering the element. case 1: System.out.println("Enter an element"); element = Integer.parseInt(br.readLine()); Turbomachinery Institute of Technology & Sciences 18 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

st.push(element); break; // Operation to be performed when getting the element. case 2: System.out.println("Which element ? "); Integer obj = st.pop(); System.out.println("Poped element= "+obj); break; // Operation to be performed to search the element. case 3: System.out.println("Which an element ? "); element = Integer.parseInt(br.readLine()); position = st.search(element); // Loop to display the element and position. if(position==-1) System.out.println("Element not found"); else System.out.println("postion of the element is:= "+position); break; default: return; } } } } 4. OUTPUT: Stack Operations 1. Push an elemen 2.Pop an element 3.Search an eleme Enter your choice 1 Enter an element 34 Stack Operations 1. Push an elemen 2.Pop an element 3.Search an eleme Enter your choice 2 Which element ? Poped element= 34 Stack Operations 1. Push an elemen 2.Pop an element 3.Search an eleme Enter your choice 4

Turbomachinery Institute of Technology & Sciences

19

Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Week 5 b) : Converts infix to postfix form 1. AIM: Write a java program that converts infix to postfix form 2. Algorithm: 1. Import the package to access classes in io package. 2. Class to display the elements. 3. Method to initialize stack size 4. Method to enter the elements into the stack. 5. Method to get the elements from the stack. 6. Method to get the top element of the stack. 7. Method to check whether the stack is empty. 8. Method to return the size of the stack. 9. Method to return the element in stack array. 10. Method to display the stack contents. 11. Class to convert infix to postfix. 12. Method to convert infix to postfix. 13. Method to check the characters and perform the operation 14. Method to check the precedence of the characters and 15. Perform the operation. 16. Class that takes infix form and converts it into postfix form using 17. Methods in into Post class. 18. Loop that takes the infix form. 19. Create object of InToPost. 20. Call the method in InTopost class 21. Displays the postfix form. 22. Creates objects of the stream readers and BufferReader. 3. PROGRAM: // Import the package to access classes in io package. import java.io.*; // Class to display the elements . class StackX { private int maxSize; private char[] stackArray; private int top; // Method to initialize stack size . public StackX(int s) { maxSize=s; stackArray=new char[maxSize]; top=-1; } // Method to enter the elements into the stack. public void push(char j) { stackArray[++top]=j; } // Method to get the elements from the stack. public char pop() { Turbomachinery Institute of Technology & Sciences 20 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

return stackArray[top--]; } // Method to get the top element of the stack. public char peek() { return stackArray[top]; } // Method to check whether the stack is empty. public boolean isEmpty() { return (top==-1); } / / Method to return the size of the stack. public int size() { return top+1; } // Method to return the element in stack array. public char peekN(int n) { return stackArray[n]; } // Method to display the stack contents. public void displayStack(String s) { System.out.println(s); System.out.print("stack(bottom-->top:"); for(int j=0;j<size();j++) { System.out.print(peekN(j)); } System.out.println(" "); } } // Class to convert infix to postfix. class InToPost { private StackX theStack; private String input; private String output; // Method to convert infix to postfix. public InToPost(String in) { input=in; int stackSize=input.length(); theStack=new StackX(stackSize); } // Method to check the characters and perform the operation. public String doTrans() { for(int j=0;j<input.length();j++) { char ch=input.charAt(j); theStack.displayStack("For"+ch+" "); switch(ch) { case '+': Turbomachinery Institute of Technology & Sciences 21 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

case '-': gotOper(ch,1); break; case '*': case '/': case '_': gotOper(ch,2); break; case '(': theStack.push(ch); break; case ')': gotParen(ch); break; default: output=output+ch; break; } } while(!theStack.isEmpty()) { theStack.displayStack("while"); output=output+theStack.pop(); } theStack.displayStack("End"); return output; } // Method to check the precedence of the characters and // perform the operation. public void gotOper(char opThis,int prec1) { while(!theStack.isEmpty()) { char opTop=theStack.pop(); if(opTop=='(') { theStack.push(opTop); break; } else { int prec2; if(opTop=='+'||opTop=='-') prec2=1; else prec2=2; if(prec2 < prec1) { theStack.push(opTop); break; } else output=output+opTop; } } theStack.push(opThis); } Turbomachinery Institute of Technology & Sciences 22 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

public void gotParen(char ch) { while(!theStack.isEmpty()) { char chx=theStack.pop(); if(chx=='(') break; else output=output+chx; } } } // Class that takes infix form and converts it into postfix form using // methods in inToPost class. class InfixApp { public static void main(String args[]) throws IOException { String input,output; // Loop that takes the infix form. while(true) { System.out.print("enter infix"); input=getString(); if(input.equals("")) break; // Create object of InToPost. InToPost theTrans=new InToPost(input); // Call the method in InTopost class. output=theTrans.doTrans(); // Displays the postfix form. System.out.println("postfix is "+output+"\n"); } } public static String getString() throws IOException { // Creates objects of the stream readers and BufferReader. InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); String s=br.readLine(); return s; } } 4. OUTPUT Input: Enter infix 5*(8+3*7)+22 Output: For stack(bottom-->top: For5 stack(bottom-->top: For* stack(bottom-->top: For( stack(bottom-->top:* For8 Turbomachinery Institute of Technology & Sciences 23 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

stack(bottom-->top:*( For+ stack(bottom-->top:*( For3 stack(bottom-->top:*(+ For* stack(bottom-->top:*(+ For7 stack(bottom-->top:*(+* For) stack(bottom-->top:*(+* For+ stack(bottom-->top:* For2 stack(bottom-->top:+ For2 stack(bottom-->top:+ while stack(bottom-->top:+ End stack(bottom-->top: postfix is null 5837*+*22+ Week 6 a): Write an Applet that displays a simple message. 1. AIM: Write a java program to create an applet and displays a simple message on the screen. 2. Algorithm: 1. Start the program. Import the packages. 2. Create a class and extends with Applet. 3. call the paint() method of graphics class object 4. using graphics class object call the graphics class methods 5. i.e call the drawstring() method to display the message on the applet 6. compile the java file and get java byte code file 7. create an applet in a separate file using html tags 8. include the java byte code file into an applet using code attribute 9. Execute the applet code using Appletviewer command at command prompt. 3. PROGRAM: Applet1.java: // Import the packages to access the classes and methods in awt and applet classes. import java.awt.*; import java.applet.*; public class Applet1 extends Applet { // Paint method to display the message. public void paint(Graphics g) { g.drawString("HELLO WORLD",20,20); } } Applet1.html: Turbomachinery Institute of Technology & Sciences 24 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

/* <applet code="Applet1" width=200 height=300> </applet>*/

4. OUTPUT:

Week 6 b): ) Develop an applet that receives an integer in one text field, and computes its factorial value and returns it in another text field, when the button named compute is clicked 1. AIM: Write an applet that computes the payment of a loan. 2. Algorithm: 1. Import the packages. 2. Applet program that calculates the principle. 3. Creation of labels. 4. Creation of textfields. 5. Add controls to the applet viewer. 6. Add Listeners to perform the action. 7. Implementing the method in action listener. 8. Display the output on the applet viewer. 3. PROGRAM: // Import the packages. import java.awt.*; import java.awt.event.*; import java.applet.*; // Applet program that calculates the principle. public class prin extends Applet implements ActionListener { TextField t1,mon,intr,prin; String msg=""; Turbomachinery Institute of Technology & Sciences 25 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

// Initialize the applet. public void init() { // Creation of labels. Label l1=new Label("amount"); Label l2=new Label("months"); Label l3=new Label("Intrest"); Label l4=new Label("principle"); // Creation of textfields. t1=new TextField(10); mon=new TextField(10); intr=new TextField(10); prin=new TextField(20); // Add controls to the applet viewer. add(l1); add(t1); add(l2); add(mon); add(l3); add(intr); add(l4); add(prin); // Add Listeners to perform the action. t1.addActionListener(this); mon.addActionListener(this); intr.addActionListener(this); prin.addActionListener(this); } int x,x1,x2; // Implementing the method in action listener. public void actionPerformed(ActionEvent ae) { repaint(); } // Display the output on the applet viewer. public void paint(Graphics g) { g.drawString("amount"+t1.getText(),100,100); g.drawString("months"+mon.getText(),100,120); g.drawString("intrest"+intr.getText(),100,160); String s1=t1.getText(); String s2=mon.getText(); String s3=intr.getText(); Turbomachinery Institute of Technology & Sciences 26 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

int x=Integer.parseInt(s1); int x1=Integer.parseInt(s2); int x2=Integer.parseInt(s3); int x4=(x*x1*x2)/100; int pri=(x+x4); String s4=""; s4=s4+pri; print.setText(s4); } } 4. OUTPUT:

Week 7 : Develop an Grid layout by creating calculator 1. AIM: Write a java program that works as a simple calculator. Use a Grid Layout to arrange Buttons for digits and for the + - * % operations. Add a text field to display the result. 2. Algorithm: 1. Start the program. Import the packages. 2. Create class that initialize the applet and create calculator. 3. Class that creates the calculator panel. 4. Creation of JButton. 5. Create the JObjectPane 6. Creation of control panel of calculator and adding buttons Using GridLayout 7. Implementing method in ActionListener 8. create an applet in a separate file using html tags 9. include the java byte code file into an applet using code attribute 10. Execute the applet code using Appletviewer command at command prompt. 3. PROGRAM: // Import the javax , awt packages and the classes. import javax.swing.*; import javax.swing.JOptionPane; import java.awt.*; import java.awt.event.*; // Class that initialize the applet and create calculator. Turbomachinery Institute of Technology & Sciences 27 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

public class Calculator extends JApplet { public void init() { CalculatorPanel calc=new CalculatorPanel(); getContentPane().add(calc); } } // Class that creates the calculator panel . class CalculatorPanel extends JPanel implements ActionListener { // Creation of JButton. JButton n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul, div,dot,equal; static JTextField result=new JTextField("0",45); static String lastCommand=null; // Create the JObjectPane. JOptionPane p=new JOptionPane(); double preRes=0,secVal=0,res; private static void assign(String no) { if((result.getText()).equals("0")) result.setText(no); else if(lastCommand=="=") { result.setText(no); lastCommand=null; } else result.setText(result.getText()+no); } // Creation of control panel of calculator and adding buttons // using GridLayout. public CalculatorPanel() { setLayout(new GridLayout()); result.setEditable(false); result.setSize(300,200); add(result); JPanel panel=new JPanel(); panel.setLayout(new GridLayout(5,5)); n7=new JButton("7"); panel.add(n7); n7.addActionListener(this); n8=new JButton("8"); panel.add(n8); n8.addActionListener(this); n9=new JButton("9"); panel.add(n9); n9.addActionListener(this); div=new JButton("/"); panel.add(div); div.addActionListener(this); n4=new JButton("4"); panel.add(n4); n4.addActionListener(this); n5=new JButton("5"); Turbomachinery Institute of Technology & Sciences 28 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

panel.add(n5); n5.addActionListener(this); n6=new JButton("6"); panel.add(n6); n6.addActionListener(this); mul=new JButton("*"); panel.add(mul); mul.addActionListener(this); n1=new JButton("1"); panel.add(n1); n1.addActionListener(this); n2=new JButton("2"); panel.add(n2); n2.addActionListener(this); n3=new JButton("3"); panel.add(n3); n3.addActionListener(this); minus=new JButton("-"); panel.add(minus); minus.addActionListener(this); dot=new JButton("."); panel.add(dot); dot.addActionListener(this); n0=new JButton("0"); panel.add(n0); n0.addActionListener(this); equal=new JButton("="); panel.add(equal); equal.addActionListener(this); plus=new JButton("+"); panel.add(plus); plus.addActionListener(this); add(panel); } // Implementing method in ActionListener. public void actionPerformed(ActionEvent ae) { if(ae.getSource()==n1) assign("1"); else if(ae.getSource()==n2) assign("2"); else if(ae.getSource()==n3) assign("3"); else if(ae.getSource()==n4) assign("4"); else if(ae.getSource()==n5) assign("5"); else if(ae.getSource()==n6) assign("6"); else if(ae.getSource()==n7) assign("7"); else if(ae.getSource()==n8) assign("8"); else if(ae.getSource()==n9) assign("9"); else if(ae.getSource()==n0) assign("0"); else if(ae.getSource()==dot) { if(((result.getText()).indexOf("."))==-1) result.setText(result.getText()+"."); } else if(ae.getSource()==minus) { preRes=Double.parseDouble(result.getText()); lastCommand="-"; result.setText("0"); Turbomachinery Institute of Technology & Sciences 29 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

} else if(ae.getSource()==div) { preRes=Double.parseDouble(result.getText()); lastCommand="/"; result.setText("0"); } else if(ae.getSource()==equal) { secVal=Double.parseDouble(result.getText()); if(lastCommand.equals("/")) res=preRes/secVal; else if(lastCommand.equals("*")) res=preRes*secVal; else if(lastCommand.equals("-")) res=preRes-secVal; else if(lastCommand.equals("+")) res=preRes+secVal; result.setText(" "+res); lastCommand="="; } else if(ae.getSource()==mul) { preRes=Double.parseDouble(result.getText()); lastCommand="*"; result.setText("0"); } else if(ae.getSource()==plus) { preRes=Double.parseDouble(result.getText()); lastCommand="+"; result.setText("0"); } } } Calculator.html <applet code="Calculator" width=200 height=300> </applet> 1. OUTPUT:

Turbomachinery Institute of Technology & Sciences

30

Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Week 8: Write a Java program for handling mouse events 1. AIM: Write a java program to implement the APPLET PACKAGES, draw Mouse event handler programs. 2. Algorithm: 1. Import the packages awt and applet. 2. Class that handles mouse events. 3. Method to initialize the applet. 4. Method to handle mouse clicked event. 5. Method to handle mouse entered event. 6. Method to handle mouse entered event. 7. Method to handle mouse pressed event. 8. Method to handle mouse relesed event. 9. Method to handle mouse dragged event. 10.Method to handle mouse moved event . 11.Method to display the message.

3. Program: import java.awt.*; import java.applet.*; import java.awt.event.*; public class MouseDemo extends Applet implements MouseListener,MouseMotionListener { Turbomachinery Institute of Technology & Sciences 31 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

int mx=0; int my=0; String msg=""; public void init() { addMouseListener(this); addMouseMotionListener(this); } public void mouseClicked(MouseEvent me) { mx=20; my=40; msg="Mouse Clicked"; repaint(); } public void mousePressed(MouseEvent me) { mx=30; my=60; msg="Mouse Pressed"; repaint(); } public void mouseReleased(MouseEvent me) { mx=30; my=60; msg="Mouse Released"; repaint(); } public void mouseEntered(MouseEvent me) { mx=40; my=80; msg="Mouse Entered"; repaint(); } public void mouseExited(MouseEvent me) { mx=40; my=80; msg="Mouse Exited"; repaint(); } public void mouseDragged(MouseEvent me) { mx=me.getX(); my=me.getY(); showStatus("Currently mouse dragged"+mx+" "+my); repaint(); } public void mouseMoved(MouseEvent me) { mx=me.getX(); my=me.getY(); showStatus("Currently mouse is at"+mx+" "+my); repaint(); } Turbomachinery Institute of Technology & Sciences 32 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

public void paint(Graphics g) { g.drawString("Handling Mouse Events",30,20); g.drawString(msg,60,40); } } /* <html> <title>mouse motions</title> <applet code="MouseDemo1" width=300 height=300> </applet> </html> */ 4. OUTPUT:

Week 9 a) : Write a Java program to create thread communication. 1. AIM: Write a Java program that creates three threads. First thread displays Goof Morning every one second the second thread displays Hello every two seconds and the the third thread displays Welcome every three seconds 2. Algorithm: Turbomachinery Institute of Technology & Sciences 33 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

1. start the program 2. create the first thread 3. call the run() method 4. sleep the first thread 1sec 5. create the second thread 6. call the run() method 7. sleep the second thread for 2sec 8. create the third thread 9. call the run() method 10. sleep the third thread 3sec 11. create the main class 12. open the main method 13. create the thread class object 14. create the objects for threads one, two, three 15. start the first thread 16. after 1sec sleep the first thread and start the second thread 17. after 2 sec sleep the second and first thread ,then start the third thread 18. Stop the program. 3. PROGRAM: // Using Thread class class One extends Thread { public void run() { for ( ; ; ) { Try { sleep(1000); } catch(InterruptedException e) {} System.out.println("Good Morning"); } } } class Two extends Thread { public void run() { for ( ; ; ) { Try { sleep(2000); } catch(InterruptedException e) {} System.out.println("Hello"); } } } class Three extends Thread { public void run() Turbomachinery Institute of Technology & Sciences 34 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

{ for ( ; ; ) { Try { sleep(3000); } catch(InterruptedException e) {} System.out.println("Welcome"); } } } class MyThread { public static void main(String args[ ]) { Thread t = new Thread(); One obj1=new One(); Two obj2=new Two(); Three obj3=new Three(); Thread t1=new Thread(obj1); Thread t2=new Thread(obj2); Thread t3=new Thread(obj3); t1.start(); try { t.sleep(1000); } catch(InterruptedException e) {} t2.start(); try { t.sleep(2000); } catch(InterruptedException e) {} t3.start(); try { t.sleep(3000); } catch(InterruptedException e) {} } } // Using Runnable interface class One implements Runnable { One( ) { new Thread(this, "One"); start(); try Turbomachinery Institute of Technology & Sciences 35 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

{ Thread.sleep(1000); } catch(InterruptedException e) {} } public void run() { for ( ; ; ) { try{ Thread.sleep(1000); } catch(InterruptedException e) {} System.out.println("Good Morning"); } } } class Two implements Runnable { Two( ) { new Thread(this, "Two") start(); try { Thread.sleep(2000); } catch(InterruptedException e) {} } public void run() { for ( ; ; ) { Try { Thread.sleep(2000); } catch(InterruptedException e) {} System.out.println("Hello"); } } } class Three implements Runnable { Three( ) { new Thread(this, "Three").start(); try { Thread.sleep(3000); } catch(InterruptedException e) {} Turbomachinery Institute of Technology & Sciences 36 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

} public void run() { for ( ; ; ) { Try { Thread.sleep(3000); } catch(InterruptedException e) {} System.out.println("Welcome"); } } } class MyThread { public static void main(String args[ ]) { One obj1=new One(); Two obj2=new Two(); Three obj3=new Three(); } } 4. OUTPUT: Good morning Good morning Hello Good morning Good morning Hello Good morning Welcome Good morning Hello Good morning Good morning

Week 9 b) : Program To write producer consumer problem 1. AIM: Write a java program that correctly implements the producer consumer Problem using the concept of inter theread communication. 2. Algorithm: 1. Start the program. Import the packages. 2. create the class for synchronized block to communicating threads Turbomachinery Institute of Technology & Sciences 37 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

3. create the code for producer and consumer 4. create the main class and main method 5. Synchronizing the Producer Consumer through interprocess communication. 6. end of the main 7. end of class. 8. Stop the program. 3. PROGRAM: class Q { int n; boolean value=false; //Communicating the threads. synchronized int get() { if(!value) try { wait(); } catch(InterruptedException e) { System.out.println("Interrupted Exception caught"); } System.out.println("Got"+n); value=false; notify(); return n; } synchronized void put(int n) { if(value) try { wait(); } catch(InterruptedException e) { System.out.println("Interrupted Exception caught"); } this.n=n; value=true; System.out.println("Put"+n); notify(); } } class Producer implements Runnable { Q q; // Code for Producer. Producer(Q q) { this.q=q; Turbomachinery Institute of Technology & Sciences 38 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

new Thread(this,"producer").start(); } public void run() { int i=0; while(true) { q.put(i++); } } } class Consumer implements Runnable { Q q; // Code for Consumer. Consumer(Q q) { this.q=q; new Thread(this,"consumer").start(); } public void run() { int i=0; while(true) { q.get(); } } } class pc { public static void main(String args[]) { Q q=new Q(); // Synchronizing the Producer Consumer thru // interprocess communication. new Producer(q); new Consumer(q); System.out.println("Print ctrl-c to stop"); } } 4. OUTPUT: Got11946 Put11947 Got11947 Put11948 Got11948 Put11949 Got11949 Put11950 Turbomachinery Institute of Technology & Sciences 39 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Got11950 Put11951 Got11951 Put11952 Got11952 Put11953 Got11953 Put11954 Got11954 Put11955 Got11955 Put11956 Got11956 Put11957 Got11957

Week 11 a) :Write a java program to simulate a traffic light. 1. AIM: Write a java program to simulate a traffic light. The program lets the user select one pf the three lights: red, yellow or green. When a radio button is selected, the light is turned on and only one light can be on at a time no light is on when program starts. 2. Algorithm: 1. 2. 3. 4. 5. 6. 7. 8. Start the program. Import the packages. Class that allows user to select the traffic lights. Add the buttons to the container. Add listeners to perform action Implement methods in Item Event class. create the main class Close the main and class. Stop the program.

3. PROGRAM: // Import the packages. import javax.swing.*; import java.awt.*; import java.awt.event.*; // Class that allows user to select the traffic lights. public class Trafficlight extends JFrame implements ItemListener { JRadioButton redbut,yellowbut,greenbut; public Trafficlight() { Container c = getContentPane(); c.setLayout(new FlowLayout()); // Create the button group. ButtonGroup group= new ButtonGroup(); redbut = new JRadioButton("Red"); yellowbut = new JRadioButton("Yellow"); greenbut = new JRadioButton("Green"); Turbomachinery Institute of Technology & Sciences 40 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

group.add(redbut); group.add(yellowbut); group.add(greenbut); // Add the buttons to the container. c.add(redbut); c.add(yellowbut); c.add(greenbut); // Add listeners to perform action redbut.addItemListener(this); yellowbut.addItemListener(this); greenbut.addItemListener(this); addWindowListener(new WindowAdapter() { // Implement methods in Window Event class. public void windowClosing(WindowEvent e) { System.exit(0); } } ); setTitle("Traffic Light "); setSize(250,200); setVisible(true); } // Implement methods in Item Event class. public void itemStateChanged(ItemEvent e) { String name= " ",color=" "; if(redbut.isSelected() ) name = "Red"; else if(yellowbut.isSelected() ) name = "Yellow"; else if(greenbut.isSelected() ) name = "Green"; JOptionPane.showMessageDialog(null,"The "+name+" light "MessgeBox", JOptionPane.INFORMATION_MESSAGE); } public static void main(String args[] ) { new trafficlight(); } }

is simulated,

4. OUTPUT:

Turbomachinery Institute of Technology & Sciences

41

Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

Week 11 b) :Program to draw Lines, Rectangles, Rounded Rectangles, filled Polygons and Ovals 1. AIM: Write a java program to implement the APPLET PACKAGES, draw Lines, Rectangles, Rounded Rectangles, filled Polygons programs. 2. Algorithm: 1. Start the program. 2. Import the packages of applet,awt,awt.event. 3. Create a classes: public void paint(Graphics g). 4. Assume the values of string, color and font. 5. g.drawString() application of Graphical User Interface. 6. Printing in the separated Applet viewer window. 7. Stop the program. 3. PROGRAM: import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code="ShapeDemo" width=300 height=300> </applet*/ public class ShapeDemo extends Applet { public void paint(Graphics g) { setLayout(new FlowLayout()); g.drawLine(10,20,50,20); g.drawRect(20,30,30,30); g.setColor(Color.RED); g.fillRect(20,30,30,30); g.drawRoundRect(20,70,50,70,15,15); g.setColor(Color.GREEN); g.fillRoundRect(20,70,50,70,15,15); g.drawOval(20,150,50,50); g.setColor(Color.BLUE); g.fillOval(20,150,50,50); } }

Turbomachinery Institute of Technology & Sciences

42

Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

4. OUTPUT:

Week 12 a) : Write a java program to create an abstract class named shape that contains an empty method named number of sides (). Provide three classes named trapezoid, triangle and Hexagon such that each one of the classes extends the class shape. Each one of the class contains only the method number of sides () that shows the number of sides in the given geometrical figures 1. AIM: To implements a program shows the number of sides in the given geometrical figures 2. Algorithm: import java.io.*; import java. abstract class shape { void numberofsides() { System.out.println("This is for abstract class"); } } class Trapezoid extends shape { void numberofsides() { System.out.println("Trapezoid having 4 sides"); } } class Triangle extends shape { void numberofsides() { System.out.println("Triangle having 3 sides"); } Turbomachinery Institute of Technology & Sciences 43 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

} class Hexagonal extends shape { void numberofsides() { System.out.println("Hexagonal having 6 sides"); } } class AbstractDemo { public static void main(String args[]) { Trapezoid tz=new Trapezoid(); Triangle t=new Triangle(); Hexagonal h=new Hexagonal(); tz.numberofsides(); t.numberofsides(); h.numberofsides(); } } Output It is having 4 sides it is having 3 sides it is having 6 sides Week 12 b) : Program to implement BorderLayout 1. AIM: Write a java program to implement the APPLET PACKAGES, Create Border layout of window. 2. Algorithm: 1. Start the program. 2. Import the packages of applet, awt, awt.event. 3. Create classes and methods. 4. Declare the Border Layout directions. 5. Application of Graphical User Interface. 6. Printing in the separated Applet viewer window. 7. Stop the program. 3. PROGRAM: import java.awt.*; import java.awt.event.*; import java.applet.*; /*<applet code = "BorderDemo" width=300 height=300> </applet> */ public class BorderDemo extends Applet { public void init( ) { setLayout(new BorderLayout( )); add(new Button("CSE students"),BorderLayout.NORTH); add(new Label("studying well"),BorderLayout.SOUTH); add(new Button("right"),BorderLayout.EAST); Turbomachinery Institute of Technology & Sciences 44 Department of Computer Science & Engg.

Object Oriented Programming using JAVA Lab

add(new Button("left"),BorderLayout.WEST); String msg = "This is the Demo for BorderLayout"+"done by Cse-1 students"; add(new TextArea(msg),BorderLayout.CENTER); } } 4. OUTPUT

Turbomachinery Institute of Technology & Sciences

45

Department of Computer Science & Engg.

S-ar putea să vă placă și