R23 Java Lab Manual
R23 Java Lab Manual
R23 Java Lab Manual
LAB MANUAL
Prepared by
If d is positive (d>0), the root will be: If the value of d is positive, both roots are real and
different. It means there are two real solutions.
If d is zero (d=0), the root will be: If the value of d is zero, both roots are real and the same.
It means we get one real solution.
If d is negative (d<0), the root will be: If the value of d is negative, both roots are distinct
and imaginary or complex. It means that there are two complex solutions.
}
else
{ last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last )
{
System.out.println("Element is not found!");
}
}
public static void main(String args[])
{
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}
Output
Element is found at index: 2
2 (b) Write a JAVA program to sort for an element in a given list of elements using
bubble sort
public class BubbleSortExample
{
static void bubbleSort(int[] arr)
{
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(arr[j-1] > arr[j])
{
//swap
elements temp
= arr[j-1]; arr[j-
1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args)
{
int arr[] ={3,60,35,2,45,320,5};
System.out.println("Array Before Bubble Sort");
for(int i=0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
bubbleSort(arr);//sorting array elements using bubble sort
System.out.println("Array After Bubble Sort");
for(int i=0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
}
}
Output
Array Before Bubble Sort
3 60 35 2 45 320 5
Array After Bubble Sort
2 3 5 35 45 60 320
Output
Sum=50
Sum=110
Sum=300
3c) Write a JAVA program to implement constructor overloading.
/* Here, Box defines three constructors to initialize the dimensions of a box various ways. */
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions
specified Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{
return width * height * depth;
}
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
3d) Write a JAVA program implement method overloading.
// 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 parameter
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
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 parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Exercise - 4
4 (A) Write a JAVA program to implement Single Inheritance
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispA() method of ClassA
b.dispA();
//call dispB() method of ClassB
b.dispB();
}
}
Output
disp() method of ClassA
disp() method of ClassB
4 (B) Write a JAVA program to implement multi level Inheritance
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...
4(C) Write a java program for abstract class to find areas of different shapes
import java.lang.Math;
abstract class Shape
{
abstract void area();
double area;
}
class Triangle extends Shape
{
double b=50,h=15;
void area()
{
area = (b*h)/2;
System.out.println("area of Triangle -->"+area);
}
}
class Rectangle extends Shape
{
double w=70,h=20;
void area()
{
area = w*h;
System.out.println("area of Rectangle -->"+area);
}
}
class Circle extends Shape
{
double r=5;
void area()
{
area = Math.PI * r * r;
System.out.println("area of Circle -->"+area);
}
}
class Area
{
public static void main(String [] args)
{
Triangle t= new Triangle();
Rectangle r =new Rectangle();
Circle c =new Circle();
t.area();
r.area();
c.area();
}
}
Output:
area of Triangle 375.0
area of Rectangle 1400.0
area of Circle 78.53981633974483
Exercise - 5
5 (A) Write a JAVA program give example for “super” keyword.
Calling the Methods of the Superclass
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
Output
eating...
barking...
Accessing the Instance Member Variables of the Superclass
class Super_Variable
{
int b = 30; //instance Variable
}
class SubClass extends Super_Variable
{
int b = 12; // shadows the superclass variable
void show()
{
System.out.println("subclass class variable:" + b);
System.out.println("superclass instance variable:" + super.b);
}
public static void main (String args[])
{
SubClass s = new SubClass();
s.show(); // call to show method of Subclass B
}
}
Output
subclass class variable:12
superclass instance variable:30
5(B) Write a JAVA program to implement Interface. What kind of Inheritance can be
achieved?
interface Father
{
double HT=6.2; void height();
}
interface Mother
{
double HT=5.8; void color();
}
class Child implements Father, Mother
{
public void height()
{
double ht=(Father.HT+Mother.HT)/2;
System.out.println("Child's Height= "+ht);
}
public void color()
{
System.out.println("Child Color= brown");
}
public static void main(String[] args)
{
Child c=new Child(); c.height();
c.color();
}
}
Output
Child's Height= 6.0
Child Color= brown
)
5(c) Write a JAVA program that implements Runtime polymorphism
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
OUTPUT:
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
}
}
Output
a=0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
}
catch (NumberFormatException e)
{
System.out.println("Number format exception");
}
}
}
Output:
Number format exception
// Java program to demonstrate FileNotFoundException
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo
{
public static void main(String args[])
{
tr }
y
{
("E:// file.txt");
FileReader fr = new FileReader(file);
/
/
F
o
l
l
o
w
i
n
g
f
i
l
e
d
o
e
s
n
o
t
e
x
i
s
t
F
i
l
e
f
i
l
e
n
e
w
F
i
l
e
catch (FileNotFoundException e)
{
System.out.println("File does not exist");
}
}
}
Output:
File does not exist
9 d) Write a JAVA program for creation of User Defined Exception
class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class TestCustomException1
{
static void validate(int age)throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{
try
{
validate(13);
}
catch(Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code...");
}
}
Output:
Exception occured: InvalidAgeException: not valid
rest of the code...
Exercise – 7
7a) 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)
import java.io.*;
class One extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Good Morning");
}
}
}
class Two extends Thread
{
public void run()
{
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Hello ");
}
}
}
class Three implements Runnable
{
public void run()
{
for(int i=0;i<100;i++)
{
try
{
Thread.sleep(3000);
}
catch(InterruptedException e)
{
System.out.println(e);
}
System.out.println("Wel come");
}
}
}
class ThreadEx
{
public static void main(String[] args)
{
One t1=new One();
Two t2=new Two();
Three tt=new Three();
Thread t3=new Thread(tt);
t1.setName("One");
t2.setName("Two");
t3.setName("Three");
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
Thread t=Thread.currentThread();
System.out.println(t);
t1.start();t2.start();t3.start();
}
}
Output
Thread[One,5,main]
Thread[Two,5,main]
Thread[Three,5,main]
Thread[main,5,main]
Good Morning
Hello
Good Morning
Wel come
Good Morning
Hello
Good Morning
Good Morning
Hello
Wel come
Good Morning
Good Morning
Hello
Good Morning
Wel come
Good Morning
Hello
Good Morning
7 b) Write a program illustrating isAlive and join ()
// Using join() to wait for threads to finish.
class NewThread implements Runnable
{
String name; // name of thread
Thread t;
NewThread(String threadname)
{
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// 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.");
}
}
class DemoJoin
{
public static void main(String args[])
{
NewThread ob1 = new NewThread("One");
NewThread ob2 = new NewThread("Two");
NewThread ob3 = new
NewThread("Three");
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
// wait for threads to finish
try
{
System.out.println("Waiting for threads to finish.");
ob1.t.join();
ob2.t.join();
ob3.t.join();
}
catch (InterruptedException e)
{
System.out.println("Main thread Interrupted");
}
System.out.println("Thread One is alive: "+ ob1.t.isAlive());
System.out.println("Thread Two is alive: "+ ob2.t.isAlive());
System.out.println("Thread Three is alive: "+ ob3.t.isAlive());
System.out.println("Main thread exiting.");
}
}
Output
New thread: Thread[One,5,main]
New thread: Thread[Two,5,main]
New thread: Thread[Three,5,main]
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
One: 5
Two: 5
Three: 5
One: 4
Two: 4
Three: 4
One: 3
Three: 3
Two: 3
One: 2
Two: 2
Three: 2
One: 1
Three: 1
Two: 1
Two exiting.
Three exiting.
One exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
7c) Write a Program illustrating Daemon Threads.
public class TestDaemonThread1 extends Thread
{
public void run()
{
if(Thread.currentThread().isDaemon())
{//checking for daemon thread
System.out.println("daemon thread work");
}
else
{
System.out.println("user thread work");
}
}
public static void main(String[] args)
{
TestDaemonThread1 t1=new TestDaemonThread1();//creating thread
TestDaemonThread1 t2=new TestDaemonThread1();
TestDaemonThread1 t3=new TestDaemonThread1();
t1.setDaemon(true);//now t1 is daemon thread
t1.start();//starting threads
t2.start();
t3.start();
}
}
Output
daemon thread work
user thread work
user thread work
7D) Write a JAVA program Producer Consumer Problem
import java.util.*;
class Producer extends Thread
{
StringBuffer sb=new StringBuffer(); public void run()
{
synchronized(sb)
{
for(int i=1;i<=10;i++)
{
sb.append(i+" : "); System.out.println("Appending");
try
{
Thread.sleep(100);
}
catch(InterruptedException ie)
{}
}
sb.notify();
}
}
}
class Consumer extends Thread
{
Producer prod; Consumer(Producer prod)
{
this.prod=prod;
}
public void run()
{
synchronized(prod.sb)
{
try
{
prod.sb.wait();
}
catch(Exception e)
{}
System.out.println("Data is: "+prod.sb);
}
}
}
class Communciate
{
public static void main(String[] args)
{
Producer p=new Producer(); Consumer c=new Consumer(p); Thread t1=new
Thread(p); Thread t2=new Thread(c);
t2.start(); //Consumer thread will start first t1.start();
}
}
Output
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Appending
Data is: 1 : 2 : 3 : 4 : 5 : 6 : 7 : 8 : 9 : 10 :
Exercise – 8
8 (A) Write a JAVA program that import and use the user defined packages
package pack;
public class Addition
{
public void add(int a,int b)
{
int c=a+b;
System.out.println("The sum is "+c);
}
}
To compile the program by using following command,
javac -d . Addition.java
write program to import use Addition class of a package pack.
import pack.Addition; class DemoPack
{
public static void main(String[] args)
{
Addition a1=new Addition(); a1.add(15,27);
}
}
Output:
java DemoPack
The Sum is 42
8(B) Without writing any code, build a GUI that display text in label and image in an
ImageView (use JavaFX)
8(C) Build a Tip Calculator app using several JavaFX components and learn how to
respond to user interactions with the GUI.
Exercise – 9 a) Write a java program that connects to a database using JDBC
import java.sql.*;
// Establishing Connection
Connection con = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl", "login1",
"pwd1");
if (con != null)
System.out.println("Connected");
else
System.out.println("Not Connected");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Connected.
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
Program for (b) & (c)
import java.sql.*;
{
String id = "id1";
String pwd = "pwd1";
String fullname = "geeks for geeks";
String email = "[email protected]";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1",
"pwd1");
Statement stmt = con.createStatement();
if (x > 0)
System.out.println("Password Successfully Updated");
else
System.out.println("ERROR OCCURRED :(");
int x = stmt.executeUpdate(q3);
if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURRED :(");
{
System.out.println("User-Id : " + rs.getString(1));
System.out.println("Full Name :" + rs.getString(3));
System.out.println("E-mail :" + rs.getString(4));
}
else
{
System.out.println("No such user id is already registered");
}
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Successfully Registered
Password Successfully Updated
One User Successfully Deleted
User-Id : 1
Full Name : Rajesh
E-mail : [email protected]