0% found this document useful (0 votes)
2 views50 pages

Java Lab Manual

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

Java Lab Manual

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

SAMPLE EXPERIMENTS

Exercise – 1
1 a) Write a JAVA program to display default value of all primitive data type of JAVA
Aim: To Write a JAVA program to display default values of all primitive data types in JAVA.
Description:. Declare a variable with the specific datatype and display the value. This gives the default value. Do not
assign a value to the variable, since we need the default.However, first we should learn what is primitive datatype in Java.
Primitive types are the Java data types used for data manipulation, for example, int, char, float, double, boolean, etc

Source Code:
class Default
{
static boolean b;
static byte by;
static short s;
static int i;
static long li;
static char c;
static float f;
static double d;
static String str;
public static void main (String args[])
{
System.out.println("Boolean="+b);
System.out.println("Byte="+by);
System.out.println("Short="+s);
System.out.println("Int="+i);
System.out.println("Long="+li);
System.out.println("Char="+c);
System.out.println("Float="+f);
System.out.println("Double="+d);
System.out.println("String="+str);
}
}

Output:
D:\DNRCET>javac Default.java
D:\DNRCET>java Default
Boolean=false
Byte=0
Short=0
Int=0
Long=0
Char=
Float=0.0
Double=0.0
String=null

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 1


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.
Aim: 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 standard form of a quadratic equation is ax2+bx+c=0. The formula to find the roots of the quadratic
equation is known as the quadratic formula.

(√b2-4ac) is called discriminant (d).

* If d is zero (d>0) roots are real and different(distinct)

* If d is zero (d=0) roots are real and the same

*If d is negative (d<0) roots are distinct and imaginary

Algorithm :

Step 1: Start

Step 2: Read a, b, c

Step 3: initialize d<-(b*b)-(4*a*c)

Step 4: initialize r<- b/2*a

Step 5: if d>0 go to Step 6, else go to Step 8

Step 6: r1=r+(sqrt(d)/2*a) and r2=r-(sqrt(d)/2*a)

Step 7: prints roots are real and distinct, first root r1 second root r2

Step 8: if d=0 go to Step 9, else go to Step 10

Step 9: print roots are real and equal, -r

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 2


Step 10: d=-d

Step 11: im=sqrt(d)/2*a

Step 12: print roots are imaginary, first root is r+i im, and the second root is r-i im

Step 13: Stop.

Source Code:

import java.io.*;
class Roots
{
public static void main(String args[]) throws IOException
{
int a,b,c,d;
double r1,r2;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter a,b and c values");
a=Integer.parseInt(dis.readLine());
b=Integer.parseInt(dis.readLine());
c=Integer.parseInt(dis.readLine());
d=b*b-4*a*c;
if(d==0)
{
r1=r2=(double)-b/(2*a);
System.out.println("Root1 is "+r1+" Root2 is "+r2);
}
else if(d>0)
{
r1=(-b+Math.sqrt(d))/(2*a);
r2=(-b-Math.sqrt(d))/(2*a);
System.out.println("Root1 is "+r1+" Root2 is "+r2);
}
else
{
System.out.println("Roots are imaginary");
}
}
}

Output:

D:\DNRCET>javac Rots.java
D:\DNRCET>java Roots
Enter a,b and c values
9
1
5
Roots are imaginary

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 3


Exercise – 2
2 a). Write a JAVA program to search for an element in a given list of elements using binary
Search mechanism.

Aim: To Write a JAVA program to search for an element in a given list of elements using binary
Search mechanism.
Description:. The Binary Search Algorithm is an efficient searching algorithm that uses the divide and conquer method to
search for an element in a sorted array or list. It is one of the most popular searching algorithms. It is more efficient than
linear search algorithms.
Algorithm:
Step 1: .Start
Step 2: Take input array and Target
Step 3: .Initialise start = 0 and end = (array size -1)
Step 4: .Intialise mid variable
Step 5: .mid = (start+end)/2
Step 6: .if array[ mid ] == target then return mid
Step 7: .if array[ mid ] < target then start = mid+1
Step 8: .if array[ mid ] > target then end = mid-1
Step 9: .if start<=end then goto step 5
Step 10: .return -1 as Not element found
Step 11: .Exit
Source Code:
import java.util.Scanner;
class A
{
int binarysearch(int L[],int n,int k)
{
int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(L[mid]==k)
{
return mid;
}
else if(L[mid]>k)
{
high=mid-1;
}
else
{
low=mid+1;
}
}
return -1;
}

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 4


}
class Bsm
{
public static void main(String args[])
{
int L[]=new int[20];
int n,k,pos,i;
A obj=new A();
Scanner s=new Scanner(System.in);
System.out.println("Enter n value");
n=s.nextInt();
System.out.println("Enter "+n+" elements");
for(i=0;i<n;i++)
{
L[i]=s.nextInt();
}
System.out.println("Enter searching element");
k=s.nextInt();
pos=obj.binarysearch(L,n,k);
if(pos==-1)
{
System.out.println("Searching element not found in the list");
}
else
{
System.out.println("Element found at "+(pos+1)+" location");
}
}
}

Output:

D:\DNRCET>javac Bsm.java

D:\DNRCET>java Bsm
Enter n value
5
Enter 5 elements
1 2 3 4 5
Enter searching element
3
Element found at 3 location

D:\DNRCET>java Bsm
Enter n value
4
Enter 4 elements
10 9 8 7
Enter searching element
5
Searching element not found in the list

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 5


2 b) Write a JAVA program to sort for an element in a given list of elements using 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 is a simple sorting algorithm used to rearrange a set of elements in ascending or descending
order. It's useful for smaller sets of elements but is inefficient for larger sets.
Algorithm:
Step 1: begin BubbleSort(arr)
Step 2: for all array elements
Step 3: if arr[i] > arr[i+1]
Step 4: swap(arr[i], arr[i+1])
Step 5: end if
Step 6: end for
Step 7: return arr
Step 8: end BubbleSort

Source Code:
import java.util.Scanner;
class Bubblesort
{
public static void main(String []args)
{
int n,t,i,j;
Scanner s = new Scanner(System.in);
System.out.println("How many numbers are to be sorted:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter " + n + " integers");
for (i = 0; i < n; i++)
a[i] = s.nextInt();
for (i = 0; i < ( n - 1 ); i++) {
for (j = 0; j < n - (i + 1); j++) {
if (a[j] > a[j+1]){
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}

System.out.println("After after sorting: ");


for (i = 0; i < n; i++){
System.out.print("\t"+a[i]);
}
}
}

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 6


Output:-
D:\DNRCET>javac BubbleSort.java
D:\DNRCET>java BubbleSort
How many numbers are to be sorted:
6
Enter 6 integers
1 9 2 8 5 3
After after sorting:
1 2 3 5 8 9

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


Aim: To Write a JAVA program using StringBuffer to delete, remove character.
Description:. The deleteCharAt(int index) method of Java StringBuffer class is used to delete the character at a specified
position of this sequence. After deleting a character, the current sequence shortened by one character.
Algorithm:
Step 1: Initialize a StringBuffer

Step 2: Create a StringBuffer object and initialize it with the input string.

Step 3: Delete a Single Character:Use the deleteCharAt(int index) method of StringBuffer to

delete a character at a specific index.

Step 4: Remove a Range of Characters:Use the delete(int startIndex, int endIndex) method of

StringBuffer to remove characters from startIndex up to, but not including, endIndex.

Step 5: Display the Modified StringBuffer:Print the StringBuffer after each deletion or removal

operation to display the updated string.

Source Code:
public class StringBufferDeleteCharAtExample1 {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("javatpoint");
System.out.println("string1: " + sb);
// deleting the character at index 4
sb = sb.deleteCharAt(4);
System.out.println("After deleting: " + sb);

sb = new StringBuffer("hello java");


System.out.println("string2: " + sb);
// deleting the character at index 5

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 7


sb = sb.deleteCharAt(5);
System.out.println("After deleting: " + sb);
}
}

Output:-
C:\Users\STUDENT>e:
E:\>javac StringBufferDeleteCharAtExample1.java
E:\>java StringBufferDeleteCharAtExample1
string1: javatpoint
After deleting: javapoint
string2: hello java
After deleting: hellojava

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 8


Exercise – 3
3 a). Write a JAVA program to implement class mechanism. – Create a class, methods and invoke them inside
main method.

Aim:-To Write a JAVA program to implement class mechanism. – Create a class, methods and invoke them inside main
method.
Description:. 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.
Algorithm:
Step 1: Define the Class

Step 2: Instance variables (attributes)

Step 3: Use Constructor

Step 4: Implement Methods

Step 5:Setter method for name

Step 6:Getter method for name

Step 7:Setter method for age

Step 8: Getter method for age

Step 9: Method to display information about the person

Step 10: Main class that contains the main method

Step 11: Create an object of Person

Step 12:Invoke methods of the Person class(Display initial information)

Step 13:Update information using setter methods

Step 14:Display updated information using getter methods

Source Code:
class Person
{
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}

public void setName(String name) {


this.name = name;

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 9


}

public String getName() {


return name;
}

public void setAge(int age) {


this.age = age;
}
public int getAge() {
return age;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}
public class MainClass {
public static void main(String[] args) {
Person person1 = new Person("John Doe", 30);
person1.displayInfo();
person1.setName("Jane Smith");
person1.setAge(25);
System.out.println("\nUpdated Information:");
System.out.println("Name: " + person1.getName());
System.out.println("Age: " + person1.getAge());
}
}

Output:

E:\>javac MainClass.java

E:\>java MainClass
Name: John Doe
Age: 30

Updated Information:
Name: Jane Smith
Age: 25

3 b). Write a JAVA program implements method overloading

Aim: To Write a JAVA program implements method overloading


Description: Method Overloading allows different methods to have the same name, but different signatures where the
signature can differ by the number of input parameters or type of input parameters, or a mixture of both

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 10


Algorithm:
Step 1:- Start the program.
Step 2:- Define a class overloading.
Step 3:- Inside that class define the 3 methods volume of different data type &
passing the different no of arguments.
Step 4:- Define the main method inside class ‘Sum’.
Step 5:- Create the object of class overloading in the main method.
Step 6:- Call the methods of overloading with the help of its object.
Step 7:- Pass the argument and display result.
Step 8:- Stop the program

Source Code:
/ Java program to demonstrate working of method
// overloading in Java

public class Sum


{
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Output:-
DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 11
C:\Users\STUDENT>e:

E:\>javac Sum.java

E:\>java Sum
30
60
31.0

3 c) Write a JAVA program to implement constructor.


Aim:To Write a JAVA program to implement constructor.
Description: A constructor in Java is a special method that is used to initialize objects. The constructor is called when an
object of a class is created. It can be used to set initial values for object attributes.
*Constructor name must be the same as its class name
*A Constructor must have no explicit return type
*A Java constructor cannot be abstract, static, final, and synchronized
Algorithm:
Step 1:- Create a Main class.
Step 2:- Create a class attribute.
Step 3:- Create a class constructor for the Main class.
Step 4:- Set the initial value for the class attribute x.
Step 5:- Create an object of class Main (This will call the constructor).
Step 6:- Print the value of x.
Step 7:- Stop the program.

Source Code:
public class Main
{
int x;

public Main()
{
x = 5;
}
public static void main(String[] args)
{

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 12


Main myObj = new Main();
System.out.println(myObj.x);
}
}

Output:-

C:\Users\STUDENT>E:

E:\>javac Main.java

E:\>java Main
5

3 d) Write a JAVA program to implement constructor overloading.


Aim: To Write a JAVA program to implement constructor overloading.
Description: In Java, we can overload constructors like methods. The constructor overloading can be defined as the
concept of having more than one constructor with different parameters so that every constructor can perform a different
task.
ALGORITHM:-
Step 1:- Start the program.
Step 2:- Define a class overloading.
Step 3:- Inside that class define the 3 methods volume of different data type &
passing the different no of arguments.
Step 4:- Define the main method inside class ‘area’.
Step 5:- Create the object of class overloading in the main method.
Step 6:- Call the methods of overloading with the help of its object.
Step 7:- Pass the argument and display result.
Step 8:- Stop the program.

Source Code:
import java.io.*;
class room
{
int a,b;
room(int x,int y)
{

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 13


a=x;
b=y;
}
room(int x)
{
a=b=x;
}
int area()
{
return(a*b);
}
}
class Overloading
{
public static void main(String args[])
{
room r1=new room(25,15);
System.out.println("Area"+r1.area());
room r2=new room(25);
System.out.println("Area"+r2.area());
}
}

Output:-
E:\>javac Overloading.java

E:\>java Overloading
Area375
Area625

E:\>

Exercise – 4

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 14


4.a) Write a JAVA program to implement Single Inheritance
Aim: To Write a JAVA program to implement Single Inheritance.
Description: When a class inherits another class, it is known as a single inheritance. In the example given below, Dog
class inherits the Animal class, so there is the single inheritance.
Algorithm:
Step 1:- Start the program.
Step 2:- Define a class Animal.
Step 3:- Define the Dog Class (Subclass)
Step 4:- Main Class (Entry Point)
Step 5:- Accessing Methods
Step 6:- Create the Object Creation.
Step 7:- Access methods.
Step 8:- Stop the program.
Source Code:
class Animal{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[])
{
Dog d=new Dog();
d.bark();
d.eat();
}
}

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 15


Output:-
E:\>javac TestInheritance.java
E:\>java TestInheritance
barking...
eating...

E:\>

4.b) Write a JAVA program to implement multi-level Inheritance.


Aim: To Write a JAVA program to implement multi-level Inheritance.
Description: When one class inherits multiple classes, it is known as multiple inheritance.
Algorithm:
Step 1:- Start the program.
Step 2:-Define interfaces
Step 3:-Implement interfaces in a class (Subclass)
* Implementing method1 from Interface1
* Implementing method2 from Interface2
Step 4:- Define the Main class (Main method - entry point of the program)
Step 5:- Instantiate an object of Child Class
Step 6:- Access methods
Step 7:- Stop the program.

Source Code:
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark(){System.out.println("barking...");
}
}
class BabyDog extends Dog
{
DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 16
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:-

E:\>javac TestInheritance2.java
E:\>java TestInheritance2
weeping...
barking...
eating...

4.c) Write a JAVA program for abstract class to find areas of different shapes
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). 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.
Algorithm:
Step 1:- Define an abstract class Shape(Abstract method to calculate area)
Step 2:- Define concrete subclasses of Shape
Step 3:- Subclass Circle extending Shape
Step 4:- Constructor to initialize radius
Step 5:- Implementation of calculateArea method for Circle
Step 6:- Subclass Rectangle extending Shape

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 17


Step 7:- Constructor to initialize length and width
Step 8:- Constructor to initialize length and width
Step 9:- Implementation of calculateArea method for Rectangle
Step 10:- Main class to demonstrate abstract class usage
Step 11:-Creating objects of Circle and Rectangle
Step 12:- Calculating and printing areas

Source Code:
abstract class Shape {

abstract double calculateArea();


}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double calculateArea() {
return length * width;
}
}
public class Main {
public static void main(String[] args) {
Circle circle = new Circle(5);

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 18


Rectangle rectangle = new Rectangle(4, 6);
System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
}
}

Output:
E:\>javac Main.java
E:\>java Main
Area of Circle: 78.53981633974483
Area of Rectangle: 24.0

Exercise – 5
5.a) Write a JAVA program give example for “super” keyword.

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 19


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

Algorithm:

Step 1:- Start the program.


Step 2:- Define the class.
Step 3:- Constructor to initialize id and name.
Step 4:-Define the Emp class extending Person.
Step 5:- Constructor to initialize id, name, and salary.
Step 6:-Method to display details of the employee.
Step 7:- Define the TestSuper5 class to test the inheritance and super keyword usage.
Step 8:-Create an object e1 of Emp class using constructor Emp(int id, String name, float salary).
Step 9:-Display details of employee e1
Step 10:- Stop the program
Source Code:
class Person
{
int id;
String name;
Person(int id,String name)
{
this.id=id;
this.name=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id,String name,float salary)
{
super(id,name);
//reusing parent constructor
this.salary=salary;
}
void display(){System.out.println(id+" "+name+" "+salary);}

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 20


}
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}
}
Output:
E:\>javac TestSuper5.java
E:\>java TestSuper5
1 ankit 45000.0

E:\>

5.b) Write a JAVA program to implement Interface. What kind of Inheritance can be achieved?
Aim: To Write a JAVA program to implement Interface.To find What kind of Inheritance can be achieved.
Description: A class can extend another class and can implement one and more than one Java interface. Also, this
topic has a major influence on the concept of Java and Multiple Inheritance.
Algoritham:

Step 1:- Start the program.

Step 2:Define the Interface.

Step 3:Create a Class Implementing the Interface.

Step 4: Use the Implemented Class.

Step 5:Create an object of the implementing class.

Step 6:- Stop the program.


Source Code:
interface add{
int addition(int i,int j);
}
interface sub
{
int substraction(int i,int j);
}
class Inheritance implements add,sub
{
DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 21
public int addition(int i,int j)
{
return (i+j);
}
public int substraction(int i,int j)
{
return (i-j);
}
public static void main(String args[])
{
Inheritance obj=new Inheritance();
int a=10,b=5;
System.out.println("Addition is="+obj.addition(a,b));
System.out.println("Substraction is="+obj.substraction(a,b));
}
}
Output:
D:\DNRCET>javac Exe6b.java
D:\DNRCET>java Exe6b
Addition is=15
Substraction is=5
D:\DNRCET>

Note:- Using interface mechanism we achieved multiple inheritance.

5.c) Write a JAVA program that implements Runtime polymorphism.

Aim: To Write a JAVA program that implements Runtime polymorphism.

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 22


Description: Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism allows you to
define one interface and have multiple implementations. The word “poly” means many and “morphs” means forms,
So it means many forms.

Algoritham:

Step 1:- Start the program.

Step 2:Define class&Method

Step 3: Define Subclasses

Step 4: Main Class

Step 5:- Access methods.

Step 6:- Stop the program.

Source Code:

class Shape

void draw()

System.out.println("drawing...");

class Rectangle extends Shape

void draw()

System.out.println("This is a rectangle...");

class Circle extends Shape

void draw(){System.out.println("This is a circle...");

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 23


}

class Triangle extends Shape

void draw()

System.out.println("This is a triangle...");

class PrepBytes{

public static void main(String args[])

Shape s;

s=new Rectangle();

s.draw();

s=new Circle();

s.draw();

s=new Triangle();

s.draw();

Output:

C:\Users\STUDENT>e:

E:\>javac PrepBytes.java

E:\>java PrepBytes

This is a rectangle...

This is a circle...

This is a triangle...

Exercise - 6

6.a) Write a JAVA program that describes exception handling mechanism.

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 24


Aim: To Write a JAVA program that describes exception handling mechanism.
Description: The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the
normal flow of the application can be maintained. Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Algorithm:

Step 1:- Start the program.

Step 2:- Create a class number.

Step 3:- Declare the main method this class to get user input .

Step 4:- Declare the variable num, digit = 0.

Step 5:- Take the number inside a Try block.

Step 6:- Count the no of digit of the input no using while loop.

Step 7:- If no input is given and any character input is given then pass it to catch

block and print invalid no.

Step 8:- Stop the program.

Source Code:

class Ehm
{
public static void main (String args[])throws Exception
{
int n=20,result;
try
{
result=n/0;
System.out.println("The result is"+result);
}
catch(ArithmeticException ex)
{
System.out.println("Arithmetic exception occoured: ");
}
finally
{
System.out.println("This is finally block");
}
result=n*n;
System.out.println("Square of given number is "+result);
}
}

Output:
C:\Users\STUDENT>e:

E:\DNRCET>javac Ehm.java

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 25


E:\DNRCET>java Ehm

Arithmetic exception occurred:

This is finally block

Square of given number is 400

6.b) Write a JAVA program Illustrating Multiple catch clauses.

Aim: To Write a JAVA program Illustrating Multiple catch clauses.

Description: Multiple catch blocks in Java are used to handle different types of exceptions. When statements in a single
try block generate multiple exceptions, we require multiple catch blocks to handle different types of exceptions. This
mechanism is called multi-catch block in java.

Algorithm:

Step 1:- Start the program.

Step 2:-Define a class.

Step 3:- Array Initialization.

Step 4:-Array Access

Step 5:-Catch ArithmeticException

Step 6:- Stop the program.

Source Code:

class Multiple
{
public static void main(String args[])
{
try
{
int a[]=new int[5];
a[5]=1/0;
//a[2]=a[20];
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception found");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out of Bounds");
}
catch(Exception e)
{
System.out.println("Exception found");

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 26


}
System.out.println("End of the Program");
}
}

Output:-
C:\Users\STUDENT>E:

E:\DNRCET>javac Multiple.java

E:\DNRCET>java Multiple
Arithmetic Exception found
End of the Program

E:\DNRCET>

* Write a JAVA program for creation of Java Built-in Exceptions.

Aim: To Write a JAVA program for creation of Java Built-in Exceptions


Description: Exceptions that are already available in Java libraries are referred to as built-in exception. These exceptions
are able to define the error situation so that we can understand the reason of getting this error. It can be categorized into
two broad categories, i.e., checked exceptions and unchecked exception.

Source Code:
public class BuiltInExceptionsExample {

public static void main(String[] args) {


try {
// ArithmeticException example
int result = 10 / 0; // Attempting to divide by zero
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());
}

try {
// NullPointerException example
String str = null;
System.out.println(str.length()); // Attempting to invoke a method on null reference
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: " + e.getMessage());
}

try {
// ArrayIndexOutOfBoundsException example
int[] arr = new int[5];
System.out.println(arr[10]); // Accessing an element outside array bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage());
}

try {
// NumberFormatException example
String str = "abc";

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 27


int num = Integer.parseInt(str); // Attempting to parse a non-numeric string
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " + e.getMessage());
}

try {
// IllegalArgumentException example
int age = -5;
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
} catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException caught: " + e.getMessage());
}
}
}

Output:

C:\Users\STUDENT>E:

E:\>javac BuiltInExceptionsExample.java

E:\>java BuiltInExceptionsExample

ArithmeticException caught: / by zero

NullPointerException caught: null

ArrayIndexOutOfBoundsException caught: 10

NumberFormatException caught: For input string: "abc"

IllegalArgumentException caught: Age cannot be negative

E:\>

*Write a JAVA program for creation of User Defined Exception .

Aim: To Write a JAVA program for creation of User Defined Exception .

Description: An exception is an issue (run time error) that occurred during the execution of a program. When an
exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never
gets executed.

Source Code:

// Custom exception class

class InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 28


}

// Example class using the custom exception

class Voter {

private String name;

private int age;

public Voter(String name, int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Voter's age must be 18 or older.");

this.name = name;

this.age = age;

public void printDetails() {

System.out.println("Name: " + name);

System.out.println("Age: " + age);

// Main class to demonstrate user-defined exception

public class UserDefinedExceptionExample {

public static void main(String[] args) {

try {

Voter voter1 = new Voter("Alice", 25);

voter1.printDetails();

Voter voter2 = new Voter("Bob", 16); // This will throw InvalidAgeException

voter2.printDetails(); // This line will not be executed

} catch (InvalidAgeException e) {

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 29


System.out.println("InvalidAgeException caught: " + e.getMessage());

Output:

C:\Users\STUDENT>E:

E:\>javac UserDefinedExceptionExample.java

E:\>java UserDefinedExceptionExample

Name: Alice

Age: 25

InvalidAgeException caught: Voter's age must be 18 or older.

E:\>

Exercise - 7

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 30


7.a) Write a JAVA program that creates threads by extending Thread class. First thread display “Good
Morning “every 1 sec, the second thread displays “Hello “every 2 seconds and the third display “Welcome”
every 3 seconds, (Repeat the same by implementing Runnable).

Description:

Algoritham:

Step 1:- Start the program.

Step 2:-Declare a class.

Step 3:-Initialize Constructor.

Step 4:-Starts the thread.

Step 5:-Loops 5 times.

Step 6:-Define a main method in a separate class.

Step 7:-Create instances of ChildThread with different names.

Step 8:- Stop the program.

Source Code:

//Program for Multithreading by implementing Runnable interface

class ChildThread implements Runnable

Thread t;

ChildThread(String name)

t = new Thread(this, name);

t.start();

public void run()

for(int i=1;i<=5;i++)

try

if(t.getName().equals("First Thread"))

Thread.sleep(1000);

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 31


System.out.println(t.getName()+": Good Morning");

else if(t.getName().equals("Second Thread"))

Thread.sleep(2000);

System.out.println(t.getName()+": Hello");

else

Thread.sleep(3000);

System.out.println(t.getName()+": Welcome");

catch(InterruptedException e)

System.out.println(t.getName()+" is interrupted");

class Exe7

public static void main(String args[])

ChildThread one = new ChildThread("First Thread");

ChildThread two = new ChildThread("Second Thread");

ChildThread three = new ChildThread("Third Thread");

Output:

C:\Users\STUDENT>E:

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 32


E:\>javac Exe7.java

E:\>java Exe7

First Thread: Good Morning

Second Thread: Hello

Third Thread: Welcome

First Thread: Good Morning

Second Thread: Hello

First Thread: Good Morning

Third Thread: Welcome

Second Thread: Hello

Third Thread: Welcome

First Thread: Good Morning

Second Thread: Hello

Third Thread: Welcome

First Thread: Good Morning

Second Thread: Hello

Third Thread: Welcome

E:\>

7.b) Write a program illustrating is Alive and join ().

Aim: To Write a program illustrating is Alive and join ()

Description: Sometimes one thread needs to know when other thread is terminating. In java, isAlive() and join() are
two different methods that are used to check whether a thread has finished its execution or not.The isAlive() method
returns true if the thread upon which it is called is still running otherwise it returns false. But, join() method is used
more commonly than isAlive(). This method waits until the thread on which it is called terminates.

Algoritham:

Step 1:-Define class.

Step 2:- Implement the run() method.

Step 3:- Print the status of the current thread using isAlive() method.

Step 4:- Create a Thread object.

Step 5:- Start the thread.

Step 6:- Wait for the thread to complete its execution.


DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 33
Step 7:- Print the status of the thread using isAlive().

Step 8:- Stop the program.

Source Code:

//import java.lang.*;

public class Exe7b implements Runnable {

public void run() {

Thread t = Thread.currentThread();

// tests if this thread is alive

System.out.println("status = " + t.isAlive());

public static void main(String args[]) throws Exception {

Thread t = new Thread(new Exe10b());

// this will call run() function

t.start();

// waits for this thread to die

t.join();

// tests if this thread is alive

System.out.println("status = " + t.isAlive());

Output:

C:\Users\STUDENT>E:

E:\>javac Exe7b.java

E:\>java Exe7b

status = true

status = false

7.c) Write a Program illustrating Daemon Threads.

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 34


Aim:-To Write a java Program illustrating Daemon Threads.

Description: Daemon thread in Java is a service provider thread that provides services to the user thread.Its life
depend on the mercy of user threads i.e. when all the user threads dies, JVM terminates this thread
automatically.There are many java daemon threads running automatically e.g. gc, finalizer etc.You can see all the
detail by typing the jconsole in the command prompt. The jconsole tool provides information about the loaded classes,
memory usage, running threads etc..

Algoritham:

Step 1:-Start the program.

Step 2:-Define class.

Step 3:-Override the run() method to define thread behavior.

Step 4:- Define Main Method.

Step 5:-Create instances of Daemonthread.

Step 6:-Set t1 as Daemon thread.

Step 7:-Start all threads.

Step 8:-Stop the program.

Source Code:

// Program for illustrating Daemon Threads

class Daemonthread extends Thread

public void run()

if(Thread.currentThread().isDaemon())

System.out.println("Daemon Thread");

else

System.out.println("User Thread");

public static void main(String args[])

Daemonthread t1= new Daemonthread();

Daemonthread t2= new Daemonthread();

Daemonthread t3= new Daemonthread();

t1.setDaemon(true);

t1.start();

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 35


t2.start();

t3.start();

Output:

C:\Users\STUDENT>E:

E:\>javac Daemonthread.java

E:\>java Daemonthread

Daemon Thread

User Thread

User Thread

7.d) Write a JAVA program Producer Consumer Problem.

Aim: To Write a JAVA program Producer Consumer Problem.

Description: The Producer-Consumer problem is a classical multi-process synchronization problem, that is we are
trying to achieve synchronization between more than one process.There is one Producer in the producer-consumer
problem, Producer is producing some items, whereas there is one Consumer that is consuming the items produced by
the Producer. The same memory buffer is shared by both producers and consumers which is of fixed-size.The task of
the Producer is to produce the item, put it into the memory buffer, and again start producing items. Whereas the task
of the Consumer is to consume the item from the memory buffer.

Algoritham:

Step 1:-Start the program.

Step 2:-Define class.

Step 3:- Define a variable.

Step 4:- Declare an item variable to store the produced or consumed item.

Step 5:- Initialize two Semaphore objects.

Step 6:- Implement get() method.

Step 7:-Implement put(int item) method.

Step 8:- Define Producer Class.

Step 9:- Define Consumer Class.

Step 10:-Define Main Class.

Step 11:-Implement the object creation.

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 36


Step 12:- Stop the program.

Source Code:

// Java implementation of a producer and consumer

// that use semaphores to control synchronization.

import java.util.concurrent.Semaphore;

class Que {

int item;

// Con initialized with 0 permits

// to ensure put() executes first

static Semaphore Con = new Semaphore(0);

static Semaphore Prod = new Semaphore(1);

// to get an item from buffer

void get() {

try {

// Before consumer can consume an item,

// it must acquire a permit from Con

Con.acquire();

} catch (InterruptedException e) {

System.out.println("InterruptedException caught");

// consumer consuming an item

System.out.println("Consumer consumed item: " + item);

// After consumer consumes the item,

// it releases Prod to notify producer

Prod.release();

// to put an item in buffer

void put(int item) {

try {

// Before producer can produce an item,

// it must acquire a permit from Prod

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 37


Prod.acquire();

} catch (InterruptedException e) {

System.out.println("InterruptedException caught");

// producer producing an item

this.item = item;

System.out.println("Producer produced item: " + item);

// After producer produces the item,

// it releases Con to notify consumer

Con.release();

// Producer class

class Producer implements Runnable {

Que q;

Producer(Que q) {

this.q = q;

new Thread(this, "Producer").start();

public void run() {

for (int i = 0; i < 5; i++) q.put(i);

// Consumer class

class Consumer implements Runnable {

Que q;

Consumer(Que q) {

this.q = q;

new Thread(this, "Consumer").start();

public void run() {

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 38


for (int i = 0; i < 5; i++) // consumer get items

q.get();

// Driver class

class Main {

public static void main(String args[]) {

// creating buffer queue

Que q = new Que();

// starting consumer thread

new Consumer(q);

// starting producer thread

new Producer(q);

Output:

C:\Users\STUDENT>E:

E:\>javac Main.java

E:\>java Main

Producer produced item: 0

Consumer consumed item: 0

Producer produced item: 1

Consumer consumed item: 1

Producer produced item: 2

Consumer consumed item: 2

Producer produced item: 3

Consumer consumed item: 3

Producer produced item: 4

Consumer consumed item: 4

Exercise – 8
DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 39
8.1) Write a JAVA program that import and use the user defined packages.

Aim:To Write a JAVA program that import and use the user defined packages.

Description:

Algoritham:

Source Code:

Output:

8.2) Without writing any code, build a GUI that display text in label and image in an ImageView (use JavaFX).

Aim: To Without writing any code, build a GUI that display text in label and image in an ImageView (use JavaFX).

Description: Label is a part of JavaFX package . Label is used to display a short text or an image, it is a non-editable
text control. It is useful for displaying text that is required to fit within a specific space, and thus may need to use an
ellipsis or truncation to size the string to fit

Source Code:

import javafx.application.Application;

import javafx.scene.Scene;

import javafx.scene.control.Label;

import javafx.scene.image.Image;

import javafx.scene.image.ImageView;

import javafx.scene.layout.VBox;

import javafx.stage.Stage;

public class DisplayTextAndImage extends Application {

@Override

public void start(Stage primaryStage) throws Exception {

// Create a label for displaying text

Label label = new Label("Hello, JavaFX!");

// Create an image view for displaying an image

ImageView imageView = new ImageView();

// Load an image (adjust the path as necessary)

imageView.setImage(new Image("path/to/your/image.png"));

// Create a layout container (VBox) to hold label and image view

VBox root = new VBox(10); // 10px spacing

root.getChildren().addAll(label, imageView);

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 40


// Create a scene with the layout container as root

Scene scene = new Scene(root, 400, 300); // Set width and height as needed

// Set the scene on the primary stage

primaryStage.setScene(scene);

primaryStage.setTitle("JavaFX Display Text and Image"); // Set the window title

primaryStage.show(); // Display the stage

public static void main(String[] args) {

launch(args); // Launch the JavaFX application

Output:

-----------------------------------

| JavaFX Display Text and Image |

|---------------------------------|

| Hello, JavaFX! |

| |

| [Image displayed here] |

| |

-----------------------------------

8.3) Build a Tip Calculator app using several JavaFX components and learn how to respond to user
interactions with the GUI.

Aim: To Build a Tip Calculator app using several JavaFX components and learn how to respond to user interactions
with the GUI.

Description:

Source Code:

import javafx.application.Application;

import javafx.geometry.Insets;

import javafx.scene.Scene;

import javafx.scene.control.*;

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 41


import javafx.scene.layout.GridPane;

import javafx.stage.Stage;

public class TipCalculatorApp extends Application {

@Override

public void start(Stage primaryStage) {

primaryStage.setTitle("Tip Calculator");

// Create UI components

Label billAmountLabel = new Label("Bill Amount:");

TextField billAmountField = new TextField();

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

ComboBox<Integer> tipPercentageComboBox = new ComboBox<>();

Label tipAmountLabel = new Label("Tip Amount:");

Label totalAmountLabel = new Label("Total Amount:");

Label tipAmountResult = new Label();

Label totalAmountResult = new Label();

Button calculateButton = new Button("Calculate");

// Populate tip percentage dropdown

tipPercentageComboBox.getItems().addAll(10, 15, 20, 25); // Example percentages

// Create layout pane and add components

GridPane gridPane = new GridPane();

gridPane.setPadding(new Insets(20));

gridPane.setHgap(10);

gridPane.setVgap(10);

gridPane.add(billAmountLabel, 0, 0);

gridPane.add(billAmountField, 1, 0);

gridPane.add(tipPercentageLabel, 0, 1);

gridPane.add(tipPercentageComboBox, 1, 1);

gridPane.add(calculateButton, 0, 2, 2, 1);

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 42


gridPane.add(tipAmountLabel, 0, 3);

gridPane.add(tipAmountResult, 1, 3);

gridPane.add(totalAmountLabel, 0, 4);

gridPane.add(totalAmountResult, 1, 4);

// Event handling for calculate button

calculateButton.setOnAction(e -> {

try {

double billAmount = Double.parseDouble(billAmountField.getText());

double tipPercentage = tipPercentageComboBox.getValue() / 100.0;

double tipAmount = billAmount * tipPercentage;

double totalAmount = billAmount + tipAmount;

tipAmountResult.setText(String.format("$%.2f", tipAmount));

totalAmountResult.setText(String.format("$%.2f", totalAmount));

catch (NumberFormatException ex)

// Handle invalid input

Alert alert = new Alert(Alert.AlertType.ERROR);

alert.setTitle("Error");

alert.setHeaderText(null);

alert.setContentText("Please enter a valid number for the bill amount.");

alert.showAndWait();

});

// Set scene and show stage

Scene scene = new Scene(gridPane, 300, 250);

primaryStage.setScene(scene);

primaryStage.show();

public static void main(String[] args) {

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 43


launch(args);

Output:

-----------------------------------

| Tip Calculator |

|---------------------------------|

| Bill Amount: [ ]|

| Tip Percentage: [ 15% ▼]


|

| |

| [ Calculate ] |

| |

| Tip Amount: [ $7.50 ] |

| Total Amount: [ $57.50 ] |

-----------------------------------

Exercise – 9
DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 44
9. 1)Write a java program that connects to a database using JDBC.

Aim: T o Write a java program that connects to a database using JDBC.

Source Code:

import java.sql.*;

public class JDBCExample {

// JDBC URL, username, and password of MySQL server

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";

private static final String USERNAME = "root";

private static final String PASSWORD = "password";

public static void main(String[] args) {

// Establishing a connection

try (Connection conn = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD)) {

// Creating a statement

Statement stmt = conn.createStatement();

// Executing a query

String sql = "SELECT * FROM users";

ResultSet rs = stmt.executeQuery(sql);

// Processing result set

while (rs.next()) {

int id = rs.getInt("id");

String name = rs.getString("name");

String email = rs.getString("email");

System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);

Output:

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 45


+----+----------+-----------------------+

| id | name | email |

+----+----------+-----------------------+

| 1 | John Doe | [email protected] || 2 |


Jane Doe | [email protected] |

| 3 | Alice | [email protected] |

+----+----------+-----------------------+

ID: 1, Name: John Doe, Email: [email protected]

ID: 2, Name: Jane Doe, Email: [email protected]

ID: 3, Name: Alice, Email: [email protected]

9 b) Write a java program to connect to a database using JDBC and insert values into it.

Aim: To Write a java program to connect to a database using JDBC and insert values into it.

Source Code:

Steps to Create a JDBC Program for Inserting Values:

CREATE DATABASE mydatabase;

USE mydatabase;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

email VARCHAR(100)

);

Java Program:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class JDBCInsertExample {


DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 46
// JDBC URL, username, and password of MySQL server

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";

private static final String USERNAME = "root";

private static final String PASSWORD = "password";

public static void main(String[] args) {

// SQL query to insert values into table

String sqlInsert = "INSERT INTO users (name, email) VALUES (?, ?)";

try (

// Establishing a connection

Connection conn = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);

// Creating a prepared statement with auto-generated keys

PreparedStatement pstmt = conn.prepareStatement(sqlInsert,


PreparedStatement.RETURN_GENERATED_KEYS)

){

// Setting parameters for the statement

pstmt.setString(1, "John Doe");

pstmt.setString(2, "[email protected]");

// Executing the statement

int affectedRows = pstmt.executeUpdate();

if (affectedRows > 0) {

System.out.println("A new user has been inserted successfully.");

} else {

System.out.println("No rows have been affected.");

} catch (SQLException e) {

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 47


e.printStackTrace();

Output:

A new user has been inserted successfully.

javac JDBCInsertExample.java

java JDBCInsertExample

9.c) Write a java program to connect to a database using JDBC and delete values from it.

Aim: To Write a java program to connect to a database using JDBC and delete values from it.

Source code:

Steps to Create a JDBC Program for Deleting Values:

CREATE DATABASE mydatabase;

USE mydatabase;

CREATE TABLE users (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100),

email VARCHAR(100)

);

Java Program:

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class JDBCDeleteExample

// JDBC URL, username, and password of MySQL server

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";

private static final String USERNAME = "root";

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 48


private static final String PASSWORD = "password";

public static void main(String[] args)

// SQL query to delete values from table based on condition

String sqlDelete = "DELETE FROM users WHERE id = ?";

try (

// Establishing a connection

Connection conn = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);

// Creating a prepared statement

PreparedStatement pstmt = conn.prepareStatement(sqlDelete)

// Setting parameter for the statement

pstmt.setInt(1, 1); // Deleting user with id = 1

// Executing the statement

int affectedRows = pstmt.executeUpdate();

if (affectedRows > 0) {

System.out.println("User with id = 1 has been deleted successfully.");

Else

System.out.println("No rows have been affected. User not found or already deleted.");

catch (SQLException e)

e.printStackTrace();

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 49


Output:

User with id = 1 has been deleted successfully.

No rows have been affected. User not found or already deleted.

java.sql.SQLException: [specific error message]

at [class and method where the exception occurred] ...

User with id = 1 has been deleted successfully.

javac JDBCDeleteExample.java

java JDBCDeleteExample

DNRCET (Airtificial Intelligence& Data Science/Machine Learning) Page 50

You might also like