0% found this document useful (0 votes)
25 views

Java Lab 1 To 9

Uploaded by

Syed Sameer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Java Lab 1 To 9

Uploaded by

Syed Sameer
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Exp: 1.

Displaying default value of all primitive data types

Aim: To write a JAVA program to display default value of all primitive data type of JAVA .

Description:

Primitive datatypes are predefined by the language and named by a keyword in Java.
Primitive types are the Java data types used for data manipulation, for example, int, char, float,
double, boolean, etc. The following are the some data types and their sizes:

Byte: An 8-bit signed two’s complement integer


Minimum Value: -128
Maximum Value: 127

Short: A 16-bit signed two’s complement integer


Minimum Value: -32768
Maximum Value: 32767

Int: A 32-bit signed two’s complement integer


Minimum Value: -2,147,483,648
Maximum Value: 2,147,483,647

Long: A 64-bit two’s complement integer


Minimum Value: -9,223,372,036,854,775,808
Maximum Value: 9,223,372,036,854,775,807

Char: A single 16-bit Unicode character.


Minimum Value: ‘\u0000’ (or 0)
Maximum value: ‘\uffff’

Float: A single-precision 32-bit IEEE 754 floating point


Minimum Value: 1.4E-45
Maximum Value: 3.4028235E38

Double: A double-precision 64-bit IEEE 754 floating point


Minimum Value: 4.9E-324
Maximum Value: 1.7976931348623157E308

Boolean: Possible values, TRUE and FALSE.


Program:

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("The default values of primitive data types are:");

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:

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

Result:

Hence, to display default value of all primitive data type of JAVA is executed
successfully.
EXP :1 b

Roots of a quadratic equation

Aim: To 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.

Description:

The roots of a function are the x-intercepts. By definition, the y-coordinate of points lying
on the x-axis is zero. Therefore, to find the roots of a quadratic function, we set f (x) = 0, and
solve the equation, ax2 + bx + c = 0.

Conditions for a quadratic equation –

ax^2 + bx + c = 0

where a, b, c are real numbers and cannot be zero ie, there value must be from {-∞ to -1} and {1
to ∞}

Program:

import java.util.*;

class quadraticdemo

public static void main(String[] args)

int a, b, c;

double r1, r2, D;

Scanner s = new Scanner(System.in);

System.out.println("Given quadratic equation:ax^2 + bx + c");

System.out.print("Enter a:");

a = s.nextInt();

System.out.print("Enter b:");
b = s.nextInt();

System.out.print("Enter c:");

c = s.nextInt();

D = b * b - 4 * a * c; if(D > 0)

System.out.println("Roots are real and unequal");

r1 = ( - b + Math.sqrt(D))/(2*a);

r2 = (-b - Math.sqrt(D))/(2*a);

System.out.println("First root is:"+r1);

System.out.println("Second root is:"+r2);

else if(D == 0)

System.out.println("Roots are real and equal");

r1 = (-b+Math.sqrt(D))/(2*a);

System.out.println("Root:"+r1);

else

System.out.println("Roots are imaginary");

OUTPUT:

Given quadratic equation:ax^2 + bx + c


Enter a:2

Enter b:3

Enter c:1

Roots are real and unequal First root is:-0.5

Second root is:-1.0

Result:

Hence, java program that display the roots of a quadratic equation ax2+bx=0, Calculated the
discriminate D and basing on value of D, described the nature of root is completed successfully.
EXPPERIMENT 2

A) Binary Search
Aim: To write a JAVA program to search for an element in a given list of elements using
binary search mechanism.
Description:
Binary Search mechanism is a searching mechanism used in a sorted array by repeatedly
dividing the search interval in half. The idea of binary search is to use the information that the
array is sorted and reduce the time complexity to O(log N). Binary search is a search
mechanism used to find the position of a target value within a sorted array. It works by
repeatedly dividing the search interval in half until the target value is found or the interval is
empty. The search interval is halved by comparing the target element with the middle value of
the search space. To apply Binary Search algorithm:
 The data structure must be sorted.
 Access to any element of the data structure should take constant time.

Program:
import java.util.Scanner;
class binarysearchdemo
{
public static void main(String args[])
{
int n, i, num,first, last, middle;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");
n = s.nextInt();
System.out.println("Enter elements in sorted order:");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
System.out.println("Enter the search value:");
num = s.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( a[middle] < num )
first = middle + 1;
else if ( a[middle] == num )
{
System.out.println("number found");
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if ( first > last )
System.out.println( " Number is not found");
}
}
Output:
Enter total number of elements: 5
Enter elements:
24689
Enter the search value: 8
number found

Result:
Hence, JAVA program to search for an element in a given list of elements using binary
search mechanism is executed successfully.
B) Bubble Sort
Aim: To write a JAVA program to sort for an element in a given list of elements using bubble
sort.
Description:

Bubble sort works on the repeatedly swapping of adjacent elements until they are not in
the intended order. It is not suitable for large data sets. The average and worst-case complexity of
Bubble sort is O(n2), where n is a number of items.

The algorithm steps are as follows:


 First, we will select the range of the unsorted array. For that, we will run a loop(say i)
that will signify the last index of the selected range. The loop will run backward from
index n-1 to 0(where n = size of the array). The value i = n-1 means the range is from 0 to
n-1, and similarly, i = n-2 means the range is from 0 to n-2, and so on.
 Within the loop, we will run another loop(say j, runs from 0 to i-1 though the range is
from 0 to i) to push the maximum element to the last index of the selected range, by
repeatedly swapping adjacent elements.
 Basically, we will swap adjacent elements(if a[j] > a[j+1]) until the maximum element of
the range reaches the end.
 Thus, after each iteration, the last part of the array will become sorted. Like: after the first
iteration, the array up to the last index will be sorted, and after the second iteration, the
array up to the second last index will be sorted, and so on.
 After (n-1) iteration, the whole array will be sorted.
Program:
import java.util.Scanner;
class bubbledemo
{
public static void main(String args[])
{
int n, i,j, temp;
int a[ ]=new int[20];
Scanner s = new Scanner(System.in);
System.out.println("Enter total number of elements:");
n = s.nextInt();
System.out.println("Enter elements:");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("The sorted elements are:");
for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
}
}
Output:
Enter total number of elements:
10
Enter elements:
3257689140
The sorted elements are:
0123456789
Result:
Hence, JAVA program to sort for an element in a given list of elements using bubble sort
is executed successfully.
C) StringBuffer
Aim:To write a JAVA program using StringBuffer to delete, remove character.
Description:
The java.lang.StringBuffer.delete() is an inbuilt method in Java which is used to remove
or delete the characters in a substring of this sequence. The substring starts at a specified index
start_point and extends to the character at the index end_point.

Syntax : public StringBuffer delete(int start_point, int end_point)

Parameters : The method accepts two parameters of integer type:


start_point – This refers to the beginning index and is included in the count.
end_point – This refer to the ending index and is excluded from the count.

Return Value : The method returns the string after deleting the substring formed by the range
mentioned in the parameters.

Program:
class stringbufferdemo
{
public static void main(String[] args)
{
StringBuffer sb1 = new StringBuffer("Hello World");
sb1.delete(0,6);
System.out.println(sb1);
StringBuffer sb2 = new StringBuffer("Some Content");
System.out.println(sb2);
sb2.delete(0, sb2.length());
System.out.println(sb2);
StringBuffer sb3 = new StringBuffer("Hello World");
sb3.deleteCharAt(0);
System.out.println(sb3);
}
}
Output:
World
Some Content

ello World

Result:
Hence, JAVA program using StringBuffer to delete, remove character is executed
successfully.
Experiments:3(a)

Class Mechanism

Aim: To write a JAVA program to implement class mechanism. – Create a class,


methods and invoke them inside main method.
Description:
In Java, classes and objects are basic concepts of Object Oriented Programming
(OOPs) that are used to represent real-world concepts and entities. The class
represents a group of objects having similar properties and behavior. A class in Java
is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. It is a user-defined blueprint or prototype from which objects
are created. For example, Student is a class while a particular student named Ravi is
an object.
Program:
1. no return type and without parameter-list:

class A
{
int l=10,b=20;
void display()
{
System.out.println(l);
System.out.println(b);
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display();
}
}
Output:
10
20
2. no return type and with parameter-list:
class A
{
void display(int l,int b)
{
System.out.println(l);
System.out.println(b);
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
a1.display(10,20);
}
}
Output:
10
20
3. return type and without parameter-list
class A
{
int l=10,b=20;
int area()
{
return l*b;
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area();
System.out.println("The area is: "+r);
}
}
Output:
The area is:200
4. return type and with parameter-list:
class A
{
int area(int l,int b)
{
return l*b;
}
}
class methoddemo
{
public static void main(String args[])
{
A a1=new A();
int r=a1.area(10,20);
System.out.println(“The area is:”+r);
}
}
Output:
The area is:200

Result:

Hence, a JAVA program to implement class mechanism. – Create a class, methods


and invoke them inside main method
Experiments:3(b)

Method Overloading

Aim: To write a JAVA program implement method overloading


Description:
In Java, Method Overloading allows a class to have multiple methods having same name but
different in parameters, it is known as Method Overloading.If we have to perform only one operation,
having same name of the methods increases the readability of the program.Suppose you have to
perform addition of the given numbers but there can be any number of arguments, if you write the
method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behavior of the method because its
name differs.So, we perform method overloading to figure out the program quickly.

Program:
class A
{
int l=10,b=20; int area()
{
return l*b;
}
int area(int l,int b)
{
return l*b;
}
}
class overmethoddemo
{
public static void main(String args[])
{
A a1=new A();
int r1=a1.area();
System.out.println("The area is: "+r1);
int r2=a1.area(5,20);
System.out.println("The area is: "+r2);
}
}
Output:
The area is: 200
The area is: 100

Result:

Hence, a JAVA program implement method overloading is executed successfully

Experiments:3(c)

Constructor

Aim: To write a JAVA to implement constructor .


Description:
In Java, a Constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling the constructor, memory for the object is
allocated in the memory. It is a special type of method that is used to initialize the object. Every
time an object is created using the new() keyword, at least one constructor is called. Unlike Java
methods, a constructor has the same name as that of the class and does not have any return type.

Program:
(i) A constructor with no parameters:

class A
{
int l,b;
A()
{ l=10; b=20;
}
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A(); int r=a1.area();
System.out.println("The area is: "+r);
}
}
Output:
The area is:200

(ii) A constructor with parameters


class A
{
int l,b;
A(int u,int v)
{
l=u; b=v;
}
int area()
{
return l*b;
}
}
class constructordemo
{
public static void main(String args[])
{
A a1=new A(10,20);
int r=a1.area(); System.out.println("The area is: "+r);
}
}
Output:
The area is:200

Result:

Hence, a JAVA to implement constructor is executed successfully.


Experiments:3(d)

Constructor Overloading

Aim: To write a JAVA program to implement constructor overloading .


Description:
Constructor overloading in Java refers to the practice of defining multiple constructors
within a class, each with a different set of parameters. These parameters can vary in terms of
their number, data types, and order. The purpose of constructor overloading is to provide
multiple ways to initialize objects in a class, catering to different scenarios and requirements.
In simple terms, when you overload constructors, you are creating multiple constructor methods
with distinct signatures in the same class. This allows you to create objects with different
initializations depending on the arguments provided during object creation.
It is a fundamental concept in object-oriented programming and is used to enhance code
flexibility and readability. It enables developers to create objects with varying attributes and
initial states without needing to write separate factory methods or use different constructors with
different names.

Program:
class A
{
int l,b;
A()
{ l=10; b=20;
}
A(int u,int v)
{
l=u; b=v;
}
int area()
{
return l*b;
}
}
class overconstructdemo
{
public static void main(String args[])
{
A a1=new A(); int r1=a1.area();
System.out.println("The area is: "+r1); A a2=new A(30,40);
int r2=a2.area(); System.out.println("The area is: "+r2);
}
}
Output:
The area is: 200 The area is: 1200

Result:

Hence, a JAVA program to implement constructor overloading is cpmoleted


successfully.
Experiment:4(a)

Implementing Single Inheritance

Aim: To write a JAVA program to implement Single Inheritance.

Description:

Inheritance in Java is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in Java is that we can create new classes that are built
upon existing classes. When we inherit from an existing class, we can reuse
methods and fields of the parent class. Moreover, we can add new methods and
fields in your current class also. The ’extends’ keyword is used for inheritance in
Java. Using the ‘extends’ keyword indicates you are derived from an existing
class.

In single inheritance, a sub-class is derived from only one super class. It inherits
the properties and behavior of a single-parent class

Program:
class A
{
A()
{
System.out.println("Inside A's Constructor");
}

}
class B extends A
{
B()
{
System.out.println("Inside B's Constructor");
}
}
class singledemo
{
public static void main(String args[])
{
B b1=new B();
}
}
Output:
Inside A's Constructor

Inside B's Constructor

Result:

Hence, the java program to implement Single Inheritance is executed successfully.


Experiment:4(b)

Implementing Multi Level Inheritance

Aim: To write a JAVA program to implement multi-level Inheritance.


Description:
The multi-level inheritance includes the involvement of at least two or more
than two classes. One class inherits the features from a parent class and the newly
created sub-class becomes the base class for another new class.

As the name suggests, in the multi-level inheritance the involvement of


multiple base classes is there. In the multilevel inheritance in java, the inherited
features are also from the multiple base classes as the newly derived class from the
parent class becomes the base class for another newly derived class.

Program:
class A
{
A()
{
System.out.println("Inside A's Constructor");
}
}
class B extends A
{
B()
{
System.out.println("Inside B's Constructor");
}
}
class C extends B
{
C()
{
System.out.println("Inside C's Constructor");
}
}
class multidemo
{
public static void main(String args[])
{

C c1=new C();
}
}
Output:
Inside A's Constructor

Inside B's Constructor

Inside C's Constructor

Result:

Hence, a JAVA program to implement multi-level Inheritance is completed


successfully.
Experiment:4(c)

Abstract Class

Aim: To write a java program for abstract class to find areas of different shapes.
Description:

A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery. Abstraction
lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.

An abstract class must be declared with an abstract keyword.

 It can have abstract and non-abstract methods.


 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the
body of the method.
Program:
abstract class shape
{
abstract double area();
}
class rectangle extends shape
{
double l=12.5,b=2.5;
double area()
{
return l*b;
}
}
class triangle extends shape
{
double b=4.2,h=6.5;
double area()
{
return 0.5*b*h;
}
}
class square extends shape
{
double s=6.5;
double area()
{
return 4*s;
}
}
class shapedemo
{
public static void main(String[] args)
{
rectangle r1=new rectangle();
triangle t1=new triangle();
square s1=new square();
System.out.println("The area of rectangle is: "+r1.area());
System.out.println("The area of triangle is: "+t1.area());
System.out.println("The area of square is: "+s1.area());
}
}
Output:
The area of rectangle is: 31.25

The area of triangle is: 13.65

The area of square is: 26.0

Result:

Hence, a java program for abstract class to find areas of different shapes is
executed successfully.
Experiment:5(a)

Super keyword implementation

Aim: Write a JAVA program give example for “super” keyword.

Description:

The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

The most common use of the super keyword is to eliminate the confusion between
super classes and subclasses that have methods with the same name.

Usage of Java super Keyword:

1. super can be used to refer immediate parent class instance variable:

This scenario occurs when a derived class and base class have the same data
members. In that case, there is a possibility of ambiguity

2. super can be used to invoke immediate parent class method:

This is used when we want to call the parent class method. So whenever a
parent and child class have the same-named methods then to resolve
ambiguity we use the super keyword.

3. super() can be used to invoke immediate parent class constructor:

The super keyword can also be used to access the parent class constructor.
One more important thing is that ‘super’ can call both parametric as well as
non-parametric constructors depending on the situation.

Advantages of Using Java Super Keyword:


 Enables reuse of code:
 Supports polymorphism
 Provides access to parent class behavior
 Allows for customization of behavior
 Facilitates abstraction and encapsulation:

Program:
(i) Using super to call super class constructor (Without parameters)

class A
{
int l,b;
A()
{
l=10;
b=20;
}
}
class B extends A
{
int h;
B()
{
super();
h=30;
}
int volume()
{
return l*b*h;
}
}
class superdemo
{
public static void main(String args[])
{
B b1=new B();
int r=b1.volume();
System.out.println("The vol. is: "+r);
}
}

Output:
The vol. is:6000
(ii) Using super to call super class constructor (With parameters)
class A
{
int l,b;
A(int u,int v)
{
l=u;
b=v;
}
}
class B extends A
{
int h;
B(int u,int v,int w)
{
super(u,v);
h=w;
}
int volume()
{
return l*b*h;
}
}
class superdemo
{
public static void main(String args[])
{
B b1=new B(30,20,30);
int r=b1.volume();
System.out.println("The vol. is: "+r);
}
}
Output:
The vol. is:18000

Result:
Thus, a JAVA program of given example for “super” keyword is executed
successfully.
Experiment:5(b)

Implementing Interface
Aim: To write a JAVA program to implement Interface.
Description:

An interface in Java is a blueprint of a class. It has static constants and abstract


methods.

The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritances in Java.

In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.

An interface is declared by using the interface keyword. It provides total


abstraction; means all the methods in an interface are declared with the empty
body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Program:
(i) First form of interface implementation

interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("B's method");
}
}
class C extends B
{
public void callme()
{
System.out.println("C's method");
}
}
class interfacedemo
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.callme();
}
}
Output:
B's method
C's method

(ii) Second form of interface implementation


interface D
{
void display();
}
interface E extends D
{
void show();
}
class A
{
void callme()
{
System.out.println("This is in callme method");
}
}
class B extends A implements E
{
public void display()
{
System.out.println("This is in display method");
}
public void show()
{
System.out.println("This is in show method");
}
}
class C extends B
{
void call()
{
System.out.println("This is in call method");
}
}
class interfacedemo
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.show();
c1.callme();
c1.call();
}
}
Output:
This is in display method
This is in show method
This is in callme method
This is in call method
(iii) Third form of interface implementation
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("This is in B's method");
}
}
class C implements A
{
public void display()
{
System.out.println("This is C's method");
}
}
class interfacedemo
{
public static void main(String args[])
{
B b1=new B();
C c1=new C();
b1.display();
c1.display();
}
}
Output:
This is in B's method
This is C's method
(iv) Fourth form of interface implementation
interface A
{
void display();
}
interface B
{
void callme();
}
interface C extends A,B
{
void call();
}
class D implements C
{
public void display()
{
System.out.println("interface A");
}
public void callme()
{
System.out.println("interface B");
}
public void call()
{
System.out.println("interface C");
}
}
class interfacedemo
{
public static void main(String args[])
{
D d1=new D();
d1.display();
d1.callme();
d1.call();
}
}
Output:
interface A
interface B
interface C

Result:
Thus, a JAVA program to implement Interface is completed successfully.
Experiment: 5(c)

Runtime Polymorphism
Aim: To write a JAVA program that implements Runtime polymorphism.
Description:

Polymorphism in Java is a concept by which we can perform a single action in


different ways. Polymorphism is derived from 2 Greek words: poly and morphs.
The word "poly" means many and "morphs" means forms. So polymorphism
means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and


runtime polymorphism. We can perform polymorphism in java by method
overloading and method overriding.

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call


to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.

Consider a scenario where Bank is a class that provides a method to get the rate of
interest. However, the rate of interest may differ according to banks. For example,
SBI, ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.

Program:
class A
{
void display()
{
System.out.println("Inside A class");
}
}
class B extends A
{
void display()
{
System.out.println("Inside B class");
}
}
class C extends A
{
void display()
{
System.out.println("Inside C class");
}
}
class runtimedemo
{
public static void main(String args[])
{
A a1=new A();
B b1=new B();
C c1=new C();
A ref;
ref=c1;
ref.display();
ref=b1;
ref.display();
ref=a1;
ref.display();
}
}
Output:
Inside C class
Inside B class
Inside A class
Result:
Thus, a JAVA program that implements Runtime polymorphism is executed
successfully.
Experiment 6(A)

Exception Handling Mechanism

Aim:

To write a JAVA program that describes exception handling mechanism


Description:

Exception Handling in Java is one of the effective means to handle runtime errors so that the
regular flow of the application can be preserved. Java Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal flow of the program’s instructions. Exceptions can be
caught and handled by the program. When an exception occurs within a method, it creates an object.
This object is called the exception object. It contains information about the exception, such as the name
and description of the exception and the state of the program when the exception occurred.

Error: An Error indicates a serious problem that a reasonable application should not try to catch.

Exception: Exception indicates conditions that a reasonable application might try to catch.

Java provides five keywords that are used to handle the exception. The following table describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by finally
block later.

finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
Program:

(i) using try and catch

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

(ii) using throw

class throwdemo
{
public static void main(String args[])
{
try
{
throw new NullPointerException("demo");
}
catch(NullPointerException e)
{
System.out.println(e);
}
}
}
Output:
java.lang.NullPointerException: demo

(iii) using finally

class finallydemo
{
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);
}
finally
{

System.out.println("This is inside finally block");


}
}
}
Output:
java.lang.ArithmeticException: / by zero This is inside finally block

(iv) using finally

class finallydemo
{
public static void main(String args[])
{
try
{
int a=10,b=5;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("This is inside finally block");
}
}
}
Output:
2
This is inside finally block

Result :

Hence , a JAVA program that describes exception handling mechanism is successfully completed
successfully.

Experiment 6(B)

Illustrating Multiple Catch Clauses

Aim:

To write a JAVA program Illustrating Multiple catch clauses.

Description:
Multiple catch blocks in Java are used to catch/handle multiple exceptions that may be thrown from a particular
code section. A try block can have multiple catch blocks to handle multiple exceptions.

Syntax:

try {

// Protected code

} catch (ExceptionType1 e1) {

// Catch block

} catch (ExceptionType2 e2) {

// Catch block

} catch (ExceptionType3 e3) {

// Catch block

 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must
come before catch for Exception.
Flowchart of Multi-catch Block:

Program:

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

Result:

Hence, to write a JAVA program Illustrating Multiple catch clauses is successfully executed.

Experiment 6(C)

Creation of Java Built-in-Exceptions

Aim:

To write a JAVA program for creation of Java Built-in Exceptions

Description:

Java defines several exception classes inside the standard package java.lang.

The most general of these exceptions are subclasses of the standard type RuntimeException.
Since java.lang is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.

Types of Java Built-in Exceptions

Built-in Exceptions in Java are categorized into two categories Checked Exceptions and Unchecked
Exceptions.

 Checked Exceptions: The checked exceptions are handled by the programmer during writing
the code, they can be handled using the try-catch block. These exceptions are checked at
compile-time.
 Unchecked Exceptions: The unchecked exceptions are not handled by the programmer. These
exceptions are thrown on run-time. Some of the unchecked exceptions are
NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc.

Types of Exceptions in Java Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations. Below is the list of important built-in
exceptions in Java.

Examples of Built-in Exception:

1. Arithmetic exception : It is thrown when an exceptional condition has occurred in an arithmetic


operation.
2.NullPointerException : This exception is raised when referring to the members of a null object. Null
represents nothing

3.StringIndexOutOfBoundsException : It is thrown by String class methods to indicate that an index


is either negative than the size of the string.

4.FileNotFoundException : This Exception is raised when a file is not accessible or does not open.

5. NumberFormatException : This exception is raised when a method could not convert a string into
a numeric format.

6. ArrayIndexOutOfBounds Exception: It is thrown to indicate that an array has been accessed with
an illegal index. The index is either negative or greater than or equal to the size of the array.

7.ClassNotFoundException : This Exception is raised when we try to access a class whose definition
is not found.

8. IOException : It is thrown when an input-output operation failed or interrupted.

9. InterruptedException : It is thrown when a thread is waiting, sleeping, or doing some processing,


and it is interrupted.

10. NoSuchMethodException : It is thrown when accessing a method which is not found.

Program:

(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);
}
}
}
Output:
java.lang.ArithmeticException: / by zero

(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);
}
}
}
Output:
java.lang.NullPointerException

(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);
}
}
}
Output:
java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified)

(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);
}
}
}
Output:
java.lang.NumberFormatException: For input string: "akki"

(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:
java.lang.ArrayIndexOutOfBoundsException: 6

Result:

Hence, to write a JAVA program for creation of Java Built-in Exceptions is executed successfully.
Experiment 6(D)

Creation of User Defined Exception

AIM:

To write a JAVA program for creation of User Defined Exception.

Description:

In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception. Basically, Java
custom exceptions are used to customize the exception according to user need.

Using the custom exception, we can have your own exception and message. Here, we have passed a
string to the constructor of superclass i.e. Exception class that can be obtained using getMessage()
method on the object we have created.

Custom exceptions provide several benefits over using only the predefined exceptions.

By creating custom exceptions, developers can:

Improve code readability: Custom exceptions can convey specific error conditions that are relevant to
the application domain. This improves the expressiveness and readability of the code.

Enhance error reporting: Custom exceptions can contain extra details that are unique to the error,
such as error codes, pertinent information, and contextual information. Better error reporting and
debugging are the results of this.

Separate business logic from exception handling: Developers may do just that by generating custom
exceptions, separating the application's business logic from the code that handles exceptions. The result
is cleaner, easier-to-maintain code.

Handle special cases: Using custom exceptions, developers can manage error scenarios unique to a
certain application and not covered by the standard exceptions.

Program:

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

Result:

Hence, to write a JAVA program for creation of User Defined Exception is completed successfully.
Experiment 7(a):

Extending Thread Class

Aim:

To 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)
Description:
Threads allows a program to operate more efficiently by doing multiple things at the
same time.

Threads can be used to perform complicated tasks in the background without interrupting
the main program.

There are two ways to create a thread.

It can be created by extending the Thread class and overriding its run() method

Thread creation by extending the Thread class:


We create a class that extends the java.lang.Thread class. This class overrides the run()
method available in the Thread class. A thread begins its life inside run() method. We
create an object of our new class and call start() method to start the execution of a thread.
Start() invokes the run() method on the Thread object.

Thread creation by implementing the Runnable Interface:

We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.

Program:

(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();
C c1=new C();
a1.start();
b1.start();
c1.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
welcomehello
welcome
welcome
welcome
welcome
(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 morning
good morning
hello
good morning
welcome good
morning hello
good morning good
morning welcome
hello
goodmorning
goodmorning
hello
good morning
welcome
good morning
hello
welcome hello
hello
welcome hello
welcome hello
hello
welcome
welcome
welcome
welcome
Result:
Hence, 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) is executed successfully.
Experiment 7(B):
is Alive and join ()
Aim:
To write a JAVA program illustrating is Alive and join ()
Description:
Thread class in java provides numerous methods that are very essential in order to
understand the working of threads as the thread stages are triggered by them. Java multi-
threading provides two ways to find with the help of isAlive() and join() method.
One thread gets to know when another thread has ended. Let us do depict stages of the
lifecycle of the thread via the below image which helps us to connect dots to understand
these methods’ workings.

isAlive() method works internally very closely in parallel to the lifecycle stages of a
thread. It tests if this thread is alive. A thread is alive if it has been started and has not yet
died. There is a transitional period from when a thread is running to when a thread is not
running.
After the run() method returns, there is a short period of time before the thread stops.

If we want to know if the start method of the thread class has been called or if the thread
has been terminated, we must use the isAlive() method. This method is used to find out if
a thread has actually been started and has yet not terminated.

Program:
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
Result:
Hence, a JAVA program illustrating is Alive and join () is successfully completed.
Experiment 7(C):
Daemon Threads
Aim:
To write a JAVA Program illustrating Daemon Threads.

Description:
In Java, daemon threads are low-priority threads that run in the background to perform
tasks such as garbage collection or provide services to user threads. The life of a daemon
thread depends on the mercy of user threads, meaning that when all user threads finish
their execution, the Java Virtual Machine (JVM) automatically terminates the daemon
thread.

To put it simply, daemon threads serve user threads by handling background tasks and
have no role other than supporting the main execution.

Example of Daemon Thread in Java:

Some examples of daemon threads in Java include garbage collection (gc) and finalizer.
These threads work silently in the background, performing tasks that support the main
execution without interfering with the user’s operations.

Program:
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
Result:
Hence, a JAVA Program illustrating Daemon Threads is successfully completed.
Experiment 7(D)

Producer Consumer Problem

Aim:

To write a JAVA program for Producer Consumer Problem.

Description:

The producer-consumer problem is a well-known synchronization issue in concurrent


programming that occurs when two threads, a producer and a consumer, share a fixed-
size buffer. The producer adds items to the buffer, while the consumer removes items
from the buffer. The challenge is to ensure that the producer doesn't add items when the
buffer is full, and the consumer doesn't remove items when the buffer is empty.

Here are some details about the producer-consumer problem in Java:

Buffer: The producer and consumer share a fixed-size memory buffer.

Access: The producer and consumer cannot access the buffer at the same time.

Waiting: If the buffer is empty, the consumer must wait for the producer to add an
item. If the buffer is full, the producer must wait for the consumer to remove an item.

Implementation: The producer-consumer problem can be implemented in Java using


threads or the BlockingQueue interface. The BlockingQueue interface is thread-safe,
allowing multiple threads to add and remove items from the queue without concurrency
issues.

Program:

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

Result:

Hence, a JAVA program for Producer Consumer Problem is executed successfully.


Exercise-8
User defined packages
(a)Write a java program that import and use the user defined packages.

AIM: To create a Java program that imports and utilizes user-defined packages for organized
code structure.
Description:
A package is a directory (or folder) that organizes related classes, interfaces, and subpackages
in Java.
Packages are divided into two categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)
(i) Creating a package:
To create a package, you choose a name for the package and put a package statement with
that name at the top of every source file that contains the types (classes, interfaces,
enumerations, and annotation types) that you want to include in the package.
The package statement (for example, package graphics;) must be the first line in the source
file. There can be only one package statement in each source file, and it applies to all types in
the file.
Steps:
1. First declare the name of the package using package keyword
Example: package mypack;
2. Type the following SOURCE-CODE under this package statement. In package : class
,data, methods all are public

package mypack;
public class box
{
public int l=10,b=20;
public void display()
{
System.out.println(l);
System.out.println(b);
}
}

To compile a Java file using the javac command, you use:


javac -d . filename.java

 Javac : The Java compiler command.


 -d . : This option specifies the destination directory for the compiled class files. The .
indicates the current directory, maintaining the package structure.
 filename.java: The name of the Java file you want to compile.

To run a compiled Java program


java <package_name>.<class_name>

 java: The command to run a Java application.


 <package_name>: The name of the package where the class is located.
 <class_name>: The name of the class you want to execute.
(ii) importing a package:

Java has an import statement that allows you to import an entire package (as in earlier
examples), or use only certain classes and interfaces defined in the package.
Steps:
1. packages can be accessed by using the import statement
General form: import pack1[.pack2].(classname/*);
Example: import java.io.*;
Here pack1 is name of top level package and pack2 is name of sub package
2. Type the following SOURCE-CODE under the current working directory and save the
SOURCE-CODE with a file name.java.

import mypack.box;
class packagedemo
{
public static void main(String args[])
{
box b1=new box();
b1.display();
}
}
3. Now compile the above SOURCE-CODE in the current working directory
javac packagedemo.java
4. Execute the above SOURCE-CODE in current working directory
java packagedemo

OUT-PUT:
10
20

Result:
The program successfully imported a user-defined package and displayed the message
b) Without writing any code, build a GUI that display text in label and image in an
image view.

AIM:
To create a JavaFX GUI that displays text in a label and an image in an image view.
Description:
A simple graphical user interface (GUI) using JavaFX, a powerful framework for creating
desktop applications in Java. The main goal is to display a welcoming message in a label and
show an image below it, providing a basic understanding of GUI components and layout
management in JavaFX.

Source Code:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;

public class SimpleGuiApp extends Application {

@Override
public void start(Stage primaryStage) {
// Create a Label
Label label = new Label("Welcome to JavaFX!");

// Create an ImageView
Image image = new Image("image.png"); // Adjust the path if necessary
ImageView imageView = new ImageView(image);

// Create a VBox layout


VBox vbox = new VBox(10); // 10px spacing
vbox.getChildren().addAll(label, imageView);

// Set up the Scene


Scene scene = new Scene(vbox, 300, 200);
primaryStage.setTitle("Simple JavaFX GUI");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}
OUTPUT:

Welcome to JavaFX!
[ Image Here ]

Result:
The program successfully displayed a welcome message in a label and an image in the image
view.
c) Build a tip Calculator app using several javafx components and learn how to
respond to user interactions with the GUI.

AIM:
To create a JavaFX tip calculator app that responds to user interactions for calculating tip
amounts based on bill and tip percentage inputs.
Description:
The Tip Calculator application is designed to provide users with a straightforward tool for
calculating the tip amount based on a specified bill and tip percentage. Built using JavaFX,
this application utilizes a graphical user interface (GUI) that enhances user experience
through interactive components.

SOURCE CODE:

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TipCalculator extends Application {

@Override
public void start(Stage primaryStage) {
// Create UI components
Label billLabel = new Label("Bill Amount:");
TextField billField = new TextField();

Label tipLabel = new Label("Tip Percentage:");


TextField tipField = new TextField();

Button calculateButton = new Button("Calculate Tip");


Label resultLabel = new Label();

// Set action for the button


calculateButton.setOnAction(e -> {
double billAmount = Double.parseDouble(billField.getText());
double tipPercentage = Double.parseDouble(tipField.getText());
double tipAmount = billAmount * (tipPercentage / 100);
resultLabel.setText("Tip Amount: $" + String.format("%.2f", tipAmount));
});

// Create layout and add components


GridPane gridPane = new GridPane();
gridPane.setPadding(new Insets(10));
gridPane.setVgap(8);
gridPane.setHgap(10);
gridPane.add(billLabel, 0, 0);
gridPane.add(billField, 1, 0);
gridPane.add(tipLabel, 0, 1);
gridPane.add(tipField, 1, 1);
gridPane.add(calculateButton, 0, 2);
gridPane.add(resultLabel, 1, 2);
// Create scene and set stage
Scene scene = new Scene(gridPane, 300, 200);
primaryStage.setTitle("Tip Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}

public static void main(String[] args) {


launch(args);
}
}

Output:

User Inputs:
o
Bill Amount: 50
o
Tip Percentage: 15
Tip Amount: $7.50

Result:
The Tip Calculator app successfully calculates and displays the tip amount based on user
input for the bill and tip percentage.
Exercise-9
A) Write a java program that connects to a database using JDBC program
AIM: To Write a java program that connects to a database using JDBC program
DESCRIPTION:
This Java program demonstrates how to establish a connection to a PostgreSQL database
using JDBC (Java Database Connectivity). The code imports essential packages like
java.sql.Connection and java.sql.DriverManager, which are part of the JDBC API. These
classes enable the program to interact with a database.
1. Database Connectivity: In this program, the main objective is to connect to a
PostgreSQL database. The Connection object is declared, which represents the active
connection to the database.
2. Loading the PostgreSQL Driver: The line Class.forName("org.postgresql.Driver")
loads the PostgreSQL JDBC driver dynamically, which is required to communicate
with the database. This ensures the driver class is registered before attempting the
connection.
3. Establishing the Connection: The DriverManager.getConnection() method is
invoked with three arguments: the JDBC URL
(jdbc:postgresql://localhost:5432/testdb), the username (postgres), and the password
(123). This method tries to connect to a PostgreSQL database named testdb running
locally on port 5432.
4. Error Handling: A try-catch block handles any exceptions that may occur during the
connection process. If an error occurs, the exception is printed, and the program exits.
5. Success Confirmation: If the connection is successful, the message "Opened
database successfully" is printed to the console, confirming the connection.

Source code:
import java.sql.Connection;
import java.sql.DriverManager;
public class PostgreSQLJDBC
{
public static void main(String args[])
{
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/testdb",
"postgres", "123");
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName()+": "+e.getMessage());
System.exit(0);
}
System.out.println("Opened database successfully");
}
}
OUTPUT:
Opened database successfully
RESULT:
Java program that connects to a database using JDBC program has been done successfully.
B) Write a java program to connect to database using JDBC & insert values into table

AIM: To write a java program to connect to database using JDBC & insert values into table
DESCRIPTION:
This Java program demonstrates how to insert data into an Oracle database using JDBC
(Java Database Connectivity). The program defines four string variables (id, pwd, fullname,
email) that hold the data to be inserted into a database table.
1. Database Driver Setup: The Class.forName("oracle.jdbc.driver.OracleDriver")
statement loads the Oracle JDBC driver, which is necessary for the Java application to
interact with the Oracle database. This ensures the driver is available before
establishing the connection.
2. Establishing the Connection: The DriverManager.getConnection() method is used to
establish a connection to the Oracle database. The method takes three arguments: the
JDBC URL (in this case, jdbc:oracle:thin:@localhost:1521:orcl), the username
(login1), and the password (pwd1). These details must match the database server
settings.
3. Creating and Executing SQL Statement: A Statement object is created using
con.createStatement(). Then, an SQL INSERT query is constructed, which includes
the data values defined earlier. The query is dynamically generated using the values
for id, pwd, fullname, and email.
4. Executing the Insert: The stmt.executeUpdate() method executes the INSERT query.
If the query is successful (i.e., data is inserted), it returns a value greater than 0, and
the program prints "Successfully Inserted". Otherwise, it prints "Insert Failed".
5. Error Handling and Closing Resources: A try-catch block handles any exceptions,
such as driver issues or connection failures. The connection is closed once the
operation is complete to release resources.

SOURCE CODE:

import java.sql.*;
public class insert1
{
public static void main(String args[])
{
String id = "id1";
String pwd = "pwd1";
String fullname = "MRCET";
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();
// Inserting data in database
String q1 = "insert into userid values('" +id+ "', '" +pwd+
"', '" +fullname+ "', '" +email+ "')";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("Successfully Inserted");
else
System.out.println("Insert Failed");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:
Successfully Inserted
After successful execution, the userid table in the Oracle database will contain a new
row with the following values:

RESULT:
Java program to connect to database using JDBC & insert values into table has been done
successfully.
C) Write a java program to connect to a database using JDBC and delete values from
table.

AIM: To write a java program to connect to a database using JDBC and delete values from
table.
DESCRIPTION:
This Java program demonstrates how to delete data from an Oracle database using
JDBC (Java Database Connectivity). The program focuses on deleting a specific user record
from the database based on matching id and pwd (password) fields.
Key Components of the Code:
1. Database Driver Setup: The line Class.forName("oracle.jdbc.driver.OracleDriver")
dynamically loads the Oracle JDBC driver, which is essential for enabling
communication between the Java program and the Oracle database.
2. Establishing the Connection: The program establishes a connection to the Oracle
database using the DriverManager.getConnection() method. It connects to the Oracle
instance running on localhost:1521, database identifier orcl, with the username login1
and password pwd1. These credentials must be correct for the connection to succeed.
3. Creating and Executing SQL Statement: A Statement object is created using
con.createStatement(), and the DELETE query is dynamically built. The query
attempts to delete a record from the userid table where both the id and pwd fields
match the values id2 and pwd2, respectively.
4. Executing the Deletion: The stmt.executeUpdate(q1) method executes the DELETE
query. If the query deletes a record, the value of x will be greater than 0, and the
program will print "One User Successfully Deleted". If no records match the criteria,
the message "ERROR OCCURED :(" is printed.
5. Error Handling and Closing Resources: The program uses a try-catch block to
handle any exceptions, such as invalid credentials or SQL syntax errors. After
execution, the connection is closed to free resources.

SOURCE CODE:
import java.sql.*;
public class delete
{
public static void main(String args[])
{
String id = "id2";
String pwd = "pwd2";
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("
jdbc:oracle:thin:@localhost:1521:orcl", "login1", "pwd1");
Statement stmt = con.createStatement();
// Deleting from database
String q1 = "DELETE from userid WHERE id = '" +
id + "' AND pwd = '" + pwd + "'";
int x = stmt.executeUpdate(q1);
if (x > 0)
System.out.println("One User Successfully Deleted");
else
System.out.println("ERROR OCCURED :(");
con.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

OUTPUT:

ERROR OCCURED :(

RESULT:
Java program to connect to a database using JDBC and delete values from table has been
done successfully.

You might also like