Swarnandhra College of Engineering and Technology
B.Tech-CSE | R23 | Academic Year: 2024-2025
Lab Course: 23CS4L02 - OOP Through Java Lab
Department | CSE |
---|---|
Programme Name | B.Tech-CSE |
Regulation | R23 |
Academic Year | 2024-2025 |
Lab Course Code | 23CS4L02 |
Lab Course Name | OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB |
Exercises
- Exercise – 1: a) Default Values in JAVA b) Quadratic Equation Roots
- Exercise – 2: a) StringBuffer Manipulation b) Implementing Class Mechanism
- Exercise – 3: a) Method Overloading b) Implementing Constructors c) Constructor Overloading
- Exercise – 4: a) Single Inheritance b) Multi-Level Inheritance c) Abstract Class for Shapes
- Exercise – 5: a) Using "super" Keyword b) Implementing Interfaces c) Runtime Polymorphism
- Exercise – 6: a) Exception Handling b) Multiple Catch Clauses c) Java Built-in Exceptions d) User Defined Exceptions
- Exercise – 7: a) Creating Threads b) isAlive and join() Methods c) Daemon Threads d) Write a JAVA program Producer Consumer Problem
- Exercise – 8: a) JDBC Connection b) JDBC Insert Operation c) JDBC Delete Operation
Exercise 1
- a) Default values of all primitive types
- b) Roots of quadratic equation
Exercise 2
- a) StringBuffer operations
- b) Class mechanism
Exercise 3
- a) Write a JAVA program implements method overloading.
- b) Write a JAVA program to implement constructor
- c) Write a JAVA program to implement constructor overloading.
Exercise 4
- a) Write a JAVA program to implement Single Inheritance
- b) Write a JAVA program to implement multi level Inheritance
- c) Write a JAVA program for abstract class to find areas of different shapes
Exercise 5
- a) Write a JAVA program give example for “super” keyword
- b) Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
- c) Write a JAVA program that implements Runtime polymorphism
Exercise 6
- a) Write a JAVA program that describes exception handling mechanism
- b) Write a JAVA program Illustrating Multiple catch clauses
- c) Write a JAVA program for creation of Java Built-in Exceptions
- d) Write a JAVA program for creation of User Defined Exception
Exercise 7
- a) Write a JAVA program that creates threads by extending Thread class. First thread display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome” every 3 seconds, (Repeat the same by implementing Runnable)
- b) Write a program illustrating is Alive and join ()
- c) Write a Program illustrating Daemon Threads.
- d) Write a JAVA program Producer Consumer Problem
Exercise 8
- a) Write a java program that connects to a database using JDBC.
- b) Write a java program to connect to a database using JDBC and insert values into it. ()
- c) Write a java program to connect to a database using JDBC and delete values from it.
Source Code: Default values of all primitive types
class DefaultDemo { static byte b; static short s; static int i; static long l; static float f; static double d; static char c; static boolean bl; public static void main(String[] args) { System.out.println("Default values of primitive data types:"); System.out.println("Byte: " + b); System.out.println("Short: " + s); System.out.println("Int :"+i); System.out.println("Long :"+l); System.out.println("Float :"+f); System.out.println("Double :"+d); System.out.println("Char :"+c); System.out.println("Boolean :"+bl); } }
Output:
Output will be displayed here. OUT-PUT: The default values of primitive data types are: Byte :0 Short :0 Int :0 Long :0 Float :0.0 Double :0.0 Char : Boolean :false
Source Code: Roots of Quadratic Equation
import java.util.Scanner; public class QuadraticEquation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a: "); double a = scanner.nextDouble(); System.out.print("Enter b: "); double b = scanner.nextDouble(); System.out.print("Enter c: "); double c = scanner.nextDouble(); double discriminant = b * b - 4 * a * c; if (discriminant > 0) { // Two real roots } else if (discriminant == 0) { // One real root } else { // Complex roots } } }
Output:
Output will be displayed here.
Source Code: example for “super” keyword
class A { int i, j; A() { i = 0; j = 0; } A(int a, int b) { i = a; j = b ; } void show() { System.out.println ("i and j : "+ i +" " + j); } } class B extends A { int k; B() { super(); k = 0; } B(int a, int b, int c) { super(a, b); k =c; } void show() { super.show(); System.out.println("k:" + k); } } class SuperKeyword { public static void main ( String args[]) { B subob = new B( 1, 2, 3 ); subob.show(); } }
Output:
Output will be displayed here.
Source Code: b) Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
class Number { protected int x; protected int y; } interface Arithmetic { int add(int a, int b); int sub(int a, int b); } class UseInterface extends Number implements Arithmetic { public int add(int a, int b) { return(a + b); } public int sub(int a, int b) { return (a - b); } public static void main(String args[]) { UseInterface ui = new UseInterface(); System.out.println("Addition --- >" + ui.add(2,3)); System.out.println("Subtraction ----- >" + ui.sub(2,1)); } }
Output:
Output will be displayed here.
Source Code: c) Implementation Runtime Polymorphism
import java.io.*; class Override { public void methodoverride() { System.out.println("This is base class Method"); } } class Overridederived extends Override { public void methodoverride() { System.out.println("This is Derived class Method"); } } public class Methodoverride { public static void main(String args[]) throws IOException { Override ob=new Override(); Override ob1=new Overridederived(); ob.methodoverride(); ob1.methodoverride(); } }
Output:
Output will be displayed here.
Exercise 6.a) Write a JAVA program that describes exception handling mechanism Source Code: Exception handling mechanism
SOURCE-CODE: Usage of Exception Handling: class trydemo { public static void main(String args[]) { try { int a=10,b=0; int c=a/b; System.out.println(c); } catch(ArithmeticException e) { System.out.println(e); } System.out.println("After the catch statement"); } }
Output:
java.lang.ArithmeticException: / by zero After the catch statement
Exercise 6. b) Write a JAVA program Illustrating Multiple catch clauses Source Code:
class multitrydemo { public static void main(String args[]) { try { int a=10,b=5; int c=a/b; int d[]={0,1}; System.out.println(d[10]); System.out.println(c); } catch(ArithmeticException e) { System.out.println(e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("After the catch statement"); } }
Output:
java.lang.ArrayIndexOutOfBoundsException: 10 After the catch statement
Exercise 6.c) Write a JAVA program for creation of Java Built-in Exceptions Source Code:
(i) Arithmetic exception class arithmeticdemo { public static void main(String args[]) { try { int a = 10, b = 0; int c = a/b; System.out.println (c); } catch(ArithmeticException e) { System.out.println (e); } } } (ii) NullPointer Exception class nullpointerdemo { public static void main(String args[]) { try { String a = null; System.out.println(a.charAt(0)); } catch(NullPointerException e) { System.out.println(e); } } } (iii) StringIndexOutOfBound Exception class stringbounddemo { public static void main(String args[]) { try { String a = "This is like chipping "; char c = a.charAt(24); System.out.println(c); } catch(StringIndexOutOfBoundsException e) { System.out.println(e); } } } (iv) FileNotFound Exception import java.io.*; class filenotfounddemo { public static void main(String args[]) { try { File file = new File("E://file.txt"); FileReader fr = new FileReader(file); } catch (FileNotFoundException e) { System.out.println(e); } } } (v) NumberFormat Exception class numberformatdemo { public static void main(String args[]) { try { int num = Integer.parseInt ("akki") ; System.out.println(num); } catch(NumberFormatException e) { System.out.println(e); } } } (vi) ArrayIndexOutOfBounds Exception class arraybounddemo { public static void main(String args[]) { try { int a[] = new int[5]; a[6] = 9; } catch(ArrayIndexOutOfBoundsException e) { System.out.println (e); } } }
Output:
(i) Arithmetic exception java.lang.ArithmeticException: / by zero ________________________________________ (ii) NullPointer Exception java.lang.NullPointerException ________________________________________ (iii) StringIndexOutOfBound Exception java.lang.StringIndexOutOfBoundsException: String index out of range: 24 ________________________________________ (iv) FileNotFound Exception java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified) ________________________________________ (v) NumberFormat Exception java.lang.NumberFormatException: For input string: "akki" ________________________________________ (vi) ArrayIndexOutOfBounds Exception java.lang.ArrayIndexOutOfBoundsException: 6
Exercise 6. d) Write a JAVA program for creation of User Defined Exception Source Code:
class A extends Exception { A(String s1) { super(s1); } } class owndemo { public static void main(String args[]) { try { throw new A("demo "); } catch(Exception e) { System.out.println(e); } } }
Output:
A: demo
Source Code: Write a JAVA program that creates threads by extending Thread class. First thread display “Good Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome” every 3 seconds,(Repeat the same by implementing Runnable)
SOURCE-CODEs: (i) Creating multiple threads using Thread class class A extends Thread { public void run() { try { for(int i=1;i<=10;i++) { sleep(1000); System.out.println("good morning"); } } catch(Exception e) { System.out.println(e); } } } class B extends Thread { public void run() { try { for(int j=1;j<=10;j++) { sleep(2000); System.out.println("hello"); } } catch(Exception e) { System.out.println(e); } } } class C extends Thread { public void run() { try { for(int k=1;k<=10;k++) { sleep(3000); System.out.println("welcome"); } } catch(Exception e) { System.out.println(e); } } } class threaddemo { public static void main(String args[]) { A a1=new A(); B b1=new B(); Cc1=newC(); a1.start(); b1.start(); c1.start(); } } __________________________________________ (ii) Creating multiple threads using Runnable interface class A implements Runnable { public void run() { try { for(int i=1;i<=10;i++) { Thread.sleep(1000); System.out.println("good morning"); } } catch(Exception e) { System.out.println(e); } } } class B implements Runnable { public void run() { try { for(int j=1;j<=10;j++) { Thread.sleep(2000); System.out.println("hello"); } } catch(Exception e) { System.out.println(e); } } } class C implements Runnable { public void run() { try { for(int k=1;k<=10;k++) { Thread.sleep(3000); System.out.println("welcome"); } } catch(Exception e) { System.out.println(e); } } } class runnabledemo { public static void main(String args[]) { A a1=new A(); B b1=new B(); C c1=new C(); Thread t1=new Thread(a1); Thread t2=new Thread(b1); Thread t3=new Thread(c1); t1.start(); t2.start(); t3.start(); } }
Output:
good morninghello good morninggood morningwelcome hello good morning good morning hello good morning welcome good morninghello good morninggood morningwelcome hello good morninghello welcome hello welcome hello hello welcome hello welcome welcome welcome welcome ___________________________________________________ good morning good morning hello good morning welcome good morninghello good morninggood morningwelcome hello goodmorning goodmorning hello good morning welcome good morning hello welcome hello hello welcome hello welcome hello hello welcome welcome welcome welcome
Source Code: b) Write a program illustrating is Alive and join ()
Implementing isAlive() and join() AIM: To write a program illustrating isAlive and join () SOURCE-CODE: class A extends Thread { public void run() { try { for(int i=1;i<=10;i++) { sleep(1000); System.out.println("good morning"); } } catch(Exception e) { System.out.println(e); } } } class B extends Thread { public void run() { try { for(int j=1;j<=10;j++) { sleep(2000); System.out.println("hello"); } } catch(Exception e) { System.out.println(e); } } } class C extends Thread { public void run() { try { for(int k=1;k<=10;k++) { sleep(3000); System.out.println("welcome"); } } catch(Exception e) { System.out.println(e); } } } class isalivedemo { public static void main(String args[]) { A a1=new A(); B b1=new B(); C c1=new C(); a1.start(); b1.start(); c1.start(); System.out.println(a1.isAlive()); System.out.println(b1.isAlive()); System.out.println(c1.isAlive()); try { a1.join(); b1.join(); c1.join(); } catch(InterruptedException e) { System.out.println(e); } System.out.println(a1.isAlive()); System.out.println(b1.isAlive()); System.out.println(c1.isAlive()); } }
Output:
true good morning true hello true welcome good morning hello good morning hello hello welcome good morning hello welcome welcome good morning hello hello hello good morning welcome good morning welcome welcome welcome hello welcome good morning false good morning false hello false good morning welcome
Source Code: c) Implementation of Daemon Threads
AIM: To write a program illustrating Daemon Threads SOURCE-CODE: class A extends Thread { public void run() { if(Thread.currentThread().isDaemon()) System.out.println("daemon thread work");else System.out.println("user thread work"); } } class daemondemo { public static void main(String[] args) { A a1=new A(); A a2=new A(); A a3=new A(); a1.setDaemon(true); a1.start(); a2.start(); a3.start(); } }
Output:
daemon thread work user thread work user thread work
Source Code: d) Producer-Consumer problem
AIM: Write a JAVA program Producer Consumer Problem SOURCE-CODE: class A { int n; boolean b=false; synchronized int get() { if(!b) try { wait(); } catch(Exception e) { System.out.println(e); } System.out.println("Got:"+n); b=false; notify(); return n; } synchronized void put(int n) { if(b) try { wait(); } catch(Exception e) { System.out.println(e); } this.n=n; b=true; System.out.println("Put:"+n); notify(); } } class producer implements Runnable { A a1; Thread t1; producer(A a1) { this.a1=a1; t1=new Thread(this); t1.start(); } public void run() { for(int i=1;i<=10;i++) { a1.put(i); } } } class consumer implements Runnable { A a1; Thread t1; consumer(A a1) { this.a1=a1; t1=new Thread(this); t1.start(); } public void run() { for(int j=1;j<=10;j++) { a1.get(); } } } class interdemo { public static void main(String args[]) { A a1=new A(); producer p1=new producer(a1); consumer c1=new consumer(a1); } }
Output:
Put:1 Got:1 Put:2 Got:2 Put:3 Got:3 Put:4 Got:4 Put:5 Got:5 Put:6 Got:6 Put:7 Got:7 Put:8 Got:8 Put:9 Got:9 Put:10 Got:10
Source Code: a) Write a java program that connects to a database using JDBC
SOURCE-CODEs: import java.sql.*; public class MySQLJDBCExample { public static void main(String[] args) { // MySQL database URL, username, and password String url = "jdbc:mysql://localhost:3306/mysql"; // change to your DB String user = "root"; // your MySQL username String password = "manager"; // your MySQL password // SQL query String query = "SELECT * FROM student"; // change to your query // Initialize connection, statement, and result set Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // Step 1: Register the JDBC driver (optional in newer versions) // Class.forName("com.mysql.cj.jdbc.Driver"); // Step 2: Open a connection conn = DriverManager.getConnection(url, user, password); // Step 3: Create a statement stmt = conn.createStatement(); // Step 4: Execute the query rs = stmt.executeQuery(query); // Step 5: Process the result set while (rs.next()) { String roll_no = rs.getString("roll_no"); // Assuming column 'id' exists String name = rs.getString("sName"); // Assuming column 'name' exists int age=rs.getInt(3); System.out.println("roll_no: " + roll_no + ", Name: " + name+" ,Age:"+age); } } catch (Exception e) { e.printStackTrace(); } finally { // Step 6: Close the resources try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }
Output:
roll_no: r001, Name: rahul bose ,Age:23 roll_no: r002, Name: sanjay sahoo ,Age:25 roll_no: r003, Name: sourav ganguly ,Age:26
Source Code: b) Write a java program to connect to a database using JDBC and insert values into it. ()
Implementing isAlive() and join() AIM: To write a program illustrating isAlive and join () SOURCE-CODE: import java.sql.*; public class MySQLJDBCExample2 { public static void main(String[] args) { // MySQL database URL, username, and password String url = "jdbc:mysql://localhost:3306/mysql"; // change to your DB String user = "root"; // your MySQL username String password = "manager"; // your MySQL password // SQL query String query = "insert into student values ('r004','Raju',28)"; // change to your query // Initialize connection, statement, and result set Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // Step 1: Register the JDBC driver (optional in newer versions) // Class.forName("com.mysql.cj.jdbc.Driver"); // Step 2: Open a connection conn = DriverManager.getConnection(url, user, password); // Step 3: Create a statement stmt = conn.createStatement(); // Step 4: Execute the query int row = stmt.executeUpdate(query); // Step 5: Process the result set /* while (rs.next()) { String roll_no = rs.getString("roll_no"); // Assuming column 'id' exists String name = rs.getString("sName"); // Assuming column 'name' exists int age=rs.getInt(3); System.out.println("roll_no: " + roll_no + ", Name: " + name+" ,Age:"+age); }*/ if( row==1) System.out.println("Successfully Inserted"); } catch (Exception e) { e.printStackTrace(); } finally { // Step 6: Close the resources try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }
Output:
Successfully Inserted
Source Code: c) Write a java program to connect to a database using JDBC and delete values from it
AIM: To write a program illustrating Daemon Threads SOURCE-CODE: import java.sql.*; public class MySQLJDBCExample3 { public static void main(String[] args) { // MySQL database URL, username, and password String url = "jdbc:mysql://localhost:3306/mysql"; // change to your DB String user = "root"; // your MySQL username String password = "manager"; // your MySQL password // SQL query String query = "delete from student where roll_no='r004'"; // change to your query // Initialize connection, statement, and result set Connection conn = null; Statement stmt = null; ResultSet rs = null; try { // Step 1: Register the JDBC driver (optional in newer versions) // Class.forName("com.mysql.cj.jdbc.Driver"); // Step 2: Open a connection conn = DriverManager.getConnection(url, user, password); // Step 3: Create a statement stmt = conn.createStatement(); // Step 4: Execute the query int row = stmt.executeUpdate(query); // Step 5: Process the result set /* while (rs.next()) { String roll_no = rs.getString("roll_no"); // Assuming column 'id' exists String name = rs.getString("sName"); // Assuming column 'name' exists int age=rs.getInt(3); System.out.println("roll_no: " + roll_no + ", Name: " + name+" ,Age:"+age); }*/ if( row==1) System.out.println("Successfully Deleted"); } catch (Exception e) { e.printStackTrace(); } finally { // Step 6: Close the resources try { if (rs != null) rs.close(); if (stmt != null) stmt.close(); if (conn != null) conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }
Output:
Successfully Deleted