0% found this document useful (0 votes)
4 views52 pages

Java Record Lab 2

The document provides an introduction to Java, detailing its history, features, and the Java Development Kit (JDK). It includes various programming exercises demonstrating Java concepts such as data types, object-oriented programming, and methods like binary search and bubble sort. Additionally, it covers practical implementations of constructors and method overloading in Java programming.

Uploaded by

hnmkts7
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)
4 views52 pages

Java Record Lab 2

The document provides an introduction to Java, detailing its history, features, and the Java Development Kit (JDK). It includes various programming exercises demonstrating Java concepts such as data types, object-oriented programming, and methods like binary search and bubble sort. Additionally, it covers practical implementations of constructors and method overloading in Java programming.

Uploaded by

hnmkts7
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

Date: Exp No: Page no:

JAVA INTRODUCTION:
Java is a class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is intended to let
application developers write once, and run anywhere (WORA), meaning that compiled
Java code can run on all platforms that support Java without the need for
recompilation. Java was first released in 1995 and is widely used for developing
applications for desktop, web, and mobile devices. Java is known for its simplicity,
robustness, and security features, making it a popular choice for enterprise-level
applications. Java was developed by James Gosling at Sun Microsystems Inc in May
1995 and later acquired by Oracle Corporation. It is a simple programming language.
Java makes writing, compiling, and debugging programming easy. It helps to create
reusable code and modular programs. Java is a class-based, object-oriented
programming language and is designed to have as few implementation dependencies
as possible. A general-purpose programming language made for developers to write
once run anywhere that is compiled Java code can run on all platforms that support
Java. Java applications are compiled to byte code that can run on any Java Virtual
Machine. The syntax of Java is similar to C/C++.

HISTORY OF JAVA:
Java’s history is as interesting as it is impactful. The journey of this powerful
programming language began in 1991 when James Gosling, Mike Sheridan, and Patrick
Naughton, a team of engineers at Sun Microsystems known as the “Green Team,” set
out to create a new language initially called “Oak.” Oak was later renamed Java,
inspired by Java coffee, and was first publicly released in 1996 as Java 1.0. This initial
version provided a no-cost runtime environment across popular platforms, making it
accessible to a broad audience. Arthur Van Hoff rewrote the Java 1.0 compiler to
strictly comply with its specifications, ensuring its reliability and cross-platform
capabilities.

Features of Java:
1. Platform Independent
2. Object-Oriented Programming
3. Simplicity
4. Robustness
5. Security
6. Distributed
7. Multithreading

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

8. Portability
9. High Performance

JDK IN JAVA:
The Java Development Kit (JDK) is a cross-platformed software development
environment that offers a collection of tools and libraries necessary for developing
Java-based software applications and applets. It is a core package used in Java, along
with the JVM (Java Virtual Machine) and the JRE (Java Runtime Environment). Beginners
often get confused with JRE and JDK, if you are only interested in running Java programs
on your machine then you can easily do it using Java Runtime Environment. However, if
you would like to develop a Java-based software application then along with JRE you
may need some additional necessary tools, which is called JDK.

JDK=JRE+Development Tools

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

JAVA DATATYPES:

PATH AND CLASS PATH:

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link] a JAVA program to display default value of all primitive data type of JAVA.
Aim: To write a program to display the default value of all primitive data type of JAVA.
Program code:
public class DataType
{
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)
{
[Link]("The default values of primitive data types are:");
[Link]("Byte :"+b);
[Link]("Short :"+s);
[Link]("Int :"+i);
[Link]("Long :"+l);
[Link]("Float :"+f);
[Link]("Double :"+d);
[Link]("Char :"+c);
[Link]("Boolean :"+bl);

Output:
C:\23-532>javac [Link]
C:\23-532>java DataType
The default values of primitive data types are:
Byte :0
Short :0
Int :0
Long :0
Float :0.0
Double :0.0

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Char :
Boolean :false

Result:
Hence, the program to display the default value of all primitive data type of JAVA
executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link] 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: To write a program to display the roots of a quadratic equation ax2+bx=0.
Program code:
package Week1;
import [Link].*;
public class quadraticformula
{
public static void main(String args[]){
int a,b,c,d,f=0;
Scanner scr=new Scanner([Link]);
[Link]("\nEnter the values of a ,b ,c : ");
a=[Link]();
b=[Link]();
c=[Link]();
d=(b*b)-(4*a*c);
if(d==0){
[Link]("Roots are real and Equal");
f=1;
}
else if(d>0){
[Link]("Roots are real and UnEqual");
f=1;
}
else
[Link]("Roots are imaginary");
if(f==1)
{
float r1=(float)(-b+[Link](d))/(2*a);
float r2=(float)(-[Link](d))/(2*a);
[Link]("Roots are : "+r1+" ,"+r2);
}
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java quadraticformula

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Enter the values of a ,b ,c :


1
2
1
Roots are real and Equal
Roots are : -1.0 ,-1.0
Result:
Hence, the program to display the roots of a quadratic equation ax2+bx=0 executed
successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link] a JAVA program to search for an element in a given list of elements using
binary search mechanism.
Aim: To search for an element in a given list of elements using binary search
mechanism.
Program Code:
import [Link].*;
class BinarySearch
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of elements in the array: ");
int size = [Link]();
int array[] = new int[size];
[Link]("Enter the elements of the array :");
for (int i = 0; i < size; i++)
{
array[i] = [Link]();
}
[Link]("Enter the value to search for: ");
int target = [Link]( );
int result = binarySearch(array, target);
if (result != -1)
{
[Link]("Element found at index: " + result);
}
else
{
[Link]("Element not found in the array.");
}

[Link]( );
}
public static int binarySearch(int[] array, int target)
{
int low = 0;
int high = [Link] - 1;
while (low <= high)
{

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

int mid = low+ (high- low) / 2;


if (array[mid] == target)
{
return mid;
}
else if (array[mid] < target)
{
low = mid + 1;
}
else
{
high= mid - 1;
} }
return -1;
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java BinarySearch
Enter the number of elements in the array:4
Enter the elements of the array :
10
20
30
40
Enter the value to search for: 30
Element found at index: 2
Result:
Hence, the program to search for an element in a given list of elements using binary
search mechanism has been executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

4. Write a JAVA program to sort for an element in a given list of elements using
bubble sort.
Aim: To sort for an element in a given list of elements using bubble sort.
Program code:
import [Link].*;
public class BubbleSort
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of elements: ");
int n = [Link]( );
int arr[] = new int[n];
[Link]("Enter " + n + " elements:");
for (int i = 0; i < n; i++)
{
arr[i] = [Link]( );
}
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
[Link]("Sorted Array:");
for (int i = 0; i < n; i++)
{
[Link]( " \n"+arr[i] );
}
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac [Link]
C:\23-532>java BubbleSort
Enter the number of elements:
4
Enter 4 elements:
46
35
21
67
Sorted Array:
21
35
46
67
Result:
Hence, the program to sort for an element in a given list of elements using bubble sort
executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

5. Write a JAVA program using StringBuffer to delete, remove character.


Aim: StringBuffer to delete, remove character.
Program code:
import [Link];
public class StringBufferExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);
[Link](“Enter any string: “);
String str = [Link]( );
StringBuffer s = new StringBuffer(str);
[Link](“\nOriginal StringBuffer: “ + s);
[Link](2, 5);
[Link](“\nAfter deleting substring from index 2 to 5: \n” + s);
[Link](0);
[Link](“\nAfter deleting character at index 0: “ + s);
[Link]( );
}
}
Output:
C:\23-532>javac [Link]
C:\23-532>java StringBufferExample

Enter any string: Hello, World!


Original StringBuffer: Hello, World!
After deleting substring from index 2 to 5:
He, World!
After deleting character at index 0: e, World!

Result:
Hence, the program to write a program to StringBuffer to delete, remove character
executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

6. Write a JAVA program to implement class mechanism. Create a class, methods


and invoke them inside main method.
Aim: To implement class mechanism. Create a class, methods and invoke them inside
main method.
Program code:
import [Link].*;
class Calculator
{
public int add(int a, int b)
{
return a + b;
}
public int subtract(int a, int b)
{
return a - b;
}
public int multiply(int a, int b)
{
return a * b;
}
public double divide(int a, int b)
{
if (b == 0)
{
[Link]("Error: Division by zero is not allowed.");
return 0;
}
return (double) a / b;
}}
public class Calculator1
{
public static void main(String[] args)
{
Calculator calc =new Calculator();
Scanner sc=new Scanner([Link]);
[Link]("Enter any Two values : ");
int a = [Link]( );
int b = [Link]( );
[Link]("Addition of " + a + " and " + b + ": " + [Link](a, b));

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link]("Subtraction of " + a + " and " + b + ": " + [Link](a, b));


[Link]("Multiplication of " + a + " and " + b + ": " + [Link](a, b));
[Link]("Division of " + a + " and " + b + ": " + [Link](a, b));
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java Calculator1
Enter any Two values:
3
4
Addition of 3 and 4: 7
Subtraction of 3 and 4: -1
Multiplication of 3 and 4: 12
Division of 3 and 4: 0.75

Result:
Hence, the program to implement class mechanism. Create a class, methods and
invoke them inside main method executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

7. Write a JAVA program implement method overloading.


Aim: To implement method overloading.
Program code:
class Overloading
{ public int add(int a, int b)
{ return a + b;
}
public double add(double a, double b)
{ return a + b;
}

public int add(int a, int b, int c)


{ return a + b + c;
}
} public class MethodOverloading1
{ public static void main(String[] args)
{
Overloading over = new Overloading( );
[Link]("\nSum of two integers: " + [Link](5,3));
[Link]("\nSum of two doubles: " + [Link](5.5,6.5));
[Link]("\nSum of three integers: " + [Link](5,6,7));
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java MethodOverloading1
Sum of two integers: 8
Sum of two doubles: 12.0
Sum of three integers: 18

Result:
Hence, the program to implement method overloading executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

8. Write a JAVA program to implement constructor.


Aim: To implement constructor.
Program code:
class Person
{
String name;
int age;
public Person()
{
[Link]("Default constructor called");
}
public Person(String name, int age)
{
[Link] = name; // 'this' keyword refers to the current object

[Link] = age;
[Link]("Parameterized constructor called");
}
public Person(Person p)
{
[Link] = [Link];
[Link] = [Link];
[Link]("Copy Constructor called");
}
public void display( )
{
[Link]("Name: " + name +" \t" +", Age: " + age);
}
}

public class Constructor


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

Person p1 = new Person();


[Link]();
Person p2 = new Person("thirumalesh", 21);
[Link]();

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Person p3 = new Person(p2);


[Link]();
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java Constructor
Default constructor called
Name: null, Age: 0
Parameterized constructor called
Name:thirumalesh, Age: 21
Copy Constructor called Name: thirumalesh, Age: 21

Result:
Hence, the program to implement constructor executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

9. Write a JAVA program to implement constructor overloading.


Aim: To implement constructor overloading.
Program code:
class Student
{
String name;
int age;
String course;
public Student( )
{
name = "Unknown";
age = 0; course = "Not Enrolled";
[Link]("Default Constructor called");
}
public Student(String name, int age)
{ [Link] = name; [Link] = age; course = "Not Enrolled";
[Link]("Constructor with two parameters called");
}
public Student(String name, int age, String course)
{
[Link] = name; [Link] = age; [Link] = course;
[Link]("Constructor with three parameters called");
}
public void display( )
{
[Link]("Name: " + name + "\t " +", Age: " + "\t " + age + ", Course: " +
course);
}
} public class ConstructorOverloading
{ public static void main(String args[])
{
Student student1 = new Student(); [Link]( );
Student student2 = new Student("thiru", 12);
[Link]( );
Student student3 = new Student("sai", 21, "Computer Science");
[Link]();
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac [Link]
C:\23-532>java ConstructorOverloading
Default Constructor called
Name: Unknown , Age: 0, Course: Not Enrolled
Constructor with two parameters called
Name:thiru , Age:12, Course: Not Enrolled
Constructor with three parameters called
Name: sai, Age: 21, Course: Computer Science

Result:
Hence, the program to implement constructor overloading executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

10. Write a JAVA program to implement Single Inheritance.


Aim: To implement Single Inheritance.
Program code:
class ParentClass
{
int a;
void setData(int a)
{
this.a = a;
}
}
class ChildClass extends ParentClass
{
void showData( )
{
[Link]("Value of a is " + a);
}
}
public class SingleInheritance
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
[Link](20);
[Link]( );
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java SingleInheritance
Value of a is 20

Result:
Hence, the program to implement single inheritance executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

11. Write a JAVA program to implement multi level Inheritance.


Aim: To implement multi level Inheritance.
Program code:
class ParentClass
{
int a;
void setData(int a)
{
this.a = a;
}
}
class ChildClass extends ParentClass
{
void showData( )
{
[Link]("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass
{
void display( )
{
[Link]("Inside ChildChildClass!");
}
}
public class Multilevel Inheritance
{
public static void main(String[] args)
{
ChildChildClass obj = new ChildChildClass();
[Link](50);
[Link]();
[Link]();
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac Multilevel [Link]
C:\23-532>java Multilevel Inheritance
Value of a is 50
Inside ChildChildClass!"

Result:
Hence, the program to implement multi-level inheritance executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

12. Write a JAVA program for abstract class to find areas of different shapes.
Aim: To write a program for abstract class to find areas of different shapes.
Program code:
abstract class Shape
{
abstract double calculateArea();
}
class Circle extends Shape
{
double radius;
public Circle(double radius)
{
[Link] = radius;
}
@Override
double calculateArea( )
{
return [Link] * radius * radius;
}
}
class Rectangle extends Shape
{
double length;
double width;
public Rectangle(double length, double width)
{
[Link] = length;
[Link] = width;
}
@Override
double calculateArea( )
{
return length * width;
}
}
class Triangle extends Shape
{ double base; double height;
public Triangle(double base, double height)
{

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link] = base;
[Link] = height;
}
@Override
double calculateArea()
{
return 0.5 * base * height;
}
}
public class AbstractClass
{
public static void main(String[] args)
{
// Creating objects of different shapes
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(6,7);
Shape triangle = new Triangle(4,5);
[Link]("Area of Circle: " + [Link]());
[Link]("Area of Rectangle: " + [Link]());
[Link]("Area of Triangle: " + [Link]());
}
}

Output:
C:\23532>javac [Link]
C:\23-532>java AbstractClass
Area of Circle: 78.53981633974483
Area of Rectangle: 42.0
Area of Triangle: 10.0

Result:
Hence, the write a program for abstract class to find areas of different shapes executed
successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

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


Aim: To implement “super” keyword.
Program code:
class Person
{
Person( )
{
[Link] ("Person class Constructor");
}
}
class Student extends Person
{
Student()
{
super( );
[Link]("Student class Constructor");
}
}

class SuperDemo
{
public static void main(String[] args)
{
Student s = new Student( );
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java SuperDemo
Person class Constructor
Student class Constructor

Result:
Hence, the program to implement “super” keyword executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

14. Write a JAVA program to implement Interface. What kind of Inheritance can be
achieved?
Aim: To implement Interface.
Program code:
interface AnimalEat
{ void eat( );
} interface AnimalTravel
{ void travel( );
} class Animal implements AnimalEat, AnimalTravel
{ public void eat( )
{
[Link]("Animal is eating");
} public void travel( )
{
[Link]("Animal is travelling");
}
}

public class InterfaceDemo


{ public static void main(String args[])
{
Animal a = new Animal( );
[Link]( );
[Link]( );
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java InterfaceDemo
Animal is eating
Animal is travelling

Result:
Hence, the program to implement interface executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

15. Write a JAVA program that implements Runtime polymorphism.


Aim: To implements Runtime polymorphism.
Program code:
class Animal
{
void sound()
{
[Link]("Animal makes a sound");
}
} class Dog extends Animal
{
@Override
void sound ( )
{
[Link]("Dog barks");
}
}
class Cat extends Animal
{
void sound( )
@Override
{
[Link]("Cat meows");
}
}
public class RuntimePolymorphism
{
public static void main(String[] args)
{
Animal myAnimal = new Dog( );
[Link]( );
myAnimal = new Cat( );
[Link]( );
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac [Link]
C:\23-532>java RuntimePolymorphism
Dog barks
Cat meows

Result:
Hence, the program to implement runtime polymorphism executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

16. Write a JAVA program that describes exception handling mechanism.


Aim: To write a program to implement exception handling mechanism.
Program code:
package week6;
import [Link];
class WeightLimitExceeded extends Exception {
WeightLimitExceeded(int weight) {
super("Weight limit exceeded by " + [Link](15 - weight) + " kg");
}
}

public class Main {

void validWeight(int weight) throws WeightLimitExceeded {


if (weight > 15) {
throw new WeightLimitExceeded(weight);
} else {
[Link]("You are ready to fly!");
}
}

public static void main(String[] args) {


Main ob = new Main();
Scanner in = new Scanner([Link]);
for (int i = 0; i < 2; i++) {
[Link]("Enter weight: ");
try {
int weight = [Link]();
[Link](weight);
} catch (WeightLimitExceeded e) {
[Link]([Link]());
} catch (Exception e) {
[Link]("Invalid input. Please enter a valid integer.");
[Link]();
}
}
[Link]();
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac [Link]
C:\23-532>java Main
Enter weight: 15
You are ready to fly!
Enter weight: 45
Weight limit exceeded by 30 kg.

Result:
Hence, the program to implement exception handling mechanism has been executed
successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link] a JAVA program Illustrating Multiple catch clauses.


Aim: To write a program to illustrate multiple catch clauses.
Program code:
package week6;
import [Link];

public class MultipleCatchExample {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter two integers to divide:");

try {
int num1 = [Link]();
int num2 = [Link]();
int result = num1 / num2;
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
catch ([Link] e) {
[Link]("Error: Please enter valid integers.");
}
catch (Exception e) {
[Link]("Error: An unexpected error occurred: " + [Link]());
}
finally {
[Link]();
}
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java MultipleCatchExample

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Enter two integers to divide:


16
4
Result: 4

Result:
Hence, the program to illustrate multiple catch clauses has been executed
successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

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


Aim: To write a program to create java built-in exceptions.
Program code:
package week6;
public class BuiltInExceptionsExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
[Link]("ArithmeticException: Division by zero is not allowed.");
}
try {
String str = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("NullPointerException: Attempted to access a method on a
null object.");
}

try {
int[] arr = new int[5];
[Link](arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException: Index is out of bounds.");
}
try {
[Link]("[Link]");
} catch (ClassNotFoundException e) {
[Link]("ClassNotFoundException: The specified class was not
found.");
}
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac [Link]
C:\23-532>java BuiltInExceptionsExample

ArithmeticException: Division by zero is not allowed.


NullPointerException: Attempted to access a method on a null object.
ArrayIndexOutOfBoundsException: Index is out of bounds.
ClassNotFoundException: The specified class was not found.

Result:
Hence, the program to create java built-in exceptions has been executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

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


Aim: To write a program for creation of user defined exception.
Program code:
package week6;
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class UserDefinedExceptionDemo {

public static void checkAge(int age) throws InvalidAgeException {


if (age < 0 || age > 150) {
throw new InvalidAgeException("Age must be between 0 and 150.");
} else {
[Link]("Age is valid: " + age);
}
}

public static void main(String[] args) {


try {
checkAge(25);
checkAge(-5);
} catch (InvalidAgeException e) {
[Link]("Caught exception: " + [Link]());
}

try {
checkAge(200);
} catch (InvalidAgeException e) {
[Link]("Caught exception: " + [Link]());
}
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac UserDefinedExceptionDemo
C:\23-532>java UserDefinedExceptionDemo

Age is valid: 25
Caught exception: Age must be between 0 and 150.
Caught exception: Age must be between 0 and 150.

Result:
Hence, the program to create user defined exception has been executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

20. 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).
Aim: To write a program to create threads by extending thread class.
Program code:
package week7;
import [Link];
class MessageRunnable implements Runnable {
private String message;
private int interval;
private int count;
public MessageRunnable(String message, int interval, int count) {
[Link] = message;
[Link] = interval;
[Link] = count;
}
public void run() {
for (int i = 0; i < count; i++) {
try {
[Link](interval);
[Link](message);
} catch (InterruptedException e) {
[Link](message + " Thread interrupted");
}
}
}
}

public class RunnableExample { public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
[Link]("Enter the limit for how many times to print each message: ");
int limit = [Link]();
Thread thread1 = new Thread(new MessageRunnable("Good night", 1000, limit));
Thread thread2 = new Thread(new MessageRunnable("Hello", 2000, limit));
Thread thread3 = new Thread(new MessageRunnable("Word", 3000, limit));
[Link]();
[Link]();
[Link]();

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link]();
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java RunnableExample
Enter the limit for how many times to print each message: 3
Good night
Hello
Good night
World
Good night
Hello
World
Hello
World

Result:
Hence, the program to create threads by extending thread class has been executed
successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

21. Write a program illustrating isAlive and join ().


Aim: To write a program to illustrate isAlive and join().
Program code:
package week7;
import [Link];
class MyThread extends Thread {
public void run() {
[Link]([Link]().getName() + " is starting."); try {
[Link](2000);
} catch (InterruptedException e) {
[Link]([Link]().getName() + " was interrupted.");
}
[Link]([Link]().getName() + " has finished.");
}
}
public class ThreadDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of threads to create: ");
int numberOfThreads = [Link]();
MyThread[] threads = new MyThread[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++) { threads[i] = new MyThread();
threads[i].start();
[Link]("Is " + threads[i].getName() + " alive? " + threads[i].isAlive());
}

for (int i = 0; i < numberOfThreads; i++) {


try {
threads[i].join();
[Link](threads[i].getName() + " has completed execution.");
} catch (InterruptedException e) {
[Link]("Main thread was interrupted.");
}
}
[Link]("All threads have completed execution."); [Link]();
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac [Link]
C:\23-532>java ThreadDemo
Enter the number of threads to create: 3 Thread-0 is starting.
Is Thread-0 alive? true
Is Thread-1 alive? true Is Thread-2 alive? true Thread-1 is starting.
Thread-2 is starting.
Thread-0 has finished.
Thread-0 has completed execution. Thread-1 has finished.
Thread-1 has completed execution. Thread-2 has finished.
Thread-2 has completed execution.
All threads have completed execution

Result:
Hence, the program to illustrate isAlive and join() has been executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

22. Write a Program illustrating Daemon Threads.


Aim: To write a program to illustrate Daemon Threads.
Program code:
package week7;
import [Link];
class DaemonThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Daemon thread is running: " + i);
try {
[Link](500);
} catch (InterruptedException e) {
[Link]("Daemon thread interrupted.");
}
}
[Link]("Daemon thread is exiting.");
}
}
public class DaemonThreadExample {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of iterations for the main thread: "); int
iterations = [Link]();
DaemonThread daemonThread = new DaemonThread();
[Link](true); [Link]();
for (int i = 0; i < iterations; i++) {
[Link]("Main thread is running: " + i); try {
[Link](1000);
} catch (InterruptedException e) {
[Link]("Main thread interrupted.");
}
}
[Link]("Main thread is exiting."); [Link]();
}
}

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

Output:
C:\23-532>javac [Link]
C:\23-532>java DaemonThreadExample
Enter the number of iterations for the main thread: 5
Enter the number of iterations for the main thread: 5
Daemon thread is running: 0
Main thread is running: 0
Daemon thread is running: 1
Main thread is running: 1
Daemon thread is running: 2
Main thread is running: 2
Daemon thread is running: 3
Main thread is running: 3
Daemon thread is running: 4
Main thread is running: 4
Main thread is exiting.

Result:
Hence, the program to illustrate Daemon threads has been executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

23. Write a JAVA program Producer Consumer Problem.


Aim: To write a program producer consumer problem.
Program code:
package week7;
import [Link];
import [Link];
import [Link];
class Buffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int limit;
public Buffer(int limit) {
[Link] = limit;
}
public synchronized void produce(int value) throws InterruptedException {
while ([Link]() == limit) {
wait();
}
[Link](value);
[Link]("Produced: " + value); notifyAll();
}
public synchronized int consume() throws InterruptedException {
while ([Link]()) {
wait();
}
int value = [Link]();
[Link]("Consumed: " + value); notifyAll();
return value;
}
}
class Producer extends Thread {
private final Buffer buffer; private final int itemsToProduce;
public Producer(Buffer buffer, int itemsToProduce) {
[Link] = buffer;
[Link] = itemsToProduce;
}
@Override
public void run() {
for (int i = 0; i < itemsToProduce; i++) {
try {

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link](i);
[Link](100);
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
class Consumer extends Thread {
private final Buffer buffer;
private final int itemsToConsume;
public Consumer(Buffer buffer, int itemsToConsume) { [Link] = buffer;
[Link] = itemsToConsume;
}
@Override
public void run() {
for (int i = 0; i < itemsToConsume; i++) { try {
[Link](); [Link](150);
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of items to produce: ");
int itemsToProduce = [Link]();
[Link]("Enter the number of items to consume: ");
int itemsToConsume = [Link]();
Buffer buffer = new Buffer(5);
Producer producer = new Producer(buffer, itemsToProduce);
Consumer consumer = new Consumer(buffer, itemsToConsume);
[Link]();
[Link]();
try {
[Link]();
[Link]();

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

} catch (InterruptedException e) {
[Link]().interrupt();
}
[Link]("Production and consumption completed.");
[Link]();
}
}

Output:
C:\23-532>javac ProducerConsumerDemo
C:\23-532>java ProducerConsumerDemo
Enter the number of items to produce: 10
Enter the number of items to consume: 10
Produced: 0
Consumed: 0
Produced: 1
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
Produced: 5
Consumed: 3
Produced: 6
Consumed: 4
Produced: 7
Consumed: 5
Produced: 8
Consumed: 6
Produced: 9
Consumed: 7
Consumed: 8
Consumed: 9
Production and consumption completed.

Result:
Hence, the program to solve the producer consumer problem executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

24. Write a java program that connects to a MySql database and Display Table
Details using JDBC.
Aim: To connects to a MySql database and Display Table Details using JDBC.
Program code:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Mysql1
{
public static void main(String[] args)
{
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = " ";
try
{
[Link]("[Link]");
Connection con = [Link](url, user, password);
[Link]("Connected to the database!");
Statement stmt = [Link]();
String query = "SELECT * FROM cricket";
ResultSet rs = [Link](query);
while ([Link]())
{
[Link]([Link](1) + "\t" + [Link](2) + "\t" + [Link](3)+"\t"
+[Link](4) + "\t" + [Link](5));
}
[Link]();
[Link]();
[Link]();
}
catch (Exception e)
{
[Link]("Error: " + [Link]());

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

}
}
}

Output:

Result:
Hence, the program to implement Java Program for to connect to MYSQL and display
the Table has been executed successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

25. Problem Statement: To write a JDBC program to connect MS Access with Insert
values in to it with using IDE.
Aim: To connect MS Access with Insert values in to it with using IDE.
Program Code:
package JDBC;
import [Link];
import [Link];
import [Link];
import [Link];
public class JDBC
{
public static void main(String[] args)
{
try {
[Link]("[Link]");
String url = "jdbc:ucanaccess://D:\\[Link]";
Connection con = [Link](url);
[Link]("Connected to the database Ms Access!");
Statement st = [Link]();
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('1', 'Naveen')");
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('2', 'Vijay')");
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('3', 'Rama')");
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('4', 'Mohith')");
[Link]("INSERT INTO DBTest (ID, Name) VALUES ('5', 'Bhusan')");
String sql = "SELECT * FROM DBTest ";
ResultSet rs = [Link](sql);
[Link]("ID\tName");
while ([Link]())
{
String ID = [Link]("ID");
String Name = [Link]("Name");
[Link](ID + "\t" + Name);
}
[Link]();
[Link]();
[Link]();
} catch (Exception e)
{
[Link]("Error: " + [Link]());

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link]();
}
}
}

Output:

Result:
Hence, the program to connect MS Access with Insert values in to it with using IDE has
been executed Successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

26. To write a JDBC program to connect Oracle with Delete values in to it without
using IDE.
Aim: To connect Oracle with Delete values in to it without using IDE.
Program Code:
import [Link].*;
public class OracleConnect
{
public static void main(String[] args)
{
String url = "jdbc:oracle:thin:@//localhost:1521/xe";
String user = "system";
String password = "root";
try {
[Link]("[Link]");
Connection con = [Link](url, user, password);
[Link]("Connection successful!");
Statement stmt = [Link]();
String deleteSQL = "DELETE FROM employees WHERE EMP_SALARY= 75000";
int rows = [Link](deleteSQL);
if (rows> 0)
{
[Link]("Successfully deleted " + rows + " record(s).");
}
else
{
[Link]("No records found to delete.");
}
ResultSet rs=[Link]("select * from employees");
while([Link]())
{
[Link]([Link](1)+" \t "+[Link](2)+"\t "+[Link](3)+" \t
"+[Link](4));
}

[Link]();
}
catch (ClassNotFoundException e)
{
[Link]("JDBC Driver not found!");

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

[Link]();
} catch (SQLException e)
{
[Link]("Connection failed!");
[Link]();
}
}
}

Output:
C:\23-532>javac [Link]
C:\23-532>java OracleConnect
Connection successful!
Successfully deleted 2 record(s).
3 Chary 65000 IT
2 Sunil 70000 CSE

Result:
Hence, the program to connect Oracle with Insert values in to it without using IDE has
been executed Successfully.

OOPS through JAVA CSE Dept


Date: Exp No: Page no:

OOPS through JAVA CSE Dept

You might also like