Solving Simple Problems Using,: Java Programming Lab
Solving Simple Problems Using,: Java Programming Lab
Solving Simple problems using, 1. Abstract classes 2. Inheritance 3. Interfaces 4. Event handling using applets 5. Threads (single and multiple) 6. Swings 7. File handling and I/O handling 8. Database applications (JDBC)
-1-
ABSTRACT CLASS
To write a JAVA program for implemeting the Abstract class. ALGORITHM: STEP1 : Start the program. STEP2 : Create an abstract class figure and an abstract method area() STEP3 : Create two subclasses Rectangle and Triangle which are inherited the properties of figure. STEP4 : Object for Rectangle and Triangle are created in main class. STEP5 : The abstract method area() can be called using the reference variable of abstract class. STEP6 : Stop the program.
-2-
CODING: abstract class Figure { double dim1; double dim2; Figure(double a, double b) { dim1=a; dim2=b; } abstract double area(); } class Rectangle extends Figure { Rectangle(double a, double b) { super(a,b); } double area() { System.out.println("Inside Area for Rectangle."); return dim1*dim2; } } class Triangle extends Figure { Triangle (double a, double b) { super(a,b); }
-3-
double area() { System.out.println("Inside Area for Triangle."); return dim1*dim2/2; } } class AbstractArea { public static void main(String args[]) { Rectangle r=new Rectangle(9,5); Triangle t=new Triangle(10,8); Figure figref; figref=r; System.out.println("Area is "+figref.area()); figref=t; System.out.println("Area is "+figref.area()); } }
OUTPUT:
-4-
RESULT: Thus the JAVA program for Abstract class has been created and executed successfully.
Ex. No :2 a
SIMPLE INHERITANCE
-5-
Date:
AIM: To write a JAVA program for implementing the Inheritance.
ALGORITHM: STEP1: Start the program. STEP2: In single inheritance the object can be created for subclass which is used to access super class methods & data members. STEP3: In multilevel inheritance the constructor of the immediate super class can be referred using super keyword. STEP4: If a same method is defined in sub class & super class the sub class method will be override by super class method. STEP5: In case of Dynamic method dispatch the super class reference variable can refer to sub class object to resolve calls overridden method at run time. STEP6: Stop the program.
CODING:
-6-
class Box { private double width; private double height; private double depth; Box(Box ob) { width=ob.width; height=ob.height; depth=ob.depth; } Box(double w,double h,double d) { width=w; height=h; depth=d; } Box() { width=-1; height=-1; depth=-1; } Box(double len) { width=height=depth=len; } double volume() { return width*height*depth; } } class BoxWeight extends Box {
-7-
double weight; BoxWeight(BoxWeight ob) { super(ob); weight=ob.weight; } BoxWeight(double w,double h,double d,double m) { super(w,h,d); weight=m; } BoxWeight() { super(); weight=-1; } BoxWeight(double len,double m) { super(len); weight=m; } } class Demosuper { public static void main(String args[]) { BoxWeight mybox1=new BoxWeight(10,20,15,34.3); BoxWeight mybox2=new BoxWeight(2,3,4,0.076); BoxWeight mybox3=new BoxWeight(); BoxWeight mycube=new BoxWeight(3,2); BoxWeight myclone=new BoxWeight(mybox1); double vol; vol=mybox1.volume(); System.out.println("Volume of mybox1 is : "+vol);
-8-
System.out.println("Weight of mybox1 is : "+mybox1.weight); System.out.println(); vol=mybox2.volume(); System.out.println("Volume of mybox2 is : "+vol); System.out.println("Weight of mybox2 is : "+mybox2.weight); System.out.println(); vol=mybox3.volume(); System.out.println("Volume of mybox3 is : "+vol); System.out.println("Weight of mybox3 is : "+mybox3.weight); System.out.println(); vol=myclone.volume(); System.out.println("Volume of myclone is : "+vol); System.out.println("Weight of myclone is : "+myclone.weight); System.out.println(); vol=mycube.volume(); System.out.println("Volume of mycube is : "+vol); System.out.println("Weight of mycube is : "+mycube.weight); System.out.println(); } }
OUTPUT:
-9-
RESULT: Thus the JAVA program for Inheritance has been created and executed successfully.
Ex. No:2 b
MULTILEVEL INHERITANCE
- 10 -
Date:
AIM: To write a JAVA program for implementing the Inheritance.
ALGORITHM: STEP1: Start the program. STEP2: In single inheritance the object can be created for subclass which is used to access super class methods & data members. STEP3: In multilevel inheritance the constructor of the immediate super class can be referred using super keyword. STEP4: If a same method is defined in sub class & super class the sub class method will be override by super class method. STEP5: In case of Dynamic method dispatch the super class reference variable can refer to sub class object to resolve calls overridden method at run time. STEP6: Stop the program.
CODING:
- 11 -
class Box { private double width; private double height; private double depth; Box(Box ob) { width=ob.width; height=ob.height; depth=ob.depth; } Box(double w,double h,double d) { width=w; height=h; depth=d; } Box() { width=-1; height=-1; depth=-1; } Box(double len) { width=height=depth=len; } double volume() { return width*height*depth; } } class BoxWeight extends Box
- 12 -
{ double weight; BoxWeight(BoxWeight ob) { super(ob); weight=ob.weight; } BoxWeight(double w,double h,double d,double m) { super(w,h,d); weight=m; } BoxWeight() { super(); weight=-1; } BoxWeight(double len,double m) { super(len); weight=m; } } class Shipment extends BoxWeight { double cost; Shipment(Shipment ob) { super(ob); cost=ob.cost; } Shipment(double w,double h,double d,double m,double c) { super(w,h,d,m);
- 13 -
cost=c; } Shipment() { super(); cost=-1; } Shipment(double len,double m,double c) { super(len,m); cost=c; } } class DemoShipment { public static void main(String args[]) { Shipment Shipment1=new Shipment (10,20,15,10,3.41); Shipment Shipment2=new Shipment (2,3,4,0.76,1.28); double vol; vol= Shipment1.volume(); System.out.println("Volume of Shipment1 is : "+vol); System.out.println("Weight of Shipment1 is : "+ Shipment1.weight); System.out.println("Shipping cost:$"+ Shipment1.cost); System.out.println(); vol= Shipment2.volume(); System.out.println("Volume of Shipment2 is : "+vol); System.out.println("Weight of Shipment2 is : "+ Shipment2.weight); System.out.println("Shipping cost:$"+ Shipment2.cost); System.out.println(); } }
- 14 -
OUTPUT:
RESULT: Thus the JAVA program for Inheritance has been created and executed successfully.
- 15 -
INTERFACES
Step 1: Start the program. Step 2: Declare the class & interface. Step 3: Include the interface to our main method class with help of Implements. Step 4: Define the function which present in the interface. Step 5: Call the function with help of object. Step 6: Stop the program.
PROGRAM:
import java.io.*; class data { int a; int b; } interface method { public int add(int x, int y); public int sub(int x, int y); public int mul(int x, int y); public int div(int x,int y);
- 16 -
} class inte extends data implements method { public int add(int x, int y) { return (x + y); } public int sub(int x, int y) { return (x - y); } public int mul(int x, int y) { return (x * y); } public int div(int x, int y) { Return(x/y); } public static void main(String arg[]) throws Exception { inte a1 = new inte(); DataInputStream d = new DataInputStream(System.in); System.out.println("Enter the first value"); String text= d.readLine(); a1.a = Integer.parseInt(text); System.out.println("Enter the second value"); text = d.readLine(); a1.b = Integer.parseInt(text); while (true) { System.out.println("1.add\n2.sub\n3.mul\n4.div\n5.exit"); System.out.println("Enter your choice"); text = d.readLine(); int c=Integer.parseInt(text); switch (c) { case 1: System.out.println("ADDTION RESULT IS:" + a1.add(a1.a,a1.b)); break;
- 17 -
case 2: System.out.println("SUBRATION RESULT IS:" + a1.sub(a1.a, a1.b)); break; case 3: System.out.println("MULTIPLICATION RESULT IS:" + a1.mul(a1.a,a1. b)); Case 4: System.out.println(DIVISION RESULT IS:+a1.div(a1.a,a1.b)); break; default: System.exit(0); } } } } OUTPUT: D:\jdk1.5\bin>javac inte.java D:\jdk1.5\bin>java inte Enter the first value 100 Enter the second value 50 1.add 2.sub 3.mul 4.exit Enter your choice 1 ADDTION RESULT IS:150 1.add 2.sub 3.mul 4.exit Enter your choice 2 SUBRATION RESULT IS:50 1.add 2.sub
- 18 -
3.mul 4.exit Enter your choice 3 MULTIPLICATION RESULT IS:5000 1.add 2.sub 3.mul 4.exit Enter your choice 4
- 19 -
RESULT: Thus the implementation of interface concept in java program was executed and verified successfully.
- 20 -
APPLETS
To write a JAVA program for Applets. ALGORITHM: STEP1: Start the program. STEP2: Applets are smalll applications that produce an arbitrary multimedia user Interface. STEP3: The mouse events can be handled using the Applet application. STEP4: The keyboard events key up,key down and key pressed are accessed by extending the class to Applet STEP5: The virtual keycodes are used to handle the special keys suych as arroe or function keys. STEP6: Adapter classes can simplify the creation of event handlers in certain situations. STEP7: Stop the execution.
- 21 -
import java.awt.*; import java.applet.*; import java.awt.event.*; /*<applet code=kmevent width=300 height=400> </applet>*/ public class kmevent extends Applet implements KeyListener, MouseListener { String msg = " KEYBOARD"; String msgm = " MOUSE"; int x = 250, y = 250; public void init() { addKeyListener(this); addMouseListener(this); } public void paint(Graphics g) { g.drawString("WELCOME TO KEY & MOUSE LISTENER",x, y); g.drawString(msg, x+100, y+100); g.drawString(msgm, x + 100, y+200); } public void keyPressed(KeyEvent ke) { msg = "KEY PRESSED"; repaint(); } public void keyReleased(KeyEvent ke) { msg = "KEY RELEASED"; repaint(); } public void keyTyped(KeyEvent ke) { msg = "KEY TYPED "; repaint(); }
- 22 -
public void mouseClicked(MouseEvent me) { msgm = "MOUSE CLICKED"; repaint(); } public void mouseEntered(MouseEvent me) { msgm = "MOUSE ENTERED"; repaint(); } public void mouseExited(MouseEvent me) { msgm = "MOUSE EXITED"; repaint(); } public void mouseReleased(MouseEvent me) { msgm = "MOUSE RELEASED"; repaint(); } public void mousePressed(MouseEvent me) { msgm = "MOUSE PRESSED"; repaint(); } public void mouseDragged(MouseEvent me) { msgm = "MOUSE DRAGGED"; repaint(); } }
OUTPUT:
- 23 -
RESULT: Thus the JAVA program for Applets was implemented and executed successfully.
Ex. No:5 a
SINGLE THREADS
- 24 -
Date:
AIM: To write a JAVA program for implementing Single Threads. ALGORITHM: STEP1: Start the program. STEP2: Threads can be creates by either implementing Runnable interface or extending Thread class. STEP3: In case of implementing Runnable, the class must provide implementation for run() method. STEP4: In case of extending the Thread class, the extending class will override the run() method. STRP5: start() method must be called to begin the execution. STEP6: Multiple threads can be created in a single program. STEP7: sleep(10000) cause main thread to sleep for 10 seconds and ensures that it will finish last. STEP8: isAlive() and join() methods are used to ensure that all the threads had completed before the completion of main thread. STEP9: Methods can be synchronized for accessing shared resources by multiple threads. STEP10: This can be implemented by putting calls to methods in synchronized blocks. STEP11: suspend() and resume() methods are used to pause and restart the threads. STEP12: wait() and notify() methods are to suspend and resume the threads by setting the suspendFlag to true or false. STEP13: stop() method is to terminate the thread. STEP14: Stop the program. CODING:
- 25 -
class NewThread implements Runnable { Thread t; NewThread() { //Create a new,second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start (); //Start the thread } //This I sthe entry point for the second thread. public void run() { try { for( int i = 5; i > 0; i --) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted"); } System.out.println("Exiting child thread"); } } class ThreadDemo { public static void main(String args[ ]) { new NewThread(); // Create a new thread
- 26 -
try { for(int i = 5; i > 0; i --) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main Thread Interrupted."); } System.out.println("Main Thread Exiting."); } }
- 27 -
OUTPUT:
RESULT: Thus the JAVA program for Single Threads has been implemented and executed successfully.
MULTIPLE THREADS
- 28 -
AIM: To write a JAVA program for implementing Multiple Threads. ALGORITHM: STEP1: Start the program. STEP2: Threads can be creats by either implementing Runnable interface or extending Thread class. STEP3: In case of implementing Runnable,the class must provide implementation for run() method. STEP4: In case of extending the Thread class, the extending class will override the run() method. STRP5: start() method must be called to begin the execution. STEP6: Multiple threads can be created in a single program. STEP7: sleep(10000) cause main thread to sleep for 10 seconds and ensures that it will finish last. STEP8: isAlive() and join() methods are used to ensure that all the threads had completed before the completion of main thread. STEP9: Methods can be synchronized for accessing shared resources by multiple threads. STEP10:This can be implemented by putting calls to methods in synchronized blocks. STEP11:suspend() and resume() methods are used to pause and restart the threads. STEP12:wait() and notify() methods are to suspend and resume the threads by setting the suspendFlag to true or false. STEP13:stop() method is to terminate the thread. STEP14:Stop the program. CODING: class newThread implements Runnable
- 29 -
{ String name; Thread t; newThread(String threadname) { name = threadname; t = new Thread(this,name); System.out.println("New thread: " + t); t.start(); } //this is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i --) { System.out.println(name + " : " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + "interrupted"); } System.out.println(name + "exiting"); //Start the thread //name of thread
- 30 -
} }
class MThread { public static void main(String args[ ]) { new newThread("One"); new newThread("Two"); new newThread("Three"); try { //wait for other threads to end //start threads
- 31 -
OUTPUT:
- 32 -
RESULT: Thus the JAVA program for Multiple Threads has been implemented and executed successfully.
- 33 -
SWINGS
To write a JAVA program for swings. ALGORITHM: STEP1: Start the program. STEP2: Buttons, checkboxes,scroll panes,tabbed panes,etc., can be included in our application using swing. STEP3: JButton class provides the functionality of push button. STEP4: It displays the specified string when the button is pushed. STEP5: Checkbox functionality was provided by JcheckBox class. STEP6: In addition to string and icon it provides state,that says whether the checkbox had selected or not. STEP7: JradioButton class provides the functionality of Radiobutton. STEP8: Combo Box can be provided using JcomboBox class. STEP9: addItem() method is used to add the choices to the list. STEP10: Tabbed panes encapsulated by JtabbedPane class. STEP11: It includes str and comp.str is the title of the tab and cmp is the component added to the tab. STEP12:Scroll panes are implemented using JscrollPane class. STEP13:The constructors of the class indicates the componentsto be added,horizontal or vertical scroll bars, etc., STEP14:Tables are implemented using JTable class. STEP15:Using the constructor Jtable(object data[][],object colhead[][]) we can insert data and column headings to the table. STEP16:Stop the execution.
- 34 -
CODING:
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Swi extends JApplet implements ActionListener { Container con; JLabel l1, l2, l3; JButton b1, b2,b3; JTextField t1,t2,t3; public void init() { con = getContentPane(); con.setLayout(new FlowLayout()); t1 = new JTextField(10); t2 = new JTextField(10); t3 = new JTextField(10); b1 = new JButton("ADD"); b2 = new JButton("SUB"); l1 = new JLabel("Enter the First mark"); l2 = new JLabel("Enter the Second mark"); l3 = new JLabel("RESULT:"); con.add(l1); con.add(t1); con.add(l2); con.add(t2); con.add(l3); con.add(t3); con.add(b1,"East"); con.add(b2); b1.addActionListener(this); b2.addActionListener(this); } public void actionPerformed(ActionEvent ae) { String text = ae.getActionCommand(); String con; int x; if (text.equals("ADD")) {
- 35 -
- 36 -
OUTPUT:
RESULT: Thus the JAVA program for Swings was implemented and executed successfully.
- 37 -
To write a JAVA program for handling Files and I/O. ALGORITHM: STEP1: Start the program STEP2: Create an object for file input stream class. STEP3: Using that object open the specified file, show the contents and close the file. STEP4: Create an object for FileOutputstream class. STEP5: Using the objects of FileInputstream and FileOutputstream, copy the content of one file to another file. STEP6: read() and write() methods are used to read and write the contents from and to the file. STEP7: Stop the execution.
- 38 -
CODING:
import java.io.*; class fileReader { public static void main(String arg[]) throws Exception { BufferedReader input=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the file name to be opened"); String t=input.readLine(); FileReader fi=new FileReader(t); BufferedReader buff=new BufferedReader(fi); int text; System.out.println(File Content is.); while((text=buff.read())!=-1) { System.out.print((char)text); } buff.close(); } }
- 39 -
OUTPUT:
RESULT: Thus the JAVA program for handling Files and I/O has been created and executed successfully.
- 40 -
To create a java program that implements database connectivity using JDBC concept.
ALGORITHM:
Step 1: Start the program. Step 2: Declare the variables and header files that are needed to perform the complete operation. Step 3: Create a layout to show the details retrieved from the database. Step 4: Load the database driver and create the instance for connection. Step 5: Create label for each object that is used to show the employee details in the form. Step 6: Stop the program.
- 41 -
CODING: import java.sql.*; import java.io.*; import java.lang.*; public class jdbc { static Statement stmt; public static void main(String args[])throws SQLException, IOException { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection("jdbc:odbc:my"); float tot,avg,mm1,mm2,mm3; String result,grade; grade =""; stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery("SELECT * FROM marks"); while (rset.next()) { mm1= Integer.parseInt(rset.getString(3)); mm2= Integer.parseInt(rset.getString(4)); mm3= Integer.parseInt(rset.getString(5)); tot = mm1+mm2+mm3; avg = tot/3; if (mm1 >=50 && mm2>=50 && mm3>=50) { result= "Pass"; if(avg > 75.0 ) { } if(avg >=60 && avg <75 ) { } if(avg >=50 && avg <60 ) { } grade ="Second class"; grade ="First class"; grade ="First class with Dist.";
- 42 -
} else result="Fail"; System.out.println("Roll No System.out.println("Name System.out.println("Unix System.out.println("VC++: " +mm3); System.out.println("Total System.out.println("Result System.out.println("Percentage if(!result.equals("Fail")) System.out.println("Grade : "+ grade); : "+ tot); : "+ result); : "+ avg); : " +rset.getString(1) + "\t"); : " +rset.getString(2) + "\t"); : " +mm2);
OUTPUT:
- 43 -
Roll No Name Web Technology Unix VC++ Total Result Percentage Grade
:1 : Kanishka : 80.0 : 90.0 : 90.0 : 260.0 : Pass : 86.666664 : First class with Dist.
---------------------------------------------Roll No Name Web Technology Unix VC++ Total Result Percentage Grade :2 : venu : 78.0 : 90.0 : 50.0 : 218.0 : Pass : 72.666664 : First class
RESULT: Thus a program that implements database connectivity using JDBC was executed successfully.
- 44 -