R23 Java Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 34

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING


(Artificial Intelligence & Machine Learning)

Object Oriented Programming through Java


Programming Laboratory
(23CS3029)
II B.Tech I Sem
(R23 Regulation)

LAB MANUAL
Prepared by

Mr. A Janardhana Rao


Assistant Professor

Pragati Engineering College


(Autonomous)
(Approved by AICTE, New Delhi & Affiliated to JNT University, Kakinada)
1-378, ADB Road, Surampalem – 533 437
INDEX
Exercis Page
e Program Name Number
Number
a) Write a JAVA program to display default value of all primitive data type of JAVA
1 b) Write a java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.
a) Write a JAVA program to search for an element in a given list of elements using
binary search mechanism.
2 b) Write a JAVA program to sort for an element in a given list of elements using bubble
sort
c) Write a JAVA program using StringBuffer to delete, remove character.
a) Write a JAVA program to implement class mechanism. Create a class, methods and
invoke them inside main method
b) Write a JAVA program implement method overloading
3
c) Write a JAVA program to implement constructor.
d)Write a JAVA program to implement constructor overloading.
a) Write a JAVA program to implement Single Inheritance
4 b) Write a JAVA program to implement multi level Inheritance
c) Write a JAVA program for abstract class to find areas of different shapes
a) Write a JAVA program give example for “super” keyword.
b) Write a JAVA program to implement Interface. What kind of Inheritance can be
5
achieved?
c) Write a JAVA program that implements Runtime polymorphism
a) Write a JAVA program that describes exception handling mechanism
b) Write a JAVA program Illustrating Multiple catch clauses
6
c) Write a JAVA program for creation of Java Built-in Exceptions
d) Write a JAVA program for creation of User Defined Exception
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)
7 b) Write a program illustrating is Alive and join ()
c) Write a Program illustrating Daemon Threads
d) Write a JAVA program Producer Consumer Problem
a) Write a JAVA program that import and use the user defined packages.
8
b) Without writing any code, build a GUI that display text in label and image in an
ImageView (use JavaFX) c) Build a Tip Calculator app using several JavaFX
components and learn how to respond to user interactions with the GUI.
a) Write a java program that connects to a database using JDBC.
9 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.
Exercise - 1
1 (a) Write a JAVA program to display default value of all primitive data types of JAVA
Ans:
class Test
{
int k;
double d;
float f;
boolean istrue;
String p;
void printValue()
{
System.out.println("int default value = "+ k);
System.out.println("double default value = "+ d);
System.out.println("float default value = "+ f);
System.out.println("boolean default value = "+ istrue);
System.out.println("String default value = "+ p);
}
public static void main(String argv[])
{
Test test = new Test();
test.printValue();
}
}
Output
int default value = 0
double default value = 0.0
float default value = 0.0
boolean default value = false
String default value = null
1 (b) Write a java program that display the roots of a quadratic equation ax2+bx=0.
Calculate the discriminate D and basing on value of D, describe the nature of root.
The formula to find the roots of the quadratic equation is known as the quadratic formula.

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.

//Java Program to find the roots of the quadratic equation


import java.util.Scanner;
public class QuadraticEquation
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
double a,b,c; //Quadratic Variables declaration
System.out.println("Enter the value of a..");
a=sc.nextDouble(); //Quadratic Variables Initialization
System.out.println("Enter the value of b..");
b=sc.nextDouble(); //Quadratic Variables Initialization
System.out.println("Enter the value of c..");
c=sc.nextDouble(); //Quadratic Variables Initialization
double d=(b*b)-(4*a*c); //Find the determinant
double D= Math.sqrt(d);
double r=2*a;
//Check for Roots
if(D>0)
{
System.out.println("Roots are real and unequal");
double root1=(D-b)/r;
double root2=(-D-b)/r;
System.out.println("Roots are..");
System.out.println(root1);
System.out.println(root2);
}
else if(D==0)
{
System.out.println("The roots of the quadratic equation are real and
equal.");
double root=(-b)/r;
System.out.println("Root is "+root);
}
else
{
System.out.println("The roots of the quadratic equation are complex
and different");
System.out.println("Roots are ");
System.out.println((-b/r)+" +i" + D);
System.out.println((-b/r)+" -i" + D);
}
}
}
Output
Enter the value of a.. 15
Enter the value of b.. 68
Enter the value of c.. 3
Roots are real and unequal Roots are..
-0.044555558333472335
-4.488777774999861
Exercise - 2
(a) Write a JAVA program to search for an element in a given list of elements using binary
search mechanism.
class BinarySearchExample
{
public static void binarySearch(int arr[], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if ( arr[mid] == key )
{
System.out.println("Element is found at index: " + mid); break;

}
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

2 (c) Write a JAVA program using StringBuffer to delete, remove character.


public class StringBufferDeleteExample1
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("javatpoint");
System.out.println("string1: " + sb);
// deleting the substring from index 2 to 6
sb = sb.delete(2,6);
System.out.println("After deleting: " + sb);
sb = new StringBuffer("let us learn java");
System.out.println("string2: " + sb);
// deleting the substring from index 0 to 7
sb = sb.delete(0, 7);
System.out.println("After deleting: " + sb);
}
}
Output
string1: Pragati
After deleting: Pri
string2: Welcome to PEC
After deleting: to PEC
Exercise - 3
a) Write a JAVA program to implement class mechanism. Create a class,
methods and invoke them inside main method.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// 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);
}
}
Output
Volume is 3000.0
Volume is 162.0
3 b) Write a JAVA program to implement constructor.
class Add
{
int a,b,total;
//creating a parameterized constructor
Add(int x,int y)
{
a=x;
b=y;
}
//method to display the values
void sum()
{
total=a+b;
System.out.println("Sum="+total);
}
public static void main(String args[])
{
//creating objects and passing values
Add obj1=new Add(20,30);
Add obj2=new Add(50,60);
Add obj3=new Add(100,200);
//calling method to display the values of object
obj1.sum();
obj2.sum();
obj3.sum();
}
}

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:

SBI Rate of Interest: 8.4


ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
Exercise - 6
6 (A) Write a JAVA program that describes exception handling mechanism
class Exception1
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero."+e);
}
System.out.println("After catch statement.");
}
}
Output
Division by zero.java.lang.ArithmeticException: / by zero
After catch statement.
6(B) Write a JAVA program Illustrating Multiple catch clauses
class MultipleCatches
{
public static void main(String args[])
{
tr
y
{ int a = 0;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;

}
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.

6 c) Write a JAVA program for creation of Java Built-in Exceptions


// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
tr
y
{ // "akki" is not a number
int num = Integer.parseInt("akki");
System.out.println(num);

}
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.*;

public class connect


{
public static void main(String args[])
{
try
{
Class.forName(&quot;oracle.jdbc.driver.OracleDriver&quot;);

// Establishing Connection
Connection con = DriverManager.getConnection(
&quot;jdbc:oracle:thin:@localhost:1521:orcl&quot;, &quot;login1&quot;,
&quot;pwd1&quot;);

if (con != null)
System.out.println(&quot;Connected&quot;);
else
System.out.println(&quot;Not Connected&quot;);
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.*;

public class insert1


{
public static void main(String args[])

Java Programming Lab Manual

{
String id = &quot;id1&quot;;
String pwd = &quot;pwd1&quot;;
String fullname = &quot;geeks for geeks&quot;;
String email = &quot;[email protected]&quot;;

try
{
Class.forName(&quot;oracle.jdbc.driver.OracleDriver&quot;);
Connection con = DriverManager.getConnection(&quot;
jdbc:oracle:thin:@localhost:1521:orcl&quot;, &quot;login1&quot;,
&quot;pwd1&quot;);
Statement stmt = con.createStatement();

// Inserting data in database


String q1 = &quot;insert into userid values(&#39;&quot; +id+ &quot;&#39;,
&#39;&quot; +pwd+
&quot;&#39;, &#39;&quot; +fullname+ &quot;&#39;, &#39;&quot;
+email+ &quot;&#39;)&quot;;
int x = stmt.executeUpdate(q1);
if (x &gt; 0)
System.out.println(&quot;Successfully Inserted&quot;);
else
System.out.println(&quot;Insert Failed&quot;);

String q2 = &quot;UPDATE userid set pwd = &#39;&quot; + newPwd +


&quot;&#39; WHERE id = &#39;&quot; +id+ &quot;&#39; AND pwd =
&#39;&quot; + pwd + &quot;&#39;&quot;;
int x = stmt.executeUpdate(q2);

if (x &gt; 0)
System.out.println(&quot;Password Successfully Updated&quot;);
else
System.out.println(&quot;ERROR OCCURRED :(&quot;);

String q3 = &quot;DELETE from userid WHERE id = &#39;&quot; + id +

&quot;&#39; AND pwd = &#39;&quot; + pwd + &quot;&#39;&quot;;

int x = stmt.executeUpdate(q3);

if (x &gt; 0)
System.out.println(&quot;One User Successfully Deleted&quot;);
else
System.out.println(&quot;ERROR OCCURRED :(&quot;);

String q4 = &quot;select * from userid WHERE id = &#39;&quot; + id +

&quot;&#39; AND pwd = &#39;&quot; + pwd + &quot;&#39;&quot;;


ResultSet rs = stmt.executeQuery(q4);
if (rs.next())

Java Programming Lab Manual

{
System.out.println(&quot;User-Id : &quot; + rs.getString(1));
System.out.println(&quot;Full Name :&quot; + rs.getString(3));
System.out.println(&quot;E-mail :&quot; + rs.getString(4));
}
else
{
System.out.println(&quot;No such user id is already registered&quot;);
}
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]

You might also like