COMPUTER SCIENCE & ENGINEERING II YEAR PAPER – 1: OOPS & JAVA (PRACTICAL SYLLABUS) NOTE:- The List of sample Programs are given below :{ Practice some more related programs on each unit} 1. Familiarization with the Java compiler and Interpreter 2. Write a simple Java program to print a line of text. 3. Write a simple Java Program to Add, Subtract, Multiply and divide two integers. 4. Write a Java program to convert the temperature from the command line in Celsius to Fahrenheit. 5. Write a simple Java program to find if a number from the command line is even or not. 6. Write a Java program to print numbers from 1 to n using the do … while structure. 7. Write a Java program to print the multiplication table of a given number n using the while structure. 8. Use break and continue statements in the above program to a) b) skip n=5. stop at n=8 9. Write a Java program to find the division of a student based on the marks obtained using switch … case statements. 10. Find if a given number is prime or not using the ‘ for’ statement. 11. Write a program that prints the first 20 Fibonacci numbers. 12. Write a java program to take a word on the command line and print all the permutations of the letters, one per line. 13. Write a program to list all the files and directories contained in a directory given on the command line. 14. Create an array of integers and print its values, sum of values and average of the values 15. Find the maximum value from the given array of numbers. 16. Arrange the given array into ascending order. 17. Create a string array, write values into it and print its values. 18. Write a program for addition of two matrices. 19. Create a class called distance with private data inches and feet. Add methods to get data from user and display the user given values for an object. Modifying access specifies to check the effect on accessing the variables from user functions. 20. Create a class called shape with private data length and breadth. Add methods to get data from user, display the area, perimeter and display the user given values for an object. Create default constructor and constructors that take one and two arguments each. Create objects to use these constructors. 21. Create a class called test with private data x and y. Write all necessary constructors and methods to accept data from user, display user data and return the sum and product of these variable to the user. 22. Create a class called “complex” in Java containing data by name” r” and “img” to represent the real and imaginary parts of a complex number. Write all necessary constructors and destructor. Write methods that “ accept” two objects of complex class and “return” the sum , difference and product of these two complex objects. 23. Write a class containing 3 functions by name ”area” to calculate the areas of a square, triangle and rectangle based on whether the function by the same name “area” is called with 1, 2 or 3 parameters. 24. A class by name “box” contains only two data members- length and breadth. Extend it to contain another class containing a third variable called height, write constructors for the new class, and method to calculate the volume of the box. Implement the concept of virtual function in this Program. 25. Write a program to create an interface by name” welcome” that contains an unimplemented method “greeting”. Create classes called “English” and “hindi” that implement this method to print the message “hello” and “namasthe” respectively. Create necessary user functions to use these classes. 26. Write a class that keeps a running total of all characters passed to it (one at a time) and throws an exception if it is passed a non-alphabetic character. 27. Develop an applet to display a simple message “ hello”. 28. Develop an applet that contains two text fields and a button. Write program so that the second text field displays the factorial of the number in the first field when the button is clicked. 29. Write a java program that changes the colors of the applet when different mouse events occur. 30. Write a java program that displays “Get” every one second, “Set” every two second and “Go” every three seconds using three threads. 1. Familiarization with the Java compiler and Interpreter: Remember that , before running the java program, the Java Development Kit(JDK) must be installed properly on our system. We can refer the java text book chapter 1.12 INSTALLING AND CONFIGURING JAVA for installation of java software on our system. Step-1: Editing: Enter the java program by using any standard text editor such as notepad ,ms-word or edit in MSDOS etc., Most of the programmers prefer to use notepad. Step-2: Saving: While entering some lines or after completion of entering a program we can save the Program with the class name and the extension must be java. Suppose a program class sample { public static void main(String args[]) { System.out.println("welcome to CSE students"); } } The above program must save with the name sample.java, and the file Save as type must be “all files” as shown below. Sample.java is the source file. Here location of file saving is important. Step-3: Compiling: After saving the program, compile the java program by using D:\java> Javac sample.java if there are any errors , repeat steps 1 thru 3 until program is error free. Step-4: Running: If there are no errors , the javac compiler creates a file called sample.class containing the bytecodes of the program. Now type the command for execution as shown below D:\java> java sample Now the output will be displayed as follows welcome to CSE students 2. Write a simple Java program to print a line of text. // prints a line of text class sample { public static void main(String args[]) { System.out.println("welcome to CSE students"); } } Output welcome to CSE students 3. Write a simple Java Program to Add, Subtract, Multiply and divide two integers. // program to add , subtract , multiply and // divide two integers class ArithmeticOperations { public static void main(String args[]) { int a , b ,x1,x2,x3,x4 ; a = 10 ; b = 6 ; x1 = a+b; x2 = a-b; x3 = a*b; x4 = a/b; System.out.println("a = "+ a + " b= " + b); System.out.println("a + b = "+ x1); System.out.println("a - b = "+ x2); System.out.println("a * b = "+ x3); System.out.println("a / b = "+ x4); } } Output a a a a a = + * / 10 b= 6 b = 16 b = 4 b = 60 b = 1 4. Write a Java program to convert the temperature from the command line in Celsius to Fahrenheit. // converts temperature from celsius to fahrenheit import java.util.*; class CelsiusToFahrenheit { public static void main(String args[]) { float c,f ; Scanner in = new Scanner(System.in); System.out.println("Enter temperature in Celsius"); c = in.nextInt(); f = 9*c/5 + 32; System.out.println("Temperature in Celsius = " + c); System.out.println("Temperature in Fahrenheit = " + f); } } input Enter temperature in Celsius 0 output Temperature in Celsius = 0.0 Temperature in Fahrenheit = 32.0 input Enter temperature in Celsius 100 output Temperature in Celsius = 100.0 Temperature in Fahrenheit = 212.0 input Enter temperature in Celsius output 34 Temperature in Celsius = 34.0 Temperature in Fahrenheit = 93.2 input Enter temperature in Celsius output -40 Temperature in Celsius = -40.0 Temperature in Fahrenheit = -40.0 5. Write a simple Java program to find if a number from the command line is even or not. This java program finds if a number is odd or even. If the number is divisible by 2 then it is even, otherwise it is odd. We use modulus operator to find remainder in our program. // finds the given number is either odd or even import java.util.Scanner; class OddOrEven { public static void main(String args[]) { int x; System.out.println("Enter an integer to check either odd or even "); Scanner in = new Scanner(System.in); x = in.nextInt(); if ( x % 2 == 0 ) System.out.println(x+" is an even number."); else System.out.println(x+" is an odd number."); } } input Enter an integer to check either odd or even 3 output 3 is an odd number. input Enter an integer to check either odd or even 4 output 4 is an even number. 6. Write a Java program to print numbers from 1 to n using the do … while structure. import java.util.Scanner; class numbers { public static void main(String args[]) { int n,i; System.out.println("enter an integer"); Scanner in = new Scanner(System.in); n= in.nextInt(); i=1; do { System.out.println(i); i=i+1; } while(i<=n); } } Input enter an integer 6 output 1 2 3 4 5 6 7. Write a Java program to print the multiplication table of a given number n using the while structure. // prints multiplication table of n import java.util.Scanner; class MultiplicationTable { public static void main(String args[]) { int n, i; System.out.println("Enter an integer to print it's multiplication table"); Scanner in = new Scanner(System.in); n = in.nextInt(); System.out.println("Multiplication table of "+n+" is :"); for ( i = 1 ; i <= 10 ; i++ ) System.out.println( n+"*"+i+" = "+(n*i)); } } input Enter an integer to print it's multiplication table 5 output Multiplication table of 5 is : 5*1 = 5 5*2 = 10 5*3 = 15 5*4 = 20 5*5 = 25 5*6 = 30 5*7 = 35 5*8 = 40 5*9 = 45 5*10 = 50 8. Use break and continue statements in the above program to a) b) skip n=5. stop at n=8 // prints multiplication table of n // stop at n = 8 and skip at n = 5 import java.util.Scanner; class MultiplicationTable1 { public static void main(String args[]) { int n, i; boolean x = true; do{ System.out.println("Enter an integer to print it's multiplication table or 8 to stop: "); Scanner in = new Scanner(System.in); n = in.nextInt(); if(n==8) break; if(n==5) { System.out.println("you have entered 5 , so it is skipped"); continue; } System.out.println("Multiplication table of "+n+" is :"); for ( i = 1 ; i <= 10 ; i++ ) System.out.println( n+"*"+i+" = "+(n*i)); } while(x); System.out.println("you have entered 8 , so it is stopped"); } } input Enter an integer to print it's multiplication table or 8 to stop: 4 output Multiplication table of 4 is : 4*1 = 4 4*2 = 8 4*3 = 12 4*4 = 16 4*5 = 20 4*6 = 24 4*7 = 28 4*8 = 32 4*9 = 36 4*10 = 40 input Enter an integer to print it's multiplication table or 8 to stop: 5 output you have entered 5 , so it is skipped input Enter an integer to print it's multiplication table or 8 to stop: 7 output Multiplication table of 7 is : 7*1 = 7 7*2 = 14 7*3 = 21 7*4 = 28 7*5 = 35 7*6 = 42 7*7 = 49 7*8 = 56 7*9 = 63 7*10 = 70 input Enter an integer to print it's multiplication table or 8 to stop: 8 output you have entered 8 , so it is stopped 9. Write a Java program to find the division of a student based on the marks obtained using switch … case statements. // program finds division. // suppose divisions are calculated as follows // 0..39: fail, 40..49: third class 50..59 :second class //60..79: first class 80.. 100 : honors //note: if we use only switch case without if statement in the // following program, it will display honors for totmarks > 100 // and less than 109 which is meaning less because marks should not be // out of range of 0-100. import java.util.Scanner; class division { public static void main(String Args[]) { int totmarks; boolean x = true; while(x) { System.out.print("enter total marks between 1-100: Scanner in = new Scanner(System.in); totmarks = in.nextInt(); "); if (totmarks < 0 || totmarks >100) { System.out.println("Marks must be in between 0-100 continue; } switch (totmarks/10) { case 0: case 1: case 2: case 3:System.out.println("Fail");break; case 4:System.out.println("Third class ");break; "); case 5:System.out.println("Second class ");break; case 6: case 7:System.out.println("First class ");break; case 8: case 9: case 10:System.out.println("Honors");break; } break; } } } input enter total marks between 1-100: 12 output Fail input enter total marks between 1-100: 42 output Third class Input enter total marks between 1-100: 56 output Second class input enter total marks between 1-100: 65 output First class input enter total marks between 1-100: 86 output Honors input enter total marks between 1-100: 102 output Marks must be in between 0-100 enter total marks between 1-100: 98 Honours input enter total marks between 1-100: 105 output Marks must be in between 0-100 enter total marks between 1-100: 52 Second class 9b)ans import java.io.*; public class Grader { public static void main(String args[]) throws Exception { BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); System.out.println("please select the range of your marks to know your Division \n1.>70% \n2.60-70% \n3.<60%"); int ch=Integer.parseInt(b.readLine()); switch(ch) { case 1: System.out.println("Your have passed the exam in Division:First class with Distinction"); break; case 2: System.out.println("Your have passed the exam in Division:First class"); break; case 3: System.out.println("Your have passed the exam in Division:Second Class"); break; } } } input please select the range of your marks to know your Division 1 1.>70% 2.60-70% 3.<60% output Your have passed the exam in Division:First class with Distinction input please select the range of your marks to know your Division 3 1.>70% 2.60-70% 3.<60% output Your have passed the exam in Division:Second Class input please select the range of your marks to know your Division 2 1.>70% 2.60-70% 3.<60% output Your have passed the exam in Division:First class 10. Find if a given number is prime or not using the ‘ for’ statement. // // // // // Prime number: A number which is only divisible by one and itself is called a prime number. Divisible means remainder is zero. 7 is a prime number because it is only divisible by one and seven. 8 is not a prime number because it is divisible by one, two, four and eight. program finds a number is prime or not import java.util.Scanner; class PrimeNumber { public static void main(String args[]) { int n, j ,status = 1 ; Scanner in = new Scanner(System.in); System.out.println("Enter a number to find whether prime or not"); n = in.nextInt(); for ( j = 2 ; j <= Math.sqrt(n) ; j++ ) { if ( n % j == 0 ) { status = 0; System.out.println(n+" is not a prime number"); break; } } if ( status == 1 ) { System.out.println(n+" is a prime number "); } } } input Enter a number to find whether prime or not 7 output 7 is a prime number input Enter a number to find whether prime or not 8 output 8 is not a prime number 11. Write a program that prints the first 20 Fibonacci numbers. // First few numbers of Fibonacci series are 0, 1, 1, 2, 3, 5, 8 ,etc // Except first two terms in sequence every other term is the sum of two previous //terms, For example 8 = 3 + 5 (addition of 3, 5). This sequence has many applications //in mathematics and Computer Science. // prints first 20 Fibonacci numbers class Fibonacci { public static void main(String args[]) { int f1, f2, f3, c; f1 = 0; f2 = 1 ; System.out.println("First 20 Fibonacci numbers:"); for(c=1;c<=20;c++) { System.out.println(f1); f3=f1+f2; f1=f2; f2=f3; } } } output First 20 Fibonacci numbers: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 12. Write a java program to take a word on the command line and print all the permutations of the letters, one per line. import java.util.*; public class PermutationExample { public static void main(String args[]) throws Exception { Scanner input = new Scanner(System.in); System.out.print("Enter String: "); String chars = input.next(); showPattern("", chars); } public static void showPattern(String st, String chars) { if (chars.length() <= 1) System.out.println(st + chars); else for (int i = 0; i < chars.length(); i++) { try { String newString = chars.substring(0, i) + chars.substring(i + 1); showPattern(st + chars.charAt(i), newString); } catch (Exception e) { e.printStackTrace(); } } } } input Enter String: abc Output abc acb bac bca cab cba input Enter String: xy output xy yx 13. Write a program to list all the files and directories contained in a directory given on the command line. //lists all files in a directory import java.io.File; public class ListFiles { public static void main(String[] args) { // Directory path here // example of input D:\\java String path = "."; //default current directory when it is .(dot) String files; File folder = new File(path); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { files = listOfFiles[i].getName(); System.out.println(files); } } } } output 3.java 4.doc 5.doc 5.java 6.doc 6.java 7.doc 8.doc 9.doc A.class AddNumbers.class AddNumbers.java AddTwoMatrix.class AddTwoMatrix.doc AddTwoMatrix.java AEvent.class 14. Create an array of integers and print its values, sum of values and average of the values. // creates an array of integers and print its values, sum of values and // average of the values import java.util.Scanner; class ArrayExample{ public static void main(String args[]){ int i,n,s=0,a[] ; float average; System.out.println("How many values in an array"); Scanner in = new Scanner(System.in); n = in.nextInt(); a = new int[n]; System.out.println("enter"+n+"values line by line"); for(i=0;i<n;++i){ System.out.print("enter a value"); a[i] = in.nextInt(); s+=a[i];} average = (float)s/n ; System.out.println("Given Array"); for(i=0;i<n;++i){ System.out.println(a[i]);} System.out.println("sum="+s); System.out.println("Average="+average); } } input How many values in an array 5 Enter 5 values line by line enter a value 12 enter a value 3 enter a value 24 enter a value 32 enter a value 5 output Given Array 12 3 24 32 5 sum=76 Average=15.2 15. Find the maximum value from the given array of numbers. // finds maximum value in a given array of integers import java.util.Scanner; class ArrayMax{ public static void main(String args[]){ int i,n,max,a[] ; System.out.println("How many values in an array"); Scanner in = new Scanner(System.in); n = in.nextInt(); a = new int[n]; System.out.println("enter "+n+" values line by line"); for(i=0;i<n;++i){ System.out.print("enter a value: "); a[i] = in.nextInt();} //process to find maximum value max = a[0]; for(i=1;i<n;++i){ if(max < a[i]) max = a[i]; } System.out.println("Given Array"); for(i=0;i<n;++i){ System.out.println(a[i]);} System.out.println("Maximum value = "+max); } } input How many values in an array 5 enter 5 values line by line enter a value: 12 enter a value: 23 enter a value: 45 enter a value: 32 enter a value: 18 output Given Array 12 23 45 32 18 Maximum value = 45 16. Arrange the given array into ascending order. // Sorting an Array of integers import java.util.*; class ArraySort{ public static void main(String args[]){ int i,n,a[] ; System.out.print("How many values in an array: Scanner in = new Scanner(System.in); n = in.nextInt(); "); a = new int[n]; //specifies array size System.out.println("enter "+n+" values line by line"); for(i=0;i<n;++i){ System.out.print("enter a value: "); a[i] = in.nextInt();} System.out.println("Given Array"); for(i=0;i<n;++i){ System.out.println(a[i]);} // for array sorting Arrays.sort(a); System.out.println("Sorted Array in ascending order"); for(i=0;i<n;++i){ System.out.println(a[i]);} } } input How many values in an array: 5 enter 5 values line by line enter a value: 24 enter a value: 13 enter a value: 6 enter a value: 43 enter a value: 11 output Given Array 24 13 6 43 11 Sorted Array in ascending order 6 11 13 24 43 17. Create a string array, write values into it and print its values. // Array with strings import java.util.*; class ArrayString{ public static void main(String args[]){ int i,n; String[] a = new String[]{"Govardhan","Bheemeswar","Ramarao", "Rajareddy", "Basavraj"}; n = a.length; for(i=0;i<n;++i){ System.out.println(a[i]);} } } Output Govardhan Bheemeswar Ramarao Rajareddy Basavraj 18. Write a program for addition of two matrices. // Matrix Addition import java.util.Scanner; class MatrixAddition { public static void main(String args[]) { int m,n,c,d; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows and columns of a matrix)"); m = in.nextInt(); n = in.nextInt(); int first[][] = new int[m][n]; int second[][] = new int[m][n]; int sum[][] = new int[m][n]; System.out.println("Enter "+m*n+" elements of first matrix"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) first[c][d] = in.nextInt(); System.out.println("Enter "+m*n+" elements of second matrix"); for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) second[c][d] = in.nextInt(); // process of addition for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) sum[c][d] = first[c][d] + second[c][d]; // printing first matrix System.out.println("First Matrix is:-"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) System.out.print(first[c][d]+"\t"); System.out.println(); } // printing second matrix System.out.println("Second Matrix is:-"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) System.out.print(second[c][d]+"\t"); System.out.println(); } System.out.println("Sum of entered matrices:-"); for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) System.out.print(sum[c][d]+"\t"); System.out.println(); } } } input Enter the number of rows and columns of a matrix 2 2 Enter 4 elements of first matrix 1 2 3 4 Enter 4 elements of second matrix 5 6 7 8 output First Matrix is:1 2 3 4 Second Matrix is:5 6 7 8 Sum of entered matrices:6 8 10 12 19. Create a class called distance with private data inches and feet. Add methods to get data from user and display the user given values for an object. Modifying access specifies to check the effect on accessing the variables from user functions. public class Distance { private int inches; private int feet; public int getInches() { return inches; } public void setInches(int inch) { inches = inch; } public int getFeet() { return feet; } public void setFeet(int f) { feet = f; } public static void main(String args[]) { Distance distance = new Distance(); //setting the values distance.setInches(10); distance.setFeet(20); //displaying the values System.out.println("inches= "+distance.getInches()); System.out.println("feet "+distance.getFeet()); } } output inches= 10 feet 20 20. Create a class called shape with private data length and breadth. Add methods to get data from user, display the area, perimeter and display the user given values for an object. Create default constructor and constructors that take one and two arguments each. Create objects to use these constructors. //finds Area and Perimeter of a Rectangle import java.util.Scanner; class Rectangle { int length; int breadth; Rectangle(int x,int y) { length=x; breadth=y; } int rectArea() { return(length*breadth); } int rectPerimeter() { return(2*(length+breadth)); } } class Shape { public static void main(String args[]) { int p , q ; System.out.print("Enter length: "); Scanner in = new Scanner(System.in); p = in.nextInt(); System.out.print("Enter breadth: "); q = in.nextInt(); Rectangle rect1=new Rectangle(p,q); int area1=rect1.rectArea(); int perimeter1 = rect1.rectPerimeter(); System.out.println("Length ="+p); System.out.println("Breadth="+q); System.out.println("Area of a Rectangle ="+area1); System.out.println("Perimeter of a Rectangle ="+perimeter1); } } input Enter length: 5 Enter breadth:6 output Length =5 Breadth=6 Area of a Rectangle =30 Perimeter of a Rectangle =22 21. Create a class called test with private data x and y. Write all necessary constructors and methods to accept data from user, display user data and return the sum and product of these variable to the user. //accepts user data for x and y and displays user data , sum and product // of those variables by using methods import java.util.Scanner; public class Test{ /** Main method */ public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter first value: "); int i = in.nextInt(); System.out.print("Enter second value: "); int j = in.nextInt(); int k = sum(i, j); int l = product(i,j); System.out.println("First value = "+i); System.out.println("Second value = "+j); System.out.println("The " and " + System.out.println("The " and " + sum of " + j + " is " product of j + " is " i + " + + k); + i + l); } /** Return the sum of two numbers */ private static int sum(int x, int y) { int result; result = x + y; return result; } /** Return the product of two numbers */ private static int product(int x, int y) { int result; result = x * y; return result; } } input Enter first value: 5 Enter second value: 3 output First value = 5 Second value = 3 The sum of 5 and 3 is 8 The product of 5 and 3 is 15 22. Create a class called “complex” in Java containing data by name” r” and “img” to represent the real and imaginary parts of a complex number. Write all necessary constructors and destructor. Write methods that “ accept” two objects of complex class and “return” the sum , difference and product of these two complex objects. // complex number operations addition, // subtraction and multiplication import java.util.Scanner; class Complex1 { public double realno; public double imgno; Complex1(){ } Complex1(double r,double i) { realno=r; imgno=i; } public Complex1 add(Complex1 x, Complex1 y) { double r = x.realno + y.realno; double i = x.imgno + y.imgno; return } public { double double return } public { double double return } new Complex1(r,i); Complex1 subtract(Complex1 x, Complex1 y) r = x.realno - y.realno; i = x.imgno - y.imgno; new Complex1(r,i); Complex1 multiply (Complex1 x, Complex1 y) r2 = x.realno * y.realno - x.imgno * y.imgno; i2 = x.imgno * y.realno + x.realno * y.imgno; new Complex1 (r2, i2); public String toString () { String imgsign = (imgno < 0) ? " - " : " + "; if (imgno < 0) imgno = -imgno ; return ("("+realno+") " + imgsign + "("+imgno + "i)"); } } class TestComplex { public static void main (String args[]) { String x = "+";//used x to print complex number as it is such as 2+3i double xr,xi,yr,yi; //two complex numbers are xr+xi & yr+yi //using instance methods Scanner in = new Scanner(System.in); System.out.println("Enter first real no"); xr = in.nextDouble(); System.out.println("Enter first imaginary no"); xi = in.nextDouble(); System.out.println("Enter Second real no"); yr = in.nextDouble(); System.out.println("Enter Second imaginary no"); yi = in.nextDouble(); Complex1 a = new Complex1 (xr,xi);// example first expression (2+3i) Complex1 b = new Complex1 (yr,yi);// example second expression (4+6i) Complex1 complex1 = new Complex1(); Complex1 value1 = complex1.add(a,b); Complex1 value2 = complex1.subtract (a,b); Complex1 value3 = complex1.multiply (a,b); System.out.println("Following result is using instance methods: "); System.out.println("first complex number :"+a.realno + x + a.imgno +"i"); System.out.println("Second complex number :"+b.realno + x + b.imgno +"i"); System.out.println("Addition : "+value1); System.out.println("Subtraction : "+value2); System.out.println("Multiplication : "+value3); }} input Enter first real no 2 Enter first imaginary no 3 Enter Second real no 4 Enter Second imaginary no 5 output Following result is using instance methods: first complex number :2.0+3.0i Second complex number :4.0+5.0i Addition : (6.0) + (8.0i) Subtraction : (-2.0) - (2.0i) Multiplication : (-7.0) + (22.0i) input Enter first real no 4 Enter first imaginary no 6 Enter Second real no -2 Enter Second imaginary no -5 output Following result is using instance methods: first complex number :4.0+6.0i Second complex number :-2.0+-5.0i Addition : (2.0) + (1.0i) Subtraction : (6.0) + (11.0i) Multiplication : (22.0) - (32.0i) 23. Write a class containing 3 functions by name ”area” to calculate the areas of a square, triangle and rectangle based on whether the function by the same name “area” is called with 1, 2 or 3 parameters. //calculate the areas of a square, triangle and rectangle based // on whether the function by the same name “area” is // called with 1, 2 or 3 parameters. // here we used BufferReader and Integer.ParseInt instead of Scanner in for inputting values import java.io.*; class areas { void area(int a ) { System.out.println( "\n Area of a square with side } "+a+" is :" + a*a); void area(int a, int b, int c) { double temp = (a + b + c); double s= temp/2; double triarea = Math.sqrt(s*(s-a)*(s-b)*(s-c)); System.out.println( "\n Area of triangle with lenght of sides "+a+"," +b+ " and " +c+" is : "+ triarea); } void area(int a , int b) { System.out.println( "\n Area of a Rectangle of length " +a+ " and breadth "+b+ " is :" + a * b); } public static void main(String args[]) throws IOException { areas d = new areas(); BufferedReader Br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("\n Find area of \n 1 . Square \n 2 . Triangle \n 3 . Rectangle \n\nSelect a choice : "); int choice =Integer.parseInt(Br.readLine()); switch(choice) { case 1: System.out.print("\n Enter the side : "); int a =Integer.parseInt(Br.readLine()); d.area(a); break; case 2: System.out.print("\n Enter the lenght of first side : "); int x =Integer.parseInt(Br.readLine()); System.out.print("\n Enter the lenght of second side : "); int y=Integer.parseInt(Br.readLine()); System.out.print("\n Enter the lenght of third side : "); int z =Integer.parseInt(Br.readLine()); d.area(x,y,z); break; case 3: System.out.print("\n Enter the length : "); int l =Integer.parseInt(Br.readLine()); System.out.print("\n Enter the breadth : "); int b =Integer.parseInt(Br.readLine()); d.area(l,b); break; default: System.out.println("Invalid choice"); } } } output Find area of 1 . Square 2 . Triangle 3 . Rectangle Select a choice : 1 Enter the side : 3 Area of a square with side 3 is :9 Find area of 1 . Square 2 . Triangle 3 . Rectangle Select a choice : Enter the lenght Enter the lenght Enter the lenght Area of triangle Find area of 1 . Square 2 . Triangle 2 of first side : 2 of second side : 3 of third side : 4 with lenght of sides 2,3 and 4 is : 2.9047375096555625 3 . Rectangle Select a choice : 3 Enter the length : 6 Enter the breadth : 5 Area of a Rectangle of length 6 and breadth 5 is :30 Find area of 1 . Square 2 . Triangle 3 . Rectangle Select a choice : 5 Invalid choice 24. A class by name “box” contains only two data members- length and breadth. Extend it to contain another class containing a third variable called height, write constructors for the new class, and method to calculate the volume of the box. Implement the concept of virtual function in this Program. //a class Box contains length and breadth //and another BoxVolume contains length,breadth and height // here we used virtual function class Box { int length , breadth; Box(int x, int y){ length = x; breadth = y;} int area(){ return(length*breadth);}} class BoxVolume extends Box { int height; BoxVolume(int x, int y, int z){ super(x,y); height = z;} int volume(){ return(length*breadth*height);}} class Box1 { public static void main(String arg[]){ BoxVolume volume1= new BoxVolume(10,15,5); int p = volume1.area(); int q = volume1.volume(); System.out.println("area = " + p); System.out.println("volume= " + q); }} output area = 150 volume= 750 25. Write a program to create an interface by name” welcome” that contains an unimplemented method “greeting”. Create classes called “English” and “hindi” that implement this method to print the message “hello” and “namasthe” respectively. Create necessary user functions to use these classes. Ans interface Welcome { String greeting(); } class English implements Welcome { public String greeting() { return "Hello"; } } class Hindi implements Welcome { public String greeting() { return "Namaste"; } } public class Test { public static void main(String ar[]) { English eng=new English(); Hindi hin = new Hindi(); System.out.println("Greetings in English: "+eng.greeting()); System.out.println("Greetings in Hindi: "+hin.greeting()); } } 26. Write a class that keeps a running total of all characters passed to it (one at a time) and throws an exception if it is passed a non-alphabetic character. Ans) import java.io.*; class Checker { boolean check(String s) { boolean hasNonAlpha = s.matches("^.*[^a-zA-Z].*$"); return hasNonAlpha; } public static void main(String ar[]) throws Exception { Checker ch=new Checker(); BufferedReader b=new BufferedReader(new InputStreamReader(System.in)); while(true) { String s=b.readLine(); if(ch.check(s)!=true) { } else { System.exit(0); } } } } 27. Develop an applet to display a simple message “ hello”. //develop an Applet to display a simple message “hello” Her we are giving step wise procedure to create and run an applet First create a java program hellojava.java import java.awt.*; import java.applet.*; public class hellojava extends Applet {public void paint (Graphics g) { g.drawString("hello",10,100); }} When this above program is error free , automatically it creates hellojava.class and then create an html tag hellojava.html as follows. The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that invokes an applet: <HTML> <BODY> <APPLET CODE= hellojava.class WIDTH=400 HEIGHT=200> </APPLET> </BODY> </HTML> An applet may be invoked by embedding directives in an HTML file and viewing the file through an applet viewer or Java-enabled browser. If we use appletviewer appletviewer hellojava.html causes to display as follows. 28. Develop an applet that contains two text fields and a button. Write program so that the second text field displays the factorial of the number in the first field when the button is clicked. // Develop an applet that contains two text fields and a button. Write program // so that the second text field displays the factorial of the number in the // first field when the button is clicked. import java.awt.*; import java.awt.event.*; public class FactEvent extends java.applet.Applet implements ActionListener { TextField t1,t2; int fact=1,m; Button b1,b2,b3; String msg; Label l1,l2; FactEvent e; public void init() { e=this; t1=new TextField(3); t2=new TextField(10); b1=new Button("FIND FACTORIAL"); l1=new Label("ENTER THE NUMBER"); l2=new Label("RESULT"); add(l1); add(t1); add(l2); add(t2); add(b1); b1.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String str=t1.getText(); if(str!="") { int num=Integer.parseInt(str); for(int i=num;i>0;i--) { fact=fact*i; } msg="" +fact; t2.setText(msg); fact=1; } } } When the above FactEvent.java is error free , it will create FactEvent.class. Now create FactEvent.html as shown below <HTML> <BODY> <APPLET CODE= FactEvent.class WIDTH=400 HEIGHT=200> </APPLET> </BODY> </HTML> To see the results, run the applet as follows appletviewer FactEvent.html then result will be as follows 29. Write a java program that changes the colors of the applet when different mouse events occur. //changes the colors of the applet when different mouse event occurs import java.applet.Applet; import java.awt.*; public class ColorButtons extends Applet { Button red, green, blue, reset; Color bgColor; public void init() { // specify the buttons red = new Button(); red.setBackground(Color.red); green = new Button(); green.setBackground(Color.green); blue = new Button(); blue.setBackground(Color.blue); reset = new Button("Reset"); // find the default color and choose this for reset button bgColor = getBackground(); reset.setBackground(bgColor); // add the buttons to the applet add(red); add(green); add(blue); add(reset); } public boolean action(Event evt, Object arg) { // if one of the buttons is pressed, change the background color if (evt.target == red) setBackground(Color.red); else if (evt.target == green) setBackground(Color.green); else if (evt.target == blue) setBackground(Color.blue); else if (evt.target == reset) setBackground(bgColor); // recolor the buttons red.setBackground(Color.red); green.setBackground(Color.green); blue.setBackground(Color.blue); reset.setBackground(bgColor); // repaint the applet repaint(); return true; } } Now create ColorButtons.html file as follows <HTML> <HEAD> </HEAD> <BODY> <APPLET CODE="ColorButtons.class" WIDTH="800" HEIGHT="500"></APPLET> </BODY> </HTML> 29b)ans import java.awt.*; import java.applet.*; import java.awt.event.*; public class MouseEvent1 extends Applet implements MouseListener{ public void init() { this.addMouseListener(this); } public void mouseClicked(MouseEvent e){ setBackground(Color.blue); } public void mouseEntered(MouseEvent e){ setBackground(Color.cyan); } public void mouseExited(MouseEvent e){ setBackground(Color.green); } public void mousePressed(MouseEvent e){ setBackground(Color.magenta); } public void mouseReleased(MouseEvent e){ setBackground(Color.yellow); } } MouseEvent1.html will be created as follows <HTML> <HEAD> </HEAD> <BODY> <APPLET ALIGN="CENTER" CODE="MouseEvent1.class" WIDTH="800" HEIGHT="500"></APPLET> </BODY> </HTML> When we run the applet as given below Appletviewer MouseEvent1.html Applet background will changes with different colors for different mouse events. 30. Write a java program that displays “Get” every one second, “Set” every two second and “Go” every three seconds using three threads. class A extends Thread { synchronized public void run() { try { while(true) { sleep(1000); System.out.println("get"); } } catch(Exception e) {} } } class B extends Thread { synchronized public void run() { try { while(true) { sleep(2000); System.out.println("Set"); } } catch(Exception e) {} } } class C extends Thread { synchronized public void run() { try { while(true) { sleep(3000); System.out.println("Go"); } } catch(Exception e) {} } } class ThreadDemo { public static void main(String args[]) { A t1=new A(); B t2=new B(); C t3=new C(); t1.start(); t2.start(); t3.start(); } }