19A05303P OBJECT ORIENTED PROGRAMMING THROUGH …



INDEXWeekPROGRAMS LISTPAGE NO1a. Installation of Java software, study of any Integrated development environment, Use Eclipse or Netbean platform and acquaint with the various menus. Create a test project, add a test class and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like renaming variables, methods and classes. Try debug step by step with javaprogram to find prime numbers between 1 to n.b. Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0. Read in a, b, c and use the quadratic formula.c. Develop a Java application to generate Electricity bill. Create a class with the following members: Consumer no., consumer name, previous month reading, current month reading, type of EB connection (i.e domestic or commercial). Commute the bill amount using the following tariff. If the type of the EB connection is domestic, calculate the amount to be paid as follows:??First 100 units - Rs. 1 per unit??101-200 units - Rs. 2.50 per unit??201 -500 units - Rs. 4 per unit??> 501 units - Rs. 6 per unitIf the type of the EB connection is commercial, calculate the amount to be paid as follows:??First 100 units - Rs. 2 per unit??101-200 units - Rs. 4.50 per unit??201 -500 units - Rs. 6 per unit??> 501 units - Rs. 7 per unitd. Write a Java program to multiply two given matrices.042a. Write Java program on use of inheritance, preventing inheritance using final, abstract classes.b. Write Java program on dynamic binding, differentiating method overloading and overriding.c. Develop a java application to implement currency converter (Dollar to INR, EURO to INR, Yen) using Interfaces.173a. Write Java program that inputs 5 numbers, each between 10 and 100 inclusive. As each number is read display it only if it’s not a duplicate of any number already read display the complete set of unique values input after the user enters each new value.b. Write a Java Program to create an abstract class named Shape that contains two integers and an empty method named print Area(). Provide three classes named Rectangle, Triangle and Circle such that each one of the classes extends the class Shape. Each one of the classes contains only the method print Area () that prints the area of the given shape.c. Write a Java program to read the time intervals (HH:MM) and to compare system time if the system Time between your time intervals print correct time and exit else try again to repute the same thing. By using String Toknizer class.264a. Write a Java program to implement user defined exception handling.b. Write java program that inputs 5 numbers, each between 10 and 100 inclusive. As each number is read display it only if it‘s not a duplicate of any number already read. Display the complete set of unique values input after the user enters each new value.315a. Write a Java program that creates a user interface to perform integer division. The user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the Result field when the Divide button is clicked. If Num1 and Num2 were not integers, the program would throw a Number Format Exception. If Num2 were zero, the program would throw an Arithmetic Exception Display the exception in a message dialog box.b. Write a Java program that creates three threads. First thread displays ―Good Morning? every one second, the second thread displays ―Hello? every two seconds and the third thread displays ―Welcome? every three seconds.356a. Write a java program to split a given text file into n parts. Name each part as the name of the original file followed by .part where n is the sequence number of the part file.b. Write a Java program that reads a file name from the user, displays information about whether the file exists, whether the file is readable, or writable, the type of file and the length of the file in bytes.397a. Write a java program that displays the number of characters, lines and words in a text file.b. Write a java program that reads a file and displays the file on the screen with line number before each line.418a. Write a Java program that correctly implements producer consumer problem using the concept of inter thread communication.b. Develop a Java application for stack operation using Buttons and JOptionPane input and Message dialog box.c. Develop a Java application to perform Addition, Division, Multiplication and substraction using JOption Pane dialog Box and Text fields.439a. Develop a Java application for the blinking eyes and mouth should open while blinking.b. Develop a Java application that simulates a traffic light. The program lets the user select one of three lights: Red, Yellow or Green with radio buttons. On selecting a button an appropriate message with ―STOP? or ―READY? or ?GO? should appear above the buttons in selected color. Initially, there is no message shown.4810a. Develop a Java application to implement the opening of a door while opening man should present before hut and closing man should disappear.b. Develop a Java application by using JtextField to read decimal value and converting a decimal number into binary number then print the binary value in another JtextField.5111a. Develop a Java application that handles all mouse events and shows the event name at the center of the window when a mouse event is fired. Use adapter classes.b. Develop a Java application to demonstrate the key event handlers.5412a. Develop a Java application to find the maximum value from the given type of elements using a generic function.b. Develop a Java application that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.c. Develop a Java application for handling mouse events.5713a. Develop a Java application to establish a JDBC connection, create a table student with properties name, register number, mark1, mark2, mark3. Insert the values into the table by using the java and display the information of the students at front end.63Week-1a. Installation of Java software, study of any Integrated development environment, Use Eclipseor Netbean platform and acquaint with the various menus. Create a test project, add a test classand run it. See how you can use auto suggestions, auto fill. Try code formatter and coderefactoring like renaming variables, methods and classes. Try debug step by step with javaprogram to find prime numbers between 1 to n.Installation of Java software An integrated development environment (IDE) is a software suite that consolidates the basic tools developers need to write and test software. Typically, an IDE contains a code editor, a?compiler?or?interpreter?and a debugger that the developer accesses through a single graphical user interface (GUI). An IDE may be a standalone application, or it may be included as part of one or more existing and compatible applications.?Popular IDE tools are?NetBeans?Eclipse?IntelliJ??Visual Studio?Windows PowerShell.Eclipse IDEJava application development is supported by many different tools. One of the most powerful and helpful tool is the free Eclipse IDE (IDE = Integrated Development Environment). To download the Eclipse IDE, go to . Click on Downloads and then select the most recent stable or release version of the Eclipse SDK for your PC platform.Eclipse requires Java to run, so first installed Java on your machine You can download Java SDKs from is an?open-source?Integrated Development Environment (IDE) supported by IBM. Eclipse is popular for Java application development (Java SE and Java EE) and Android apps. It also supports C/C++, PHP, Python, Perl, and other web project developments via extensible plug-ins. Eclipse is cross-platform and runs under Windows, Linux and Mac OS.How to Install Eclipse on WindowsStep 0: Install JDKTo use Eclipse for Java programming, you need to first install Java Development Kit (JDK). Step 1: DownloadDownload Eclipse from . Under "Get Eclipse Neon" ? Click "Download Packages". For beginners, choose the 3rd entry "Eclipse IDE for Java Developers" (32-bit or 64-bit) (e.g., "eclipse-java-neon-2-win32-x86_64.zip" 161MB) ? Download.Step 2: UnzipTo install Eclipse, simply unzip the downloaded file into a directory of your choice (e.g., "d:\myproject").There is no need to run any installer. Moreover, you can simply delete the entire Eclipse directory when it is no longer needed (without running any un-installer). You are free to move or rename the directory. You can install (unzip) multiple copies of Eclipse in the same machine.Writing your First Java Program in EclipseOpen the Eclipse File menu. Then select New to create a new Java project. After that click to the item Java Project within the project menu item list. This opens the New Java Project dialog box.In the New Java Project dialog box, first please enter a project name (e.g. JavaApp1). Then select the Java 6 Run Time Environment (JRE) for this project (see Use a project pecific JRE). Finally press Finish.Please open the Eclipse File menu again. Then select Class to add a new Java class. This opens the New Java Class dialog box.In the New Java Class dialog box first select the source folder for the class. Then enter the name HelloWorld for the new class. Make sure that in the Which method stubs would you like to create? Area the public static void main(String[] args) check box is checked. Finally press Finish to create the new class.The Eclipse workbench now contains an editor window with the Java source code template for the new HelloWorld class.Within the Eclipse editor window please replace the following Java source code line// TODO Auto-generated method stubWith System.out.println(“Hello World!”);Please choose the Project => Properties menu item and select the compiler compliance level 1.6 (this compiler level belongs to Java 6) within the Properties for JavaApp1 dialog box (see JDK Compliance).Now choose the Run => Run menu item. This starts the execution of your Java application within the Eclipse IDE. Watch the Hello World! Output within the console window.Note: The Java source code of this sample is stored within the file HelloWorld.java. It is not necessary to compile the source code to the class file HelloWorld.class over a menu item or a shortcut. The Eclipse IDE compiles automatically after each file save operation or before a run.The executable HelloWorld.class class file is located in the bin directory of your project (in this sample the directory …\workspace\JavaApp1\bin). Please transfer this new class file to the DNP/2486.Java program to find prime numbers between 1 to n.1)?We are finding the prime numbers within the limit.2)?Read the “n” value using scanner object ?sc.nextInt()and store it in the variable n.3)?The for loop iterates from j=2 to j=given number. then count assigned to 0, the inner loop finds the divisors of each j value, count value represents no.of divisors. If count=2, then that number is a prime number.import java.util.Scanner;class PrimeExample{public static void main(String arg[]){int i,count;System.out.print("Enter n value : ");Scanner sc=new Scanner(System.in);int n=sc.nextInt();System.out.println("Prime numbers between 1 to "+n+" are ");for(int j=2;j<=n;j++){count=0;for(i=1;i<=j;i++){ if(j%i==0) {count++; }}if(count==2)System.out.print(j+" "); }}}b. Write a Java program that prints all real solutions to the quadratic equation ax2+bx+c=0. Readin a, b, c and use the quadratic formula.import java.io.*;import java.util.Scanner;public class Qudratic {public static void main(String[] args){double x1,x2,disc,a,b,c;double xr,xi;Scanner sc=new Scanner(System.in);System.out.println("enter a,b,c values");a=Double.parseDouble(sc.next());b=Double.parseDouble(sc.next());c=Double.parseDouble(sc.next());disc=(b*b)-(4*a*c);if(disc==0){System.out.println("roots are real and equal");x1=x2=b/(2.0*a);System.out.println("roots are"+x1 +","+x2);}else if(disc>0){System.out.println("roots are real and unequal");x1=(-b+Math.sqrt(disc))/(2.0*a);x2=(-b-Math.sqrt(disc))/(2.0*a);System.out.println("rootsare"+x1 +","+x2);}else{xr=(-b/(2.0*a));disc=Math.abs(disc);xi=(Math.sqrt(disc)/(2.0*a));System.out.println("roots are imaginary");System.out.println("root1:"+xr+"+"+xi+"i,");System.out.println("root2:"+xr+"-"+xi+"i,");}}}Output:enter a,b,c values1 2 3roots are imaginaryroot1:-1.0+1.4142135623730951i,root2:-1.0-1.4142135623730951i,enter a,b,c values1 -2 -3roots are real and unequalrootsare3.0,-1.0enter a,b,c values1 2 1roots are real and equalroots are1.0,1.0c. Develop a Java application to generate Electricity bill. Create a class with the followingmembers: Consumer no., consumer name, previous month reading, current month reading, typeof EB connection(i.e domestic or commercial). Commute the bill amount using the following tariff.If the type of the EB connection is domestic, calculate the amount to be paid as follows:??First 100 units - Rs. 1 per unit??101-200 units - Rs. 2.50 per unit??201 -500 units - Rs. 4 per unit??> 501 units - Rs. 6 per unitIf the type of the EB connection is commercial, calculate the amount to be paid as follows:??First 100 units - Rs. 2 per unit??101-200 units - Rs. 4.50 per unit??201 -500 units - Rs. 6 per unit??> 501 units - Rs. 7 per unitimport java.util.Scanner; class ElectBill{int ConsumerNo;String ConsumerName; int PrevReading;int CurrReading;int ActualReading;String EBConn; double Bill;void input_data(){Scanner sc = new Scanner(System.in); System.out.println("\n Enter Consumer Number: "); ConsumerNo = sc.nextInt();System.out.println("\n Enter Consumer Name: "); ConsumerName = sc.next();System.out.println("\n Enter Previous Units: "); PrevReading = sc.nextInt();do{System.out.println("Enter Current Units consumed:"); CurrReading = sc.nextInt();}while(CurrReading < PrevReading);ActualReading = CurrReading - PrevReading;System.out.println("Enter the types of EB Connection(domestic or commercial)"); EBConn = sc.next();}double calculate_bill(){int choice; if(EBConn=="domenstic")choice=1; elsechoice=2; switch(choice){case 1:if(ActualReading>=0 && ActualReading<=100) Bill=ActualReading*1;else if(ActualReading>100 && ActualReading <= 200) Bill=(100*1)+((ActualReading-100)*2.50);else if(ActualReading>200 && ActualReading <= 500) Bill=(100*1)+(100*2.50)+((ActualReading-200)*4);elseBill=(100*1)+(100*2.50)+(300*4)+((ActualReading-500)*6);break; case 2:if(ActualReading>=0 && ActualReading<=100) Bill=ActualReading*2;else if(ActualReading>100 && ActualReading <= 200) Bill=(100*1)+((ActualReading-100)*4.50);else if(ActualReading>200 && ActualReading <= 500) Bill=(100*1)+(100*2.50)+((ActualReading-200)*6);elseBill=(100*1)+(100*2.50)+(300*4)+((ActualReading-500)*7);break;}return Bill;}void display(){System.out.println(" "); System.out.println("ELCTRICITY BILL"); System.out.println(" "); System.out.println("Consumer Number: "+ConsumerNo); System.out.println("Consumer Name: "+ConsumerName);System.out.println("Consumer Previous Units: "+PrevReading); System.out.println("Consumer Current Units: "+CurrReading);System.out.println("Consumer Actual Units: "+ActualReading);System.out.println("Type of EBConnection: "+EBConn); System.out.println(" "); System.out.println("Total Amount(Rs.): "+Bill);}}class ElectBillGen{public static void main (String[] args){ElectBill b=new ElectBill(); b.input_data(); b.calculate_bill(); b.display();}}d. Write a Java program to multiply two given matrices.// Java program to multiply two matrices. import java.io.*;import java.util.Scanner;class MatrixMultiplication { static void printMatrix(int M[][],int rowSize,int colSize) { for (int i = 0; i < rowSize; i++) { for (int j = 0; j < colSize; j++) System.out.print(M[i][j] + " "); System.out.println(); } } static void readMatrix(int M[][],int rowSize,int colSize) { Scanner s = new Scanner(System.in);System.out.println("Enter Matrix Elements: ");for (int i = 0; i < rowSize; i++) { for (int j = 0; j < colSize; j++) M[i][j]=s.nextInt(); System.out.println(); } }static void multiplyMatrix( int row1, int col2, int row2,int A[][],int B[][],int C[][]){ int i, j, k; for (i = 0; i < row1; i++) { for (j = 0; j < col2; j++) { for (k = 0; k < row2; k++) C[i][j] += A[i][k] * B[k][j]; } } } public static void main(String[] args) { int row1,col1,row2,col2;Scanner s = new Scanner(System.in);System.out.println("\nEnter First Matrix row size: ");row1 = s.nextInt();System.out.println("\nEnter First Matrix col size: ");col1 = s.nextInt();System.out.println("\nEnter Second Matrix row size: ");row2 = s.nextInt();System.out.println("\nEnter Second Matrix col size: ");col2 = s.nextInt();if (row2 != col1) { System.out.println( "\nMatrix Multiplication is Not Possible"); return; }int A[][] = new int[row1][col1];int B[][] = new int[row2][col2];readMatrix(A,row1,col1);readMatrix(B,row2,col2);System.out.println("\nMatrix A:"); printMatrix(A, row1, col1); System.out.println("\nMatrix B:"); printMatrix(B, row2, col2);int C[][] = new int[row1][col2];multiplyMatrix(row1, col2, row2, A,B,C);// Print the result System.out.println("\nResultant Matrix:"); printMatrix(C, row1, col2); } }Week -2a) write a java program that uses inheritance concept.class A {int i, j;void showij() {System.out.println("i and j: " + i + " " + j);}}// Create a subclass by extending class A.class B extends A {int k;void showk() {System.out.println("k: " + k);}void sum() {System.out.println("i+j+k: " + (i+j+k));}}class SimpleInheritance {public static void main(String args []) {A superOb = new A();B subOb = new B();superOb.i = 10;superOb.j = 20;System.out.println("Contents of superOb: ");superOb.showij();System.out.println();subOb.i = 7;subOb.j = 8;subOb.k = 9;System.out.println("Contents of subOb: ");subOb.showij();subOb.showk();System.out.println();System.out.println("Sum of i, j and k in subOb:");subOb.sum();}}Output:Contents of superOb:i and j: 10 20Contents of subOb:i and j: 7 8k: 9Sum of i, j and k in subOb:i+j+k: 242 b) Write a java program to prevent inheritance using final keyword.class A {final void meth() {System.out.println("This is a final method.");}}class B extends A {void meth() { // ERROR! Can't override.System.out.println("Illegal!");}}public class PreventInheritance {public static void main(String a[]){A a1=new A();B b1=new B();a1.meth();b1.meth();}} Output: Compilation error.2 c) Write a java program to demonstrate abstract methods and classes.abstract class Figure {double dim1;double dim2;Figure(double a, double b) {dim1 = a;dim2 = b;}// area is now an abstract methodabstract double area();}class Rectangle extends Figure {Rectangle(double a, double b) {super(a, b);}// override area for rectangledouble area() {System.out.println("Inside Area for Rectangle.");return dim1 * dim2;}}class Triangle extends Figure {Triangle(double a, double b) {super(a, b);}// override area for right triangledouble area() {System.out.println("Inside Area for Triangle.");return dim1 * dim2 / 2;}}class AbstractAreas {public static void main(String args[]) {// Figure f = new Figure(10, 10); // illegal nowRectangle r = new Rectangle(9, 5);Triangle t = new Triangle(10, 8);Figure figref; // this is OK, no object is createdfigref = r;System.out.println("Area is " + figref.area());figref = t;System.out.println("Area is " + figref.area());}}/*Output:Inside Area for Rectangle.Area is 45.0Inside Area for Triangle.Area is 40.0b. Write Java program on dynamic binding, differentiating method overloading and overriding.Write a java program to demonstrate Dynamic binding.class A {void callme() {System.out.println("Inside A's callme method");}}class B extends A {// override callme()void callme() {System.out.println("Inside B's callme method");}}class C extends A {// override callme()void callme() {System.out.println("Inside C's callme method");}}class Dispatch {public static void main(String args[]) {A a = new A(); // object of type AB b = new B(); // object of type BC c = new C(); // object of type CA r; // obtain a reference of type Ar = a; // r refers to an A objectr.callme(); // calls A's version of callmer = b; // r refers to a B objectr.callme(); // calls B's version of callmer = c; // r refers to a C objectr.callme(); // calls C's version of callme}}Output:Inside A's callme methodInside B's callme methodInside C's callme methodWrite a java program to demonstrate method overloading concept.// Demonstrate method overloading.class OverloadDemo {void test() {System.out.println("No parameters");}// Overload test for one integer parameter.void test(int a) {System.out.println("a: " + a);}// Overload test for two integer parameters.void test(int a, int b) {System.out.println("a and b: " + a + " " + b);}// Overload test for a double parameterdouble test(double a) {System.out.println("double a: " + a);return a*a;}}class Overload {public static void main(String args[]) {OverloadDemo ob = new OverloadDemo();double result;// call all versions of test()ob.test();ob.test(10);ob.test(10, 20);result = ob.test(123.25);System.out.println("Result of ob.test(123.25): " + result);}}Output:No parametersa: 10a and b: 10 20double a: 123.25Result of ob.test(123.25): 15190.5625Write a java program to demonstrate method Overriding concept.class A {int i, j;A(int a, int b) {i = a;j = b;}// display i and jvoid show() {System.out.println("i and j: " + i + " " + j);}}class B extends A {int k;B(int a, int b, int c) {super(a, b);k = c;}void show() {super.show(); // this calls A's show()System.out.println("k: " + k);}}class Override {public static void main(String args[]) {B subOb = new B(1, 2, 3);subOb.show(); // this calls show() in B}}/*Output:i and j: 1 2k: 3//Currency Exchangeimport java.io.*;import java.util.Scanner;interface CurrencyInterface{public double DollarToINR(double Dollars);public double INRToDollar(double INR);public double EuroToINR(double Euros);public double INRToEuro(double INR);public double YenToINR(double Yens);public double INRToYen(double INR);}class CurrencyClass implements CurrencyInterface{double ER = 0;public CurrencyClass(double CurrentExchange){ER = CurrentExchange;}public double DollarToINR(double Dollars){double INR = 0; INR = Dollars * ER; return INR;}public double INRToDollar(double INR){double Dollars = 0; Dollars = INR / ER; return Dollars;}public double EuroToINR(double Euros){double INR = 0; INR = Euros * ER; return INR;}public double INRToEuro(double INR){double Euros = 0; Euros = INR / ER; return Euros;}public double YenToINR(double Yens){double INR = 0; INR = Yens * ER; return INR;}public double INRToYen(double INR){double Yens = 0; Yens = INR / ER; return Yens;}}class CurrencyConverter{public static void main(String[] args) throws NoClassDefFoundError{double CurrentExchange;int choice; double inr;char ans='y'; Scanner input = new Scanner(System.in);do{System.out.println("Menu For Currency Conversion"); System.out.println("1. Dollar to INR"); System.out.println("2. INR to Dollar"); System.out.println("3. Euro to INR"); System.out.println("4. INR to Euro"); System.out.println("5. Yen to INR"); System.out.println("6. INR to Yen");System.out.println("Enter your choice: "); choice = input.nextInt();System.out.println("Please enter the current exchange rate: "); CurrentExchange = input.nextDouble();CurrencyClass cc=new CurrencyClass(CurrentExchange); switch(choice){case 1:System.out.print("Enter Dollars :"); double dollar=input.nextDouble();System.out.println (dollar+" dollars are converted to "+cc.DollarToINR(dollar)+" Rs.");break; case 2:System.out.print("Enter INR :"); inr=input.nextDouble();System.out.println(inr+" Rs. are converted to "+cc.INRToDollar(inr)+" Dollars");break; case 3:System.out.print("Enter Euro :"); double euro=input.nextDouble();System.out.println(euro+" Euros are converted to "+cc.EuroToINR(euro)+" Rs.");break; case 4:System.out.print("Enter INR :"); inr=input.nextDouble();System.out.println(inr+" Rs. are converted to "+cc.INRToEuro(inr)+" Euros");break; case 5:System.out.print("Enter Yen :"); double yen=input.nextDouble();System.out.println(yen+" Yens are converted to "+cc.YenToINR(yen)+" Rs.");break; case 6:System.out.print("Enter INR :"); inr=input.nextDouble();System.out.println(inr+" Rs. are converted to "+cc.INRToYen(inr)+" Yens");break;default:System.out.println("Wrong choice, Try again...");}System.out.println("Do You want to go to Currency Conversion Menu?(y/n) "); ans = input.next().charAt(0);}while(ans=='y');}}Week-3a. Write Java program that inputs 5 numbers, each between 10 and 100 inclusive. As eachnumber is read display it only if it’s not a duplicate of any number already read display thecomplete set of unique values input after the user enters each new value.import java.io.*;import java.util.Scanner;public class week3b{public static void main(String[] args) { Scanner input = new Scanner(System.in); int sid[] = new int[5]; int count = 0; int x = 0; int num = 0; while (x < sid.length) { System.out.println(“Enter number: “); num = input.nextInt(); if ((num >= 10) && (num <= 100)) { for (int i = 0; i < sid.length; i++) { if (sid[i] == num) digit = true; } if (!digit) { System.out.println(“the number is” + num); sid[count] = num; count++; x++; } else System.out.printf(“The entered number already exist, Try again.. \n”); } else System.out.println(“number must be between 10 and 100, Try again..”); for (int i =0; i < x; i++) { System.out.print(sid[i] +” “); } } //End of while loop } } Output:enter 5 integers between 10 and 10012The elements are: 12enter 5 integers between 10 and 10033The elements are: 1233enter 5 integers between 10 and 1001000invalid rangeThe elements are: 1233Duplicate value enter 5 integers between 10 and 10055The elements are: 1233 55b. Write a Java Program to create an abstract class named Shape that contains two integersand an empty method named print Area(). Provide three classes named Rectangle, Triangleand Circle such that each one of the classes extends the class Shape. Each one of the classescontains only the method print Area () that prints the area of the given shape.abstract class Shape {double dim1;double dim2;Shape(double a, double b) {dim1 = a;dim2 = b;}abstract double printArea();}class Rectangle extends Shape {Rectangle(double l, double b) {super(l, b);}double printArea() {System.out.println("Inside Rectangle Class.");return dim1 * dim2;}}class Triangle extends Shape {Triangle(double b, double h) {super(b, h);}// override area for right triangledouble printArea() {System.out.println("Inside Triangle Class.");return dim1 * dim2 / 2;}}class Circle extends Shape {Circle(double pi, double r) {super(pi, r);}double printArea() {System.out.println("Inside Circle Class.");return dim1 * (dim2 * dim2);}}class AbstractShape {public static void main(String args[]) {Rectangle r = new Rectangle(9, 5);Triangle t = new Triangle(10, 8);Circle c = new Circle(2,3);Shape ref; // this is OK, no object is createdref = r;System.out.println("Area is " + ref.printArea());ref = t;System.out.println("Area is " + ref.printArea());ref = c;System.out.println("Area is " + ref.printArea());}}c. Write a Java program to read the time intervals (HH:MM) and to compare system time ifthe system Time between your time intervals print correct time and exit else try again torepute the same thing. By using String Toknizer class.import java.io.*;import java.util.Date;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.StringTokenizer;public class week3c {public static void main(String[] args)throws IOException {// TODO Auto-generated method stubBufferedReader br = new BufferedReader(new InputStreamReader(System.in));int cnt;do{System.out.println(“Enter User Time in hh:hh format:- “);String mytime = br.readLine(); System.out.println(“User Entered Time: “+mytime); DateFormat df = new SimpleDateFormat(“hh:mm”);Date date = new Date();String systime = df.format(date); System.out.println(“System Time: “+systime); StringTokenizer st1 = new StringTokenizer(mytime,”:”);StringTokenizer st2 = new StringTokenizer(systime,”:”);cnt=0;while(st1.hasMoreTokens() && st2.hasMoreTokens()){int n1 = Integer.parseInt(st1.nextToken());int n2 = Integer.parseInt(st2.nextToken()); if(n1 == n2){cnt++;}else{System.out.println(“Given time is out of the range, Try Again...”);break;}}}while(cnt < 2); System.out.println(“Given time is within the range”); }}Week-4a. Write a Java program to implement user defined exception handling.class NestTry{public static void main(String args[]) {try{int a = args.length;int b = 42 / a;System.out.println("a = " + a);try {if(a==1)a = a/(a-a);if(a==2) {int c[] = { 1 };c[42] = 99;}} catch(ArrayIndexOutOfBoundsException e) {System.out.println("Array index out-of-bounds: " + e);}} catch(ArithmeticException e) {System.out.println("Divide by 0: " + e);}}}Output:C:\>java NestTryDivide by 0: java.lang.ArithmeticException: / by zeroC:\>java NestTry Onea = 1Divide by 0: java.lang.ArithmeticException: / by zeroC:\>java NestTry One Twoa = 2Array index out-of-bounds:java.lang.ArrayIndexOutOfBoundsException:42b) Write a java program to create user-defined exception class.class MyException extends Exception {private int detail;MyException(int a) {detail = a;}public String toString() {return "MyException[" + detail + "]";}}class ExceptionDemo {static void compute(int a) throws MyException {System.out.println("Called compute(" + a + ")");if(a > 10)throw new MyException(a);System.out.println("Normal exit");}public static void main(String args[]) {try {compute(1);compute(20);} catch (MyException e) {System.out.println("Caught " + e);}}}Output:Called compute(1)Normal exitCalled compute(20)Caught MyException[20]b. Write java program that inputs 5 numbers, each between 10 and 100 inclusive. As eachnumber is read display it only if it‘s not a duplicate of any number already read. Display thecomplete set of unique values input after the user enters each new value.import java.io.*;import java.util.Scanner;public class week3b{public static void main(String[] args) { Scanner input = new Scanner(System.in); int sid[] = new int[5]; int count = 0; int x = 0; int num = 0; while (x < sid.length) { System.out.println(“Enter number: “); num = input.nextInt(); if ((num >= 10) && (num <= 100)) { for (int i = 0; i < sid.length; i++) { if (sid[i] == num) digit = true; } if (!digit) { System.out.println(“the number is” + num); sid[count] = num; count++; x++; } else System.out.printf(“The entered number already exist, Try again.. \n”); } else System.out.println(“number must be between 10 and 100, Try again..”); for (int i =0; i < x; i++) { System.out.print(sid[i] +” “); } } //End of while loop } } Output:enter 5 integers between 10 and 10012The elements are: 12enter 5 integers between 10 and 10033The elements are: 1233enter 5 integers between 10 and 1001000invalid rangeThe elements are: 1233Duplicate value enter 5 integers between 10 and 10055The elements are: 1233 55Week-5a. Write a Java program that creates a user interface to perform integer division. The userenters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2is displayed in the Result field when the Divide button is clicked. If Num1 and Num2 werenot integers, the program would throw a Number Format Exception. If Num2 were zero,the program would throw an Arithmetic Exception Display the exception in a messagedialog box.import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code=”week5a” width=500 height=500></applet>*/public class week5a extends Applet implements ActionListener {String msg;TextField num1,num2,res;Label l1,l2,l3;Button div;public void init(){l1=new Label(“Number 1”);l2=new Label(“Number 2”);l3=new Label(“result”);num1=new TextField(10);num2=new TextField(10);res=new TextField(10);div=new Button(“DIV”);div.addActionListener(this);add(l1);add(num1);add(l2);add(num2);add(l3);add(res);add(div);}public void actionPerformed(ActionEvent ae){String arg=ae.getActionCommand();if(arg.equals(“DIV”)){String s1=num1.getText();String s2=num2.getText();int num1=Integer.parseInt(s1);int num2=Integer.parseInt(s2);if(num2==0){try{System.out.println(“ “);}catch(Exception e){System.out.println(“ArithematicException”+e);}msg=”Arithemetic Exception”;repaint();}else if((num1<0)||(num2<0)){try{System.out.println(“”);}catch(Exception e){System.out.println(“NumberFormat”+e);}msg=”NumberFormat Exception”;repaint();}else{int num3=num1/num2;res.setText(String.valueOf(num3));}}}public void paint(Graphics g){g.drawString(msg,30,150);}}b. Write a Java program that creates three threads. First thread displays ―Good Morning?every one second, the second thread displays ―Hello? every two seconds and the third threaddisplays ―Welcome? every three seconds.class A extends Thread{synchronized public void run(){try{while(true){sleep(1000);System.out.println(“Good Morning”);}}catch(Exception e){ System.out.println(“Exception: “+e);}}}class B extends Thread{synchronized public void run(){try{while(true){sleep(2000);System.out.println(“Hello”);}}catch(Exception e){ System.out.println(“Exception: “+e);}}}class C extends Thread{synchronized public void run(){try{while(true){sleep(3000);System.out.println(“welcome”);}}catch(Exception e){ System.out.println(“Exception: “+e);}}}class Week4c{public static void main(String args[]){A t1=new A();B t2=new B();C t3=new C();t1.start();t2.start();t3.start();}}Week-6a. Write a java program to split a given text file into n parts. Name each part as the name ofthe original file followed by .part where n is the sequence number of the part file.import java.io.*;class FileSplit { public static void splitFile(File f) throws IOException { int partCounter = 1; long fsize = f.length(); System.out.println(“The file size is: “+fsize); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println(“How many file parts you want: “); int n = Integer.parseInt(br.readLine()); int sizeOfFiles =(int)fsize/n; byte[] buffer = new byte[sizeOfFiles]; BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f)); String name = f.getName(); int tmp = 0; while ((tmp = bis.read(buffer)) > 0) { File newFile = new File(f.getParent(), name + “.” + “part”+String.format(“%03d”, partCounter++)); FileOutputStream out = new FileOutputStream(newFile); out.write(buffer, 0, tmp); out.close(); } bis.close(); }public static void main(String[] args)throws IOException {// TODO Auto-generated method stubsplitFile(new File(“d:\\Vinu.txt”));}}b. Write a Java program that reads a file name from the user, displays information aboutwhether the file exists, whether the file is readable, or writable, the type of file and the lengthof the file in bytes.import java.io.*;import java.swing.*;class FileDemo{public static void main(String args[]){String filename = JOptionPane.showInputDialog("Enter filename: ");File f = new File(filename);System.out.println("File exists: "+f.exists());System.out.println("File is readable: "+f.canRead());System.out.println("File is writable: "+f.canWrite());System.out.println("Is a directory: "+f.isDirectory());System.out.println("length of the file: "+f.length()+" bytes");try{char ch;StringBuffer buff = new StringBuffer("");FileInputStream fis = new FileInputStream(filename);while(fis.available()!=0){ch = (char)fis.read();buff.append(ch);}System.out.println("\nContents of the file are: ");System.out.println(buff);fis.close();}catch(FileNotFoundException e){System.out.println("Cannot find the specified file...");}catch(IOException i){System.out.println("Cannot read file...");}}}OUTPUTFile name: sample.txtFile exists: trueFile is readable: trueFile is writable: trueIs a directory: falselength of the file: 20 bytesWeek-7a. Write a java program that displays the number of characters, lines and words in a text file.//Program to count number of lines,characters,and words in a text fileimport java.util.*;import java.io.*;class week7a{??????????? public static void main(String args[])throws IOException??????????? {??????????????????????? int nl=1,nw=0;?????????????????????? ????? ????? char ch;??????????????????????? Scanner scr=new Scanner(System.in);??????????????????????? System.out.print("\nEnter File name: ");??????????????????????? String str=scr.nextLine();??????????????????????? FileInputStream f=new FileInputStream(str);??????????????????????? int n=f.available();??????????????????????? for(int i=0;i<n;i++)??????????????????????? {??????????????????????????????????? ch=(char)f.read();??????????????????????????????????? if(ch=='\n')??????????????????????????????????? nl++;??????????????????????????????????? else if(ch==' ')??????????????????????????????????????????????? nw++;?????????????????????????????????????????????????????????????????????????????????????????????? }??????????????????????? System.out.println("\nNumber of lines : "+nl);??????????????????????? System.out.println("\nNumber of words : "+(nl+nw));??????????????????????? System.out.println("\nNumber of characters : "+n);?????????????????????????????? }}Output:Enter File name: temp.txtNumber of lines : 3Number of words : 3Number of characters : 26b. Write a java program that reads a file and displays the file on the screen with line numberbefore each line./Program to print the contents of the file along with line numberimport java.util.*;import java.io.*;class week7b{??????????? public static void main(String args[])throws IOException??????????? {??????????????????????? int j=1;??????????? ????? ????? char ch;??????????????????????? Scanner scr=new Scanner(System.in);??????????????????????? System.out.print("\nEnter File name: ");??????????????????????? String str=scr.next();??????????????????????? FileInputStream f=new FileInputStream(str);??????????????????????? System.out.println("\nContents of the file are");??????????????????????? int n=f.available();??????????????????????? System.out.print(j+": ");??????????????????????? for(int i=0;i<n;i++)??????????????????????? {??????????????????????????????????? ch=(char)f.read();??????????????????????????????????? System.out.print(ch);??????????????????????????????????? if(ch=='\n')??????????????????????????????????? {??????????????????????????????????????????????? System.out.print(++j+": ");?????????????????????????????????????????????????????????????????????????????????? }?????????????????????????????????????????????????????????????????????? }??????????? }}Output:Enter File name: temp.txtContents of the file are :1: aaaaa2: bbbb3: ccccWeek-8a. Write a Java program that correctly implements producer consumer problem using theconcept of inter thread communication.import java.util.Scanner;class Q{int n;Scanner sc=new Scanner(System.in);boolean valueSet=false;String d="";synchronized int get(){if(!valueSet)try{wait();}catch(InterruptedException e){System.out.println("Interrupted Exception caught");}System.out.println("Got:"+n);valueSet=false;notify();return n;}synchronized void put(int n){if(valueSet)try{wait();System.out.print("enter data");n=Integer.parseInt(sc.next());}catch(InterruptedException e){System.out.println("Interrupted Exception caught");}this.n=n;valueSet=true;System.out.println("Put:"+n);notify();}}class Producer implements Runnable{Q q;Producer(Q q){this.q=q;new Thread(this,"Producer").start();}public void run(){int i=0;while(true){q.put(i++);}}}class Consumer implements Runnable{Q q;Consumer(Q q){this.q=q;new Thread(this,"Consumer").start();}public void run(){while(true){q.get();}}}class Week18{public static void main(String[] args){Q q=new Q();new Producer(q);new Consumer(q);System.out.println("Press Control-c to stop");}}Output:Put:0Press Control-c to stopGot:0enter data65Put:65Got:65enter data33Put:33Got:33enter data8Put:8Got:8b. Develop a Java application for stack operation using Buttons and JOptionPane input andMessage dialog box.import javax.swing.JOptionPane;public class week8b{ public static void main (String args []) {Stack s = new Stack ();String choice;bVinodn done = false; while (!done) { try{ choice = JOptionPane.showInputDialog( "1. push \n" + "2. pop \n" + "3. peek \n" + "4. check empty \n" + "5. print the stack \n" + "6. exit \n \n" + "choose one:"); switch (Integer.parseInt(choice)){ case 1: String temp = JOptionPane.showInputDialog("Input integer to push:"); s.push(Integer.parseInt(temp)); break; case 2: JOptionPane.showMessageDialog(null, "The value popped is " + s.pop()); break; case 3: JOptionPane.showMessageDialog(null, "The value peeked at is " + s.peek()); break; case 4: if (s.empty()) { JOptionPane.showMessageDialog(null, "The stack is empty."); } else { JOptionPane.showMessageDialog(null, "The stack is not empty."); } break; case 5: JOptionPane.showMessageDialog(null, s.printStack()); break; case 6: JOptionPane.showMessageDialog(null, "...exiting"); done = true; break; default: JOptionPane.showMessageDialog(null, "You entered an invalid choice. \n" + "Please try again!"); } } catch (NumberFormatException ex) { JOptionPane.showMessageDialog( null, "You must type an integer. Please Try again!"); } } } }c. Develop a Java application to perform Addition, Division, Multiplication and substractionusing JOption Pane dialog Box and Text fields.import java.util.Scanner;import javax.swing.JoptionPane; public class week8c{ public static void main(String [] args) { Scanner norbel = new Scanner(System.in); int answer; String Fnumber = JoptionPane.showInputDialog(“Enter first Integer: “); int fnum = Integer.parseInt(Fnumber); fnum = norbel.nextInt(); String operator = JoptionPane.showInputDialog(“Operation:n 1.Additionn 2.Subtractionn 3.Multiplicationn 4.Divisionn”); Integer opt = Integer.parseInt(operator); if(opt == 1) { String opt1 = JoptionPane.showInputDialog(“Enter second Integer: “); int snum = Integer.parseInt(opt1); snum = norbel.nextInt(); answer = fnum + snum; String ans = “Answer” +answer+ “!”; JoptionPane.showMessageDialog(null,answer); if(opt == 2) { String opt2 = JoptionPane.showInputDialog(“Enter second Integer: “); int snum = Integer.parseInt(opt2); snum = norbel.nextInt(); answer = fnum - snum; String ans = “Answer” +answer+ “!”; JoptionPane.showMessageDialog(null,ans); } if(opt == 3) { String opt3 = JoptionPane.showInputDialog(“Enter second Integer: “); int snum = Integer.parseInt(opt3); snum = norbel.nextInt(); answer = fnum * snum; String ans = “Answer” +answer+ “!”; JoptionPane.showMessageDialog(null,ans); } if(opt == 4) { String opt4 = JoptionPane.showInputDialog(“Enter second Integer: “); int snum = Integer.parseInt(opt4); snum = norbel.nextInt(); answer = fnum / snum; String ans = “Answer” +answer+ “!”; JoptionPane.showMessageDialog(null,ans); } else { String error = “Error”; JoptionPane.showMessageDialog(null, error); } }}Week-9a. Develop a Java application for the blinking eyes and mouth should open while blinking.import java.applet.Applet;//<applet code="A.class" width=200 height=200></applet>import java.awt.BorderLayout;import java.awt.Canvas;import java.awt.Color;import java.awt.Graphics;public class A extends Applet { private static final long serialVersionUID = -1152278362796573663L; public class MyCanvas extends Canvas { private static final long serialVersionUID = -4372759074220420333L; private int flag = 0; public void paint(Graphics g) { draw(); } public void draw() { Graphics g = this.getGraphics(); g.setColor(Color.BLACK); super.paint(g); if (flag == 0) { System.out.println(flag); g.drawOval(40, 40, 120, 150);// face g.drawRect(57, 75, 30, 5);// left eye shut g.drawRect(110, 75, 30, 20);// right eye g.drawOval(85, 100, 30, 30);// nose g.fillArc(60, 125, 80, 40, 180, 180);// mouth g.drawOval(25, 92, 15, 30);// left ear g.drawOval(160, 92, 15, 30);// right ear flag = 1; } else { System.out.println(flag); g.drawOval(40, 40, 120, 150);// face g.drawOval(57, 75, 30, 20);// left eye g.drawOval(110, 75, 30, 20);// right eye g.fillOval(68, 81, 10, 10);// left pupil g.fillOval(121, 81, 10, 10);// right pupil g.drawOval(85, 100, 30, 30);// nose g.fillArc(60, 125, 80, 40, 180, 180);// mouth g.drawOval(25, 92, 15, 30);// left ear g.drawOval(160, 92, 15, 30);// right ear flag = 0; } try { Thread.sleep(900); } catch (Exception e) { System.out.println("killed while sleeping"); } this.repaint(100); } } public void init() { this.C = new MyCanvas(); this.setLayout(new BorderLayout()); this.add(C, BorderLayout.CENTER); C.setBackground(Color.GRAY); } private MyCanvas C;}b. Develop a Java application that simulates a traffic light. The program lets the user selectone of three lights: Red, Yellow or Green with radio buttons. On selecting a button anappropriate message with ―STOP? or ―READY? or ?GO? should appear above thebuttons in selected color. Initially, there is no message shown.import java.applet.Applet;import java.awt.*;import java.awt.event.*;/* * <applet code = "TrafficLightsExample" width = 1000 height = 500> * </applet> * */public class TrafficLightsExample extends Applet implements ItemListener{CheckboxGroup grp = new CheckboxGroup();Checkbox redLight, yellowLight, greenLight;Label msg;public void init(){redLight = new Checkbox("Red", grp, false);yellowLight = new Checkbox("Yellow", grp, false);greenLight = new Checkbox("Green", grp, false);msg = new Label("");redLight.addItemListener(this);yellowLight.addItemListener(this);greenLight.addItemListener(this);add(redLight);add(yellowLight);add(greenLight);add(msg);msg.setFont(new Font("Serif", Font.BOLD, 20));}public void itemStateChanged(ItemEvent ie) {redLight.setForeground(Color.BLACK);yellowLight.setForeground(Color.BLACK);greenLight.setForeground(Color.BLACK);if(redLight.getState() == true) {redLight.setForeground(Color.RED);msg.setForeground(Color.RED);msg.setText("STOP");}else if(yellowLight.getState() == true) {yellowLight.setForeground(Color.YELLOW);msg.setForeground(Color.YELLOW);msg.setText("READY");}else{greenLight.setForeground(Color.GREEN);msg.setForeground(Color.GREEN);msg.setText("GO");}}}OUTPUTWeek-10a. Develop a Java application to implement the opening of a door while opening man shouldpresent before hut and closing man should disappear.import javax.swing.*;import java.awt.*;import java.awt.event.*;class Animation extends JFrame implements ActionListener{ ImageIcon ii1, ii2; Container c; JButton b1,b2; JLabel lb1; Animation() { c = getContentPane(); c.setLayout(null); ii1 = new ImageIcon("house0.jpg"); ii2 = new ImageIcon("house1.jpg"); lb1 = new JLabel(ii1); lb1.setBounds(50,10,500,500); b1 = new JButton("Open"); b2 = new JButton("Close"); b1.addActionListener(this); b2.addActionListener(this); b1.setBounds(650,240,70,40); b2.setBounds(650,320,70,40); c.add(lb1); c.add(b1); c.add(b2); } public void actionPerformed(ActionEvent ae) { String str = ae.getActionCommand(); if( str.equals("Open") ) lb1.setIcon(ii2); else lb1.setIcon(ii1); } public static void main(String args[]) { Animation ob = new Animation(); ob.setTitle("Animation"); ob.setSize(800,600); ob.setVisible(true); ob.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }}b. Develop a Java application by using JtextField to read decimal value and converting adecimal number into binary number then print the binary value in another JtextField.// <applet code="week10bapplet.class" height=300 width=300></applet>import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;public class week10bapplet extends JApplet implements ActionListener{JPanel mainpanel=new JPanel(new GridLayout (3,1));JPanel p1=new JPanel(new FlowLayout(0));JPanel p2=new JPanel(new FlowLayout (0));JPanel p3=new JPanel(new FlowLayout ());JTextField q1=new JTextField (10);JTextField q2=new JTextField (10);JButton clickbutton = new JButton("convert");public void init(){getContentPane().add(mainpanel);mainpanel.add(p1);mainpanel.add(p2);mainpanel.add(p3);p1.add(new JLabel("Insert Decimal:"));p1.add(q1);p2.add(clickbutton);p3.add(new JLabel("Decimal to Binary:"));p3.add(q2);clickbutton.addActionListener(this);}public void actionPerformed(ActionEvent x){if(x.getSource()==clickbutton){int counter,dec,user;user=Integer.valueOf(q1.getText()).intValue();String[]conversion=new String[8];String[]complete=new String[4];counter=0;complete[0]="";do{dec=user%2;conversion[counter]=String.valueOf(dec);complete[0]=conversion[counter]+complete[0];user=user/2;counter+=1;}while(user !=0);q2.setText(String.valueOf(complete[user]));}}}Week-11a. Develop a Java application that handles all mouse events and shows the event name at thecenter of the window when a mouse event is fired. Use adapter classes.import java.awt.*;import java.awt.event.*;import java.applet.*;/* <applet code="Week11a" width=500 height=500></applet> */public class Week11a extends Appletimplements MouseListener,MouseMotionListener{int X=0,Y=20;String msg="MouseEvents";public void init(){addMouseListener(this);addMouseMotionListener(this);setBackground(Color.black);setForeground(Color.red);}public void mouseEntered(MouseEvent m){setBackground(Color.magenta);showStatus("Mouse Entered");repaint();}public void mouseExited(MouseEvent m){setBackground(Color.black);showStatus("Mouse Exited");repaint();}public void mousePressed(MouseEvent m){X=10;Y=20;msg="NEC";setBackground(Color.green);repaint();}public void mouseReleased(MouseEvent m){X=10;Y=20;msg="Engineering";setBackground(Color.blue);repaint();}public void mouseMoved(MouseEvent m){X=m.getX();Y=m.getY();msg="College";setBackground(Color.white);showStatus("Mouse Moved");repaint();}public void mouseDragged(MouseEvent m){msg="CSE";setBackground(Color.yellow);showStatus("Mouse Moved"+m.getX()+" "+m.getY());repaint();}public void mouseClicked(MouseEvent m){msg="Students";setBackground(Color.pink);showStatus("Mouse Clicked");repaint();}public void paint(Graphics g){g.drawString(msg,X,Y);}}Output:b. Develop a Java application to demonstrate the key event handlers.import java.awt.*;import java.awt.event.*;import java.applet.*;/*<applet code="KeyboardEventsPro" width=300 height=100></applet>*/public class KeyboardEventsPro extends Appletimplements KeyListener {String msg = "";int X = 10, Y = 20; // output coordinatespublic void init() {addKeyListener(this);}public void keyPressed(KeyEvent ke) {showStatus("Key Down");}public void keyReleased(KeyEvent ke) {showStatus("Key Up");}public void keyTyped(KeyEvent ke) {msg += ke.getKeyChar();repaint();}// Display keystrokes.public void paint(Graphics g) {g.drawString(msg, X, Y);}}Output:Week-12a. Develop a Java application to find the maximum value from the given type of elementsusing a generic function.public class MainClass { // determines the largest of three Comparable objects public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // assume x is initially the largest if (pareTo(max) > 0) max = y; // y is the largest so far if (pareTo(max) > 0) max = z; // z is the largest return max; // returns the largest object } // end method maximum public static void main(String args[]) { System.out.printf("Maximum of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5)); System.out.printf("Maximum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7)); System.out.printf("Maximum of %s, %s and %s is %s\n", "pear", "apple", "orange", maximum( "pear", "apple", "orange")); }}OUTPUTMaximum of 3, 4 and 5 is 5Maximum of 6.6, 8.8 and 7.7 is 8.8Maximum of pear, apple and orange is pearb. Develop a Java application that works as a simple calculator. Use a grid layout to arrangebuttons for the digits and for the +, -,*, % operations. Add a text field to display the result.import java.awt.*;import java.applet.*;import java.awt.event.*;/*<applet code=calc width=200 height=200></applet>*/public class calc extends Applet implements ActionListener{ TextField t1; String a="",b; String oper="",s="",p=""; int first=0,second=0,result=0; Panel p1; Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9; Button add,sub,mul,div,mod,res,space; public void init() { Panel p2,p3; p1=new Panel(); p2=new Panel(); p3=new Panel(); t1=new TextField(a,20); p1.setLayout(new BorderLayout()); p2.add(t1); b0=new Button("0"); b1=new Button("1"); b2=new Button("2"); b3=new Button("3"); b4=new Button("4"); b5=new Button("5"); b6=new Button("6"); b7=new Button("7"); b8=new Button("8"); b9=new Button("9"); add=new Button("+"); sub=new Button("-"); mul=new Button("*"); div=new Button("/"); mod=new Button("%"); res=new Button("="); space=new Button("c"); p3.setLayout(new GridLayout(4,4)); b0.addActionListener(this); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); b6.addActionListener(this); b7.addActionListener(this); b8.addActionListener(this); b9.addActionListener(this); add.addActionListener(this); sub.addActionListener(this); mul.addActionListener(this); div.addActionListener(this); mod.addActionListener(this); res.addActionListener(this); space.addActionListener(this); p3.add(b0); p3.add(b1); p3.add(b2); p3.add(b3); p3.add(b4); p3.add(b5); p3.add(b6); p3.add(b7); p3.add(b8); p3.add(b9); p3.add(add); p3.add(sub); p3.add(mul); p3.add(div); p3.add(mod); p3.add(res); p3.add(space); p1.add(p2,BorderLayout.NORTH); p1.add(p3,BorderLayout.CENTER); add(p1); } public void actionPerformed(ActionEvent ae) { a=ae.getActionCommand(); if(a=="0"||a=="1"||a=="2"||a=="3"||a=="4"||a=="5"||a=="6"||a=="7"||a=="8"||a=="9") { t1.setText(t1.getText()+a); } if(a=="+"||a=="-"||a=="*"||a=="/"||a=="%") { first=Integer.parseInt(t1.getText()); oper=a; t1.setText(""); } if(a=="=") { if(oper=="+") result=first+Integer.parseInt(t1.getText()); if(oper=="-") result=first-Integer.parseInt(t1.getText()); if(oper=="*") result=first*Integer.parseInt(t1.getText()); if(oper=="/") result=first/Integer.parseInt(t1.getText()); if(oper=="%") result=first%Integer.parseInt(t1.getText()); t1.setText(result+""); } if(a=="c") t1.setText(""); }} Output:c. Develop a Java application for handling mouse events.import java.awt.*;import java.awt.event.*;import java.applet.*;/* <applet code="Week11b" width=500 height=500></applet> */public class Week13 extends Appletimplements MouseListener,MouseMotionListener{int X=0,Y=20;String msg="MouseEvents";public void init(){addMouseListener(this);addMouseMotionListener(this);setBackground(Color.black);setForeground(Color.red);}public void mouseEntered(MouseEvent m){setBackground(Color.magenta);showStatus("Mouse Entered");repaint();}public void mouseExited(MouseEvent m){setBackground(Color.black);showStatus("Mouse Exited");repaint();}public void mousePressed(MouseEvent m){X=10;Y=20;msg="NEC";setBackground(Color.green);repaint();}public void mouseReleased(MouseEvent m){X=10;Y=20;msg="Engineering";setBackground(Color.blue);repaint();}public void mouseMoved(MouseEvent m){X=m.getX();Y=m.getY();msg="College";setBackground(Color.white);showStatus("Mouse Moved");repaint();}public void mouseDragged(MouseEvent m){msg="CSE";setBackground(Color.yellow);showStatus("Mouse Moved"+m.getX()+" "+m.getY());repaint();}public void mouseClicked(MouseEvent m){msg="Students";setBackground(Color.pink);showStatus("Mouse Clicked");repaint();}public void paint(Graphics g){g.drawString(msg,X,Y);}}Output:Week-13a. Develop a Java application to establish a JDBC connection, create a table student withproperties name, register number, mark1, mark2, mark3. Insert the values into the table byusing the java and display the information of the students at front end.import java.awt.*;import javax.swing.*;import java.sql.*;class StudentForm extends JFrame{JLable l1,l2,l3,l4,l5,l6,l7;JTextField t1,t2,t3,t4,t5,t6,t7;JButton b1,b2;Connection con;PreparedStatement insert;PreparedStatement update;PreparedStatement delet;PreparedStatement select;StudentForm(){setSize(355,300);setLocation(100,100);Container c=getContentPane();Title=new JLabel(“Student Details”);Title.setFont(new Font(“Dialog”,Font.BOLD,15));l1=new JLable(“Register No”);l2=new JLable(“Student Name”);l3=new JLable(“Marks1”);l4=new JLable(“Marks2”);l5=new JLable(“Marks3”);t1=new JTextField(10);t2=new JTextField(10);t3=new JTextField(10);t4=new JTextField(10);t5=new JTextField(10);b1=new JButton(“Insert”);b2=new JButton(“Display”);c.setLayout(null);title.setBounds(60,10,160,20);c.add(title);l1.setBounds(40,40,50,20);c.add(l1);t1.setBounds(95,40,108,20);c.add(t1);l2.setBounds(40,70,50,20);c.add(l2);t2.setBounds(95,70,108,20);c.add(t2);l3.setBounds(40,100,50,20);c.add(l3);t3.setBounds(95,100,108,20);c.add(t3);b1.setBounds(10,140,65,40);c.add(b1);b2.setBounds(77,140,65,40);c.add(b2);//b3.setBounds(144,140,65,40);//c.add(b3);//b4.setBounds(211,140,65,40);//c.add(b4);Info=new Label(“Getting connected to the database”);Info.setFont(new Font(“Dialog”,Font.BOLD,15));Info.setBounds(20,190,330,30);c.add(info);b1.addActionListener(new InsertListener());b2.addActionListener(new DisplayListener());setVisible(true);getConnection();}Void getConnection(){try{Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);String url=”jdbc:odbc:student”;Con=DriverManager.getConnection(url,”scott”,”tiger”);Info.setText(“Connection is established with the database”);insertps=con.prepareStatement(“Insert into student values(?,?,?,?,?)”);selectps=con.prepareStatement(“select * from student where studentno=?”);}Catch(ClassNotFoundExceptoin e){System.out.println(“Driver class not found….”);System.out.println(e);}Catch(SQLExceptoin e){Info.setText(“Unable to get connected to the database”);}}class insertListener implements ActionListener{Public void actionPerformed(ActionEvent e){Try{Int sno=Integer.parseInt(t1.getText());String name=t2.getText();Int m1= Integer.parseInt(t3.getText());Int m2=Integer.parseInt(t1.getText());Int m3=Integer.parseInt(t1.getText());Insertps.setInt(1,sno);Insertps.setString(2,name);Insertps.setInt(3,m1);Insertps.setInt(4,m2);Insertps.setInt(5,m3);Insertps.executeUpdate();Info.setText(“One row inserted successfully”);Insertps.clearParameters();T1.setText(“”);T2.setText(“”);T3.setText(“”);T4.setText(“”);T5.setText(“”);}Catch(SQLException se){Info.setText(“Failed to insert a record…”);}Catch(Exception de){Info.setText(“enter proper data before insertion….”);}}}Class DisplayListener implements ActionListener{Public void actionPerformed(ActionEvent e){ Try { Intsno=Integer.parseInt(t1.getText()); Selectps.setInt(1,sno); Selectps.execute(); ResultSet rs=selectps.getResultSet(); rs.next(); t2.setText(rs.getString(2)); t3.setText(“”+rs.getFloat(3)); info.setText(“One row displayed successfully”); selectps.clearPameters(); } Catch(SQLException se) { Info.setText(“Failed toshow the record…”); } Catch(Exception de){Info.setText(“enter proper student no before selectingshow..”);}}}Public static void main(String args[]){New StudentForm();}} ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download