LAB MANUAL For OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB 4136 Diploma In Computer Engineering IVth semester By MDIT Polytechnic College Ulliyeri CYCLE I 1. 2. 3. 4. 5. 6. 7. 8. 9. Write a java program to print a text Write a java program to Print an Integer entered by an user Class object Array of objects in Java Passing and returning objects as arguments Constructor –default and parameterized Method overloading Static variables and methods. Exception handling mechanism. CYCLE II 1. 2. 3. 4. 5. Single inheritance Multilevel inheritance Hierarchical inheritance Interfaces Packages CYCLE III 1. Experiment 1 : Print a text Aim Write a java program to print a text Program class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } Result Program executed successfully and obtained the output Experiment 2 : Print an Integer Aim Write a java program to Print an Integer entered by an user Program import java.util.Scanner; public class HelloWorld { public static void main(String[] args) { // Creates a reader instance which takes input from standard input - keyboard Scanner reader = new Scanner(System.in); System.out.println("Enter a number: "); // nextInt() reads the next integer from the keyboard int number = reader.nextInt(); System.out.println("You entered: " + number); } } Result Program executed successfully and obtained the output Experiment 3 : Class and object Theory Class A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. A class in Java can contain: o Fields o Methods o Constructors o Blocks o Nested class and interface Objects An object in Java is the physical as well as a logical entity,whereas, a class in Java is a logical entity only. An object is an instance of a class; Object is a real world entity. The object is an entity which has state and behavior. Aim Write a java program to Input & print student details using class and object Program import java.util.Scanner; class Student{ void getDetails(){ Scanner sc = new Scanner(System.in); System.out.println("***Input the asked details***"); System.out.println("Enter Roll Number:"); int rollNo = sc.nextInt(); System.out.println("Enter Name:"); String name = sc.next(); System.out.println("Enter Age:"); int age = sc.nextInt(); System.out.println("Enter City:"); String city = sc.next(); System.out.println("Enter Course:"); String course = sc.next(); System.out.println("***Inputed Student Details***"); System.out.println("Roll Number:"+rollNo); System.out.println("Name:"+name); System.out.println("Age:"+age); System.out.println("City:"+city); System.out.println("Course:"+course); } } class Main{ public static void main(String[] args) { Student st = new Student(); st.getDetails(); } } Result Program executed successfully and obtained the output Experiment 4 : Array of objects in Java Aim Write a program to print students details using array of objects. Program import java.util.Scanner; class Student { private String name; private int marks; public void setDetails(String n, int m) { name = n; marks = m; } public void printDetails() { System.out.println("Name: " + name); System.out.println("Marks: " + marks); } } class Test { public static void main(String[] args) { // declaring array of objects Student[] st = new Student[5]; // initializing array Scanner s = new Scanner(System.in); for (int i = 0; i < 5; i++) { System.out.println("Student " + (i + 1)); System.out.println("Enter name"); String name = s.next(); System.out.println("Enter marks"); int marks = s.nextInt(); st[i] = new Student(); st[i].setDetails(name, marks); } // printing details of the objects for (int i = 0; i < 5; i++) { st[i].printDetails(); } } } Result Program executed successfully and obtained the output Experiment 5 : Passing and returning objects as arguments Aim Write a program to print the area of a rectangle by passing the object as arguments and returning the object Program import java.util.Scanner; public class Object_Pass { int length, breadth, area; Object_Pass area1(Object_Pass object1) { object1 = new Object_Pass(); object1.length = this.length; object1.breadth = this.breadth; object1.area = object1.length * object1.breadth; return object1; } Object_Pass area2(Object_Pass object2) { object2 = new Object_Pass(); object2.length = this.length + 5; object2.breadth = this.breadth + 6; object2.area = object2.length * object2.breadth; return object2; } public static void main(String[] args) { Object_Pass obj = new Object_Pass(); Scanner s = new Scanner(System.in); System.out.print("Enter length:"); obj.length = s.nextInt(); System.out.print("Enter breadth:"); obj.breadth = s.nextInt(); Object_Pass a = obj.area1(obj); Object_Pass b = obj.area2(obj); System.out.println("Area:"+a.area); System.out.println("Area:"+b.area); } } Result Program executed successfully and obtained the output Experiment 6 : Constructor –default and parameterized Theory Constructor Constructors are special methods that are generally used to initialize an instance of a class. Constructors do not have a return type, they have the same name as the class, and may or may not contain parameters. Types of constructorsa. Default constructor – constructor which does not take any argument b. Parameterized constructor – constructors with parameters Aim Write a program to illustrate the working of default and parameterized constructor Program public class Constructor { double width; double height; double depth; Constructor() { System.out.println("Constructor without parameter"); width = 10; height = 10; depth = 10; } Constructor(int a, int b, int c) { System.out.println("Constructor with parameter"); width = a; height = b; depth = c; } double volume() { return width * height * depth; } } class ConstructorDemo { public static void main(String args[]) { Constructor cuboid1 = new Constructor(); double vol; vol = cuboid1.volume(); System.out.println("Volume is " + vol); Constructor cuboid2 = new Constructor(8,11,9); vol = cuboid2.volume(); System.out.println("Volume is " + vol); } } Result Program executed successfully and obtained the output Experiment 7 : Method overloading Theory If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. Advantage of method overloading Method overloading increases the readability of the program. Different ways to overload the method There are two ways to overload the method in java 1. By changing number of arguments 2. By changing the data type Aim Write a program to find the sum of numbers using method overloading class Overload { int add(int a, int b) { int sum = a+b; return sum; } int add(int a, int b, int c) { int sum = a+b+c; return sum; } } class JavaExample { public static void main(String args[]) { Overload obj = new Overload(); System.out.println(obj.add(10, 20)); System.out.println(obj.add(10, 20, 30)); } } Result Program executed successfully and obtained the output Experiment 8 : Static variable and method Theory Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. Static variables can be accessed by calling with the class name ClassName.VariableName. Static method is a special member function which is used to access only static data members any other normal data members cannot be accessed through static member function-example Aim Write a Java program to demonstrate example of static variable and static method Program import java.util.*; class Item { private String itemName; private int quantity; private static int cnt = 0; //variable to count public void getItem() { Scanner sc = new Scanner(System.in); System.out.print("Enter item name: "); itemName = sc.next(); System.out.print("Enter item quantity: "); quantity = sc.nextInt(); //increment counter cnt++; } public void showItem() { System.out.println("Item Name: " + itemName + "\tQuantity: " + quantity); } public static int getCounter() { return cnt; } } public class StaticVar { public static void main(String[] s) { try { Item I1 = new Item(); Item I2 = new Item(); Item I3 = new Item(); I1.getItem(); I2.getItem(); I3.getItem(); I1.showItem(); I2.showItem(); I3.showItem(); System.out.println("Total object created (total items are): " + Item.getCounter()); } } } Result Program executed successfully and obtained the output Experiment 9 : Exception handling mechanism Theory Exception is an error event that can happen during the execution of a program and disrupts it’s normal flow. Exception can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure etc Exception handling is the process of handling errors and exceptions in such a way that they do not hinder normal execution of the system. Exceptions. are also known as Run Time Errors Exception handling is built upon three keywords: try, catch, and throw,finally. Throw - A program throws an exception when a problem shows up Catch - A program catches an exception. Try- identifies a block of code for which particular exceptions will be activated Finally - finally block is optional and can be used only with try-catch block. finally block gets executed always, whether exception occurrs or not. Aim Write a Java program to demonstrate exception handling mechanism in java Program import java.util.Scanner; public class JavaExample { public static void main(String[] args) { int num1, num2; Scanner scan = new Scanner(System.in); System.out.print("Enter first number(dividend): "); num1 = scan.nextInt(); System.out.print("Enter second number(divisor): "); num2 = scan.nextInt(); try { int div = num1 / num2; System.out.println("Quotient: "+div); }catch(ArithmeticException e){ System.out.println("Do not enter divisor as zero."); System.out.println("Error Message: "+e); } } } Result Program executed successfully and obtained the output Experiment 10 : Single inheritance Theory . Inheritance is an Object oriented feature which allows a class to inherit behavior and data from other class Single inheritance - a derived class is inherited from the only one base class example Aim Write a program illustrate Single Inheritance in Java Program class Employee { void salary() { System.out.println("Salary= 200000"); } } class Programmer extends Employee { // Programmer class inherits from Employee class void bonus() { System.out.println("Bonus=50000"); } } class single_inheritance { public static void main(String args[]) { Programmer p = new Programmer(); p.salary(); // calls method of super class p.bonus(); // calls method of sub class } } Result Program executed successfully and obtained the output Experiment 11 : Multilevel inheritance Theory Multilevel inheritance- deriving a class from another derived class Aim Write a program illustrate multilevel Inheritance in Java Program class Car{ public Car() { System.out.println("Class Car"); } public void vehicleType() { System.out.println("Vehicle Type: Car"); } } class Maruti extends Car{ public Maruti() { System.out.println("Class Maruti"); } public void brand() { System.out.println("Brand: Maruti"); } public void speed() { System.out.println("Max: 90Kmph"); } } public class Maruti800 extends Maruti{ public Maruti800() { System.out.println("Maruti Model: 800"); } public void speed() { System.out.println("Max: 80Kmph"); } public static void main(String args[]) { Maruti800 obj=new Maruti800(); obj.vehicleType(); obj.brand(); obj.speed(); } } Result Program executed successfully and obtained the output Experiment 12 : Theory Hierarchical inheritance Hierarchical inheritance - deriving more than one class from a base class – example Aim Write a program illustrate hierarchical Inheritance in Java Program class Employee { double salary = 50000; void displaySalary() { System.out.println("Employee Salary: Rs."+salary); } } class FullTimeEmployee extends Employee{ double hike = 0.50; void incrementSalary() { salary = salary + (salary * hike); } } class InternEmployee extends Employee{ double hike = 0.25; void incrementSalary() { salary = salary + (salary * hike); } } public class Main { public static void main(String[] args) { FullTimeEmployee emp1 = new FullTimeEmployee(); InternEmployee emp2 = new InternEmployee(); System.out.println("Salary of a full-time employee before incrementing:"); emp1.displaySalary(); System.out.println("Salary of an intern before incrementing:"); emp2.displaySalary(); emp1.incrementSalary(); emp2.incrementSalary(); System.out.println("Salary of a full-time employee after incrementing:"); emp1.displaySalary(); System.out.println("Salary of an intern after incrementing:"); emp2.displaySalary(); } } Result Program executed successfully and obtained the output Experiment 13 : Interface Theory An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. A Java interface contains static constants and abstract methods. A class can implement multiple interfaces. In Java, interfaces are declared using the interface keyword. All methods in the interface are implicitly public and abstract. Aim Write a program illustrate interface in Java Program interface Teacher { void display1(); } class Student { void display2() { System.out.println("Hi I am Student"); } } class College extends Student implements Teacher { public void display1() { System.out.println("Hi I am Teacher"); } } class Interface_Class { public static void main(String arh[]) { College c=new College(); c.display1(); c.display2(); } } Result Program executed successfully and obtained the output Experiment 13 Theory : Packages A java package is a group of similar types of classes, interfaces and subpackages. Package in java can be categorized in two form, built-in package and userdefined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc. Java package can be compiled using the command 1. javac -d directory javafilename There are three ways to access the package from outside the package. 1. import package.*; - The import keyword is used to make the classes and interface of another package accessible to the current package. 2. import package.classname; - Using package.classname then only declared class of this package will be accessible 3. fully qualified name - Using fully qualified name then only declared class of this package will be accessible. It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class. Aim Java program to implement package in java Program package pack; public class Addition { int x,y; public Addition(int a, int b) { x=a; y=b; } public void sum() { System.out.println("Sum :"+(x+y)); } } Step 1: Save the above file with Addition.java package pack; public class Subtraction { int x,y; public Subtraction(int a, int b) { x=a; y=b; } public void diff() { System.out.println("Difference :"+(x-y)); } } Step 2: Save the above file with Subtraction.java Step 3: Compilation To compile the java files use the following commands javac -d directory_path name_of_the_java file Javac –d . name_of_the_java file Step 4: Access package from another package There are three ways to use package in another package: 1. With fully qualified name. class UseofPack { public static void main(String arg[]) { pack.Addition a=new pack.Addition(10,15); a.sum(); pack.Subtraction s=new pack.Subtraction(20,15); s.difference(); } } 2. import package.classname; import pack.Addition; import pack.Subtraction; class UseofPack { public static void main(String arg[]) { Addition a=new Addition(10,15); a.sum(); Subtraction s=new Subtraction(20,15); s.difference(); } } 3. import package.*; import pack.*; class UseofPack { public static void main(String arg[]) { Addition a=new Addition(10,15); a.sum(); Subtraction s=new Subtraction(20,15); s.difference(); } } Result Program executed successfully and obtained the output Experiment 14 : SWING package. . Theory Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written in java. It is platform independent unlike AWT and has lightweight components. Container Class Any class which has other components in it is called as a container class. For building GUI applications at least one container class is necessary. Following are the three types of container classes: 1. Panel – It is used to organize components on to a window 2. Frame – A fully functioning window with icons and titles 3. Dialog – It is like a pop up window but not fully functional like the frame Aim Write programs to illustrate the GUI applications using the SWING package Program JButton Class It is used to create a labelled button. It inherits the AbstractButton class and is platform independent. JTextField Class It inherits the JTextComponent class and it is used to allow editing of single line text. JPanel Class It inherits the JComponent class and provides space for an application which can attach any other component. JMenu Class It inherits the JMenuItem class, and is a pull down menu component which is displayed from the menu bar. import javax.swing.*; import java.awt.*; class gui { public static void main(String args[]) { //Creating the Frame JFrame frame = new JFrame("Chat Frame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(400, 400); //Creating the MenuBar and adding components JMenuBar mb = new JMenuBar(); JMenu m1 = new JMenu("FILE"); JMenu m2 = new JMenu("Help"); mb.add(m1); mb.add(m2); JMenuItem m11 = new JMenuItem("Open"); JMenuItem m22 = new JMenuItem("Save as"); m1.add(m11); m1.add(m22); //Creating the panel at bottom and adding components JPanel panel = new JPanel(); // the panel is not visible in output JLabel label = new JLabel("Enter Text"); JTextField tf = new JTextField(10); // accepts upto 10 characters JButton send = new JButton("Send"); JButton reset = new JButton("Reset"); panel.add(label); // Components Added using Flow Layout panel.add(tf); panel.add(send); panel.add(reset); // Text Area at the Center JTextArea ta = new JTextArea(); //Adding Components to the frame. frame.getContentPane().add(BorderLayout.SOUTH, panel); frame.getContentPane().add(BorderLayout.NORTH, mb); frame.getContentPane().add(BorderLayout.CENTER, ta); frame.setVisible(true); } } JScrollBar Class It is used to add scroll bar, both horizontal and vertical. import javax.swing.*; class example{ example(){ JFrame a = new JFrame("example"); JScrollBar b = new JScrollBar(); b.setBounds(90,90,40,90); a.add(b); a.setSize(300,300); a.setLayout(null); a.setVisible(true); } public static void main(String args[]){ new example(); } } JList Class It inherits JComponent class, the object of JList class represents a list of text items. import javax.swing.*; public class Example { Example(){ JFrame a = new JFrame("example"); DefaultListModel<String> l = new DefaultListModel< >(); l.addElement("first item"); l.addElement("second item"); JList<String> b = new JList< >(l); b.setBounds(100,100,75,75); a.add(b); a.setSize(400,400); a.setVisible(true); a.setLayout(null); } public static void main(String args[]) { new Example(); } } JLabel Class It is used for placing text in a container. It also inherits JComponent class. import javax.swing.*; public class Example{ public static void main(String args[]) { JFrame a = new JFrame("example"); JLabel b1; b1 = new JLabel("edureka"); b1.setBounds(40,40,90,20); a.add(b1); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } } JComboBox Class It inherits the JComponent class and is used to show pop up menu of choices. import javax.swing.*; public class Example{ JFrame a; Example(){ a = new JFrame("example"); string courses[] = { "core java","advance java", "java servlet"}; JComboBox c = new JComboBox(courses); c.setBounds(40,40,90,20); a.add(c); a.setSize(400,400); a.setLayout(null); a.setVisible(true); } public static void main(String args[]) { new Example(); } } Result Program executed successfully and obtained the output Experiment 15 : GUI Programming in Java Theory Dialog Boxes for Input /Output A dialog box is a small graphical window that displays a message to the user or requests input. Two of the dialog boxes are: – Message Dialog - a dialog box that displays a message. Input Dialog - a dialog box that prompts the user for input. The ‘javax.swing.JOptionPane’ class offers dialog box methods. The following statement must be before the program’s class header: import javax.swing.JOptionPane; Input Dialog Syntax : <String variable> = JOptionPane.showInputDialog (<message> ) Reading Number Input The JOptionPane’s showInputDialog method always returns the user's input as a String. String containing a number, such as "15", can be converted to a numeric data type. The Parse Methods : Each of the numeric wrapper classes has a parse method that converts a string to a number. Aim Create a program illustrate the working of GUI based input output operations Program import javax.swing.JOptionPane; public class Main { public static void main(String[] args) { // obtain user input from JOptionPane input dialogs String firstNumber = JOptionPane.showInputDialog("Enter first integer"); String secondNumber = JOptionPane.showInputDialog("Enter second integer"); // convert String inputs to int values for use in a calculation int number1 = Integer.parseInt(firstNumber); int number2 = Integer.parseInt(secondNumber); int sum = number1 + number2; // add numbers // display result in a JOptionPane message dialog JOptionPane.showMessageDialog(null, "The sum is " + sum, "Sum of Two Int egers", JOptionPane.PLAIN_MESSAGE); } } Result Program executed successfully and obtained the output Experiment 15 : EVENT HANDLING IN JAVA . Theory An event can be defined as changing the state of an object or behavior by performing actions. Actions can be a button click, cursor movement, keypress through keyboard or page scrolling, etc. The java.awt.event package can be used to provide various event classes. Classification of Events Foreground Events- events that require user interaction to generate, i.e., foreground events are generated due to interaction by the user on components in Graphic User Interface (GUI). Interactions are nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc. Background Events- Events that don’t require interactions of users to generate are known as background events. Examples of these events are operating system failures/interrupts, operation completion, etc. Event Handling It is a mechanism to control the events and to decide what should happen after an event occur. Components of Event Handling 1. Events An event is an object that describes a phase change during a source. 2. Event Sources A source is an object that generates an occasion. 3. Event Listeners A listener is an object that’s notified when an occasion occurs.. The methods that receive and process events are defined in interfaces found in java.awt.event. Aim Write programs to illustrate the event handling in java. Program import java.awt.*; import java.awt.event.*; class EventHandling extends Frame implements ActionListener { TextField textField; EventHandling () { textField = new TextField (); textField.setBounds (60, 50, 170, 20); Button button = new Button ("Show"); button.setBounds (90, 140, 75, 40); button.addActionListener (this); add (button); add (textField); setSize (250, 250); setLayout (null); setVisible (true); } public void actionPerformed (ActionEvent e) { textField.setText ("Hello World"); } public static void main (String args[]) { new EventHandling (); } } Result Program executed successfully and obtained the output Experiment 16 : Listener interfaces in java . Theory Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Aim Write a program to illustrate listener interfaces in java Program import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Random; public class LearningAWT { public LearningAWT(){ // creating frame object Frame frame = new Frame("Scaler topics, presents"); // creating button object and setting the bounds of it // bounds are x,y cordinates in the container and // width,hieght of the button object Button mybtn = new Button("Click Me"); mybtn.setBounds(130,150,100,60); mybtn.setBackground(Color.red); // adding actionListner to the button // that will change the UI // once the button is clicked, as instructed mybtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Random rand = new Random(); float r = rand.nextFloat(); float g = rand.nextFloat(); float b = rand.nextFloat(); // choosing random background color for button after click mybtn.setBackground(new Color(r,g,b)); r = rand.nextFloat(); g = rand.nextFloat(); b = rand.nextFloat(); // choosing random text color for button after click mybtn.setForeground(new Color(r,g,b)); // updating button font mybtn.setFont(new Font("Arial", Font. BOLD, 18)); } }); // locating the button inside the frame and // setting the layout and size for the frame frame.add(mybtn); frame.setSize(300,300); frame.setLayout(null); frame.setVisible(true); // adding windowlistner to the frame // to make x button clickable. frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { frame.dispose(); } }); } public static void main(String[] args) { LearningAWT f = new LearningAWT(); } } Result Program executed successfully and obtained the output Experiment 17 : Establishing JDBC connection with SQL Theory JDBC (Java Database Connectivity) is the Java API that manages connecting to a database, issuing queries and commands, and handling result sets obtained from the database. Steps For Connectivity Between Java Program and Database 1. Import the Packages 2. Load the drivers using the forName() method 3. Register the drivers using DriverManager 4. Establish a connection using the Connection class object 5. Create a statement 6. Execute the query 7. Close the connections