0% found this document useful (0 votes)
10 views58 pages

SOFT

Java is a class-based, object-oriented programming language designed for platform independence, allowing developers to write once and run anywhere. The document covers Java's history, features, data types, and provides examples of various Java programs including displaying default values of data types, solving quadratic equations, performing binary search, bubble sort, and using StringBuffer. Additionally, it explains the Java Development Kit (JDK) and the differences between JDK and JRE.

Uploaded by

Praveena
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)
10 views58 pages

SOFT

Java is a class-based, object-oriented programming language designed for platform independence, allowing developers to write once and run anywhere. The document covers Java's history, features, data types, and provides examples of various Java programs including displaying default values of data types, solving quadratic equations, performing binary search, bubble sort, and using StringBuffer. Additionally, it explains the Java Development Kit (JDK) and the differences between JDK and JRE.

Uploaded by

Praveena
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/ 58

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
8. Portability
9. High Performance

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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

JAVA DATATYPES:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 to 16 decimal digits

boolean 1 bit Stores true or false values


char 2 bytes Stores a single character/letter or ASCII values

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

PATH AND CLASS PATH:

S.
No. PATH CLASSPATH

An environment variable is used by the operating An environment variable is used by the Java
1.
system to find the executable files. compiler to find the path of classes.

PATH setting up an environment for the operating


Classpath setting up the environment for
2. system. Operating System will look in this PATH for
Java. Java will use to find compiled classes.
executables.

3. Refers to the operating system. Refers to the Developing Environment.

In classpath, we must place .\lib\jar file or


4. In path variable, we must place .\bin folder path
directory path in which .java file is available.

CLASSPATH is used by the compiler and JVM


5. PATH is used by CMD prompt to find binary files.
to find library files.

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

1.Write 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)
{
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:
C:\23-518>javac DataType.java
C:\23-518>java DataType
The default values of primitive data types are:
Byte :0

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Short :0
Int :0
Long :0
Float :0.0
Double :0.0
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:

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

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Sample Output:
C:\23-515>javac quardraticformula.java
C:\23-515>java quadraticformula
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
Executed Output:
C:\23-515>javac quardraticformula.java
C:\23-515>java quadraticformula
Given quadratic equation: ax^2 + bx + c
Enter a: 1
Enter b: -3
Enter c: 2
Roots are real and unequal
First root is: 2.0
Second root is: 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:

3.Write 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 java.util.*;
class BinarySearch
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int size = scanner.nextInt();
int array[] = new int[size];
System.out.println("Enter the elements of the array :");
for (int i = 0; i < size; i++)
{
array[i] = scanner.nextInt();
}
System.out.print("Enter the value to search for: ");
int target = scanner.nextInt( );
int result = binarySearch(array, target);
if (result != -1)
{
System.out.println("Element found at index: " + result);
}
else
{
System.out.println("Element not found in the array.");
}

scanner.close( );
}
public static int binarySearch(int[] array, int target)
{
int low = 0;
int high = array.length - 1;

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

while (low <= high)


{
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;
}
}

Sample Output:
C:\23-515>javac BinarySearch.java
C:\23-515>java BinarySearch
Enter the number of elements in the array: 5
Enter the elements of the array :
1
3
5
7
9
Enter the value to search for: 5
Element found at index: 2
Executed Output:
C:\23-515>javac BinarySearch.java
C:\23-515>java BinarySearch
Enter the number of elements in the array: 6
Enter the elements of the array :
10
20
30
40

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

50
60
Enter the value to search for: 25
Element not found in the array.
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 java.util.*;
public class BubbleSort
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of elements: ");
int n = scanner.nextInt( );
int arr[] = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++)
{
arr[i] = scanner.nextInt( );
}
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;
}
}
}
System.out.println("Sorted Array:");
for (int i = 0; i < n; i++)
{
System.out.println( " \n"+arr[i] );
}
}
}

Output:

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

C:\23-515>javac BubbleSort.java
C:\23-515>java BubbleSort
Enter the number of elements:
5
Enter 5 elements:
64
34
25
12
22
Sorted Array:
12
22
25
34
64

Result:
Hence, the program to sort for an element in a given list of elements
using bubble sort executed successfully.

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


character.

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Aim: StringBuffer to delete, remove character.


Program code:
import java.util.Scanner;
public class StringBufferExample
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print(“Enter any string: “);
String str = scanner.nextLine( );
StringBuffer s = new StringBuffer(str);
System.out.println(“\nOriginal StringBuffer: “ + s);
s.delete(2, 5);
System.out.println(“\nAfter deleting substring from index 2 to 5: \n” +
s);
s.deleteCharAt(0);
System.out.println(“\nAfter deleting character at index 0: “ + s);
scanner.close( );
}
}
Sample Output:
C:\23-515>javac StringBufferExample.java
C:\23-515>java StringBufferExample
Enter any string: HelloWorld
Original StringBuffer: HelloWorld
After deleting substring from index 2 to 5: HeWorld
After deleting character at index 0: eWorld
Executed Output:
Enter any string: JavaProgramming
Original StringBuffer: JavaProgramming
After deleting substring from index 2 to 5: JaProgramming
After deleting character at index 0: aProgramming

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 java.util.*;
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)
{
System.out.println("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(System.in);
System.out.println("Enter any Two values : ");
int a = sc.nextInt( );
int b = sc.nextInt( );
System.out.println("Addition of " + a + " and " + b + ": " +
calc.add(a, b));

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

System.out.println("Subtraction of " + a + " and " + b + ": " +


calc.subtract(a, b));
System.out.println("Multiplication of " + a + " and " + b + ": " +
calc.multiply(a, b)); System.out.println("Division of " + a + " and " +
b + ": " + calc.divide(a, b));
}
}

Sample Output:
C:\23-515>javac Calculator1.java
C:\23-515>java Calculator1
Enter any Two values :
10
5
Addition of 10 and 5: 15
Subtraction of 10 and 5: 5
Multiplication of 10 and 5: 50
Division of 10 and 5: 2.0
Executed Output:
Enter any Two values :
8
0
Addition of 8 and 0: 8
Subtraction of 8 and 0: 8
Multiplication of 8 and 0: 0
Error: Division by zero is not allowed.
Division of 8 and 0: 0.0
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( );
System.out.println("\nSum of two integers: " + over.add(15, 20));
System.out.println("\nSum of two doubles: " + over.add(11.5,
20.5));
System.out.println("\nSum of three integers: " + over.add(10, 20,
30));
}
}

Output:
C:\23-515>javac MethodOverloading1.java
C:\23-515>java MethodOverloading1
Sum of two integers: 35
Sum of two doubles: 32.0
Sum of three integers: 60
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()
{
System.out.println("Default constructor called");
}
public Person(String name, int age)
{
this.name = name; // 'this' keyword refers to the current object

this.age = age;
System.out.println("Parameterized constructor called");
}
public Person(Person p)
{
this.name = p.name;
this.age = p.age;
System.out.println("Copy Constructor called");
}
public void display( )
{
System.out.println("Name: " + name +" \t" +", Age: " + age);
}
}

public class Constructor


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

Person p1 = new Person();


p1.display();

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Person p2 = new Person("Ramyasree", 25);


p2.display();
Person p3 = new Person(p2);
p3.display();
}
}
Output:
C:\23-515>javac Constructor.java
C:\23-515>java Constructor
Default constructor called
Name: null , Age: 0
Parameterized constructor called
Name: Ramyasree , Age: 25
Copy Constructor called
Name: Ramyasree , Age: 25

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";
System.out.println("Default Constructor called");
}
public Student(String name, int age)
{ this.name = name; this.age = age; course = "Not
Enrolled";
System.out.println("Constructor with two parameters called");
}
public Student(String name, int age, String course)
{
this.name = name; this.age = age; this.course = course;
System.out.println("Constructor with three parameters called");
}
public void display( )
{
System.out.println("Name: " + name + "\t " +", Age: " + "\t " + age
+ ", Course: " + course);
}
} public class ConstructorOverloading
{ public static void main(String args[])
{
Student student1 = new Student(); student1.display( );
Student student2 = new Student("Charitha", 5);
student2.display( );
Student student3 = new Student("Bobby", 22, "Computer Science");
Student3.display();
}
}

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Output:
C:\23-515>javac ConstructorOverloading.java
C:\23-515>java ConstructorOverloading
Default Constructor called
Name: Praveena , Age: 0, Course: Not Enrolled
Constructor with two parameters called
Name: Charitha , Age: 5, Course: Not Enrolled
Constructor with three parameters called
Name: Bobby , Age: 22, 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( )
{
System.out.println("Value of a is " + a);
}
}
public class SingleInheritance
{
public static void main(String[] args)
{
ChildClass obj = new ChildClass();
obj.setData(10);
obj.showData( );
}
}
Output:
C:\23-515>javac SingleInheritance.java
C:\23-515>java SingleInheritance
Value of a is 10
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( )
{
System.out.println("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass
{
void display( )
{
System.out.println("Inside ChildChildClass!");
}
}
public class Multilevel Inheritance
{
public static void main(String[] args)
{
ChildChildClass obj = new ChildChildClass();
obj.setData(100);
obj.showData();
obj.display();
}
}

Output:
C:\23-515>javac Multilevel Inheritance.java
C:\23-515>java Multilevel Inheritance

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Value of a is 100
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)
{
this.radius = radius;
}
@Override
double calculateArea( )
{
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape
{
double length;
double width;
public Rectangle(double length, double width)
{
this.length = length;
this.width = 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:

{
this.base = base;
this.height = 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(4, 6);
Shape triangle = new Triangle(3, 8);
System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Rectangle: " +
rectangle.calculateArea());
System.out.println("Area of Triangle: " + triangle.calculateArea());
}
}
Output:
C:\23-515>javac AbstractClass.java
C:\23-515>java AbstractClass
Area of Circle: 78.53981633974483
Area of Rectangle: 24.0
Area of Triangle: 12.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( )
{
System.out.println ("Person class Constructor");
}
}
class Student extends Person
{
Student()
{
super( );
System.out.println("Student class Constructor");
}
}

class SuperDemo
{
public static void main(String[] args)
{
Student s = new Student( );
}
}
Output:
C:\23-515>javac SuperDemo.java
C:\23-515>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( )
{
System.out.println("Animal is eating");
} public void travel( )
{
System.out.println("Animal is travelling");
}
}

public class InterfaceDemo


{ public static void main(String args[])
{
Animal a = new Animal( );
a.eat( );
a.travel( );
}
}
Output:
C:\23-515>javac InterfaceDemo.java
C:\23-515>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()
{
System.out.println("Animal makes a sound");
}
} class Dog extends Animal
{
@Override
void sound ( )
{
System.out.println("Dog barks");
}
}
class Cat extends Animal
{
void sound( )
@Override
{
System.out.println("Cat meows");
}
}
public class RuntimePolymorphism
{
public static void main(String[] args)
{
Animal myAnimal = new Dog( );
myAnimal.sound( );
myAnimal = new Cat( );
myAnimal.sound( );
}
}

Output:
C:\23-515>javac RuntimePolymorphism.java
C:\23-515>java RuntimePolymorphism

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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 java.util.Scanner;
class WeightLimitExceeded extends Exception {
WeightLimitExceeded(int weight) {
super("Weight limit exceeded by " + Math.abs(15 - weight) + " kg");
}
}

public class Main {

void validWeight(int weight) throws WeightLimitExceeded {


if (weight > 15) {
throw new WeightLimitExceeded(weight);
} else {
System.out.println("You are ready to fly!");
}
}

public static void main(String[] args) {


Main ob = new Main();
Scanner in = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
System.out.print("Enter weight: ");
try {
int weight = in.nextInt();
ob.validWeight(weight);
} catch (WeightLimitExceeded e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("Invalid input. Please enter a valid integer.");
in.next();
}
}
in.close();
}
}

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Output:
C:\23-515>javac Main.java
C:\23-515>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.

17.Write a JAVA program Illustrating Multiple catch clauses.

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Aim: To write a program to illustrate multiple catch clauses.


Program code:
package week6;
import java.util.Scanner;

public class MultipleCatchExample {


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

System.out.println("Enter two integers to divide:");

try {
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int result = num1 / num2;
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
catch (java.util.InputMismatchException e) {
System.out.println("Error: Please enter valid integers.");
}
catch (Exception e) {
System.out.println("Error: An unexpected error occurred: " +
e.getMessage());
}
finally {
scanner.close();
}
}
}

Output:
C:\23-515>javac MultipleCatchExample.java
C:\23-515>java MultipleCatchExample
Enter two integers to divide:
10
2
Result: 5

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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

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


Aim: To write a program to create java built-in exceptions.

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Program code:
package week6;
public class BuiltInExceptionsExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Division by zero is not
allowed.");
}
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException: Attempted to access a
method on a null object.");
}

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

Output:
C:\23-515>javac BuiltInExceptionsExample.java
C:\23-515>java BuiltInExceptionsExample

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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.

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

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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 {
System.out.println("Age is valid: " + age);
}
}

public static void main(String[] args) {


try {
checkAge(25);
checkAge(-5);
} catch (InvalidAgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}

try {
checkAge(200);
} catch (InvalidAgeException e) {
System.out.println("Caught exception: " + e.getMessage());
}
}
}

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

Age is valid: 25

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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.

20. Write a JAVA program that creates threads by extending


Thread class. First thread display “Good Morning “every 1 sec,

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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 java.util.Scanner;
class MessageRunnable implements Runnable {
private String message;
private int interval;
private int count;
public MessageRunnable(String message, int interval, int count) {
this.message = message;
this.interval = interval;
this.count = count;
}
public void run() {
for (int i = 0; i < count; i++) {
try {
Thread.sleep(interval);
System.out.println(message);
} catch (InterruptedException e) {
System.out.println(message + " Thread interrupted");
}
}
}
}

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


Scanner scanner = new Scanner(System.in);
System.out.print("Enter the limit for how many times to print each
message: "); int limit = scanner.nextInt();
Thread thread1 = new Thread(new MessageRunnable("Good
Morning", 1000, limit));
Thread thread2 = new Thread(new MessageRunnable("Hello", 2000,
limit));
Thread thread3 = new Thread(new MessageRunnable("Welcome",
3000, limit));
thread1.start();
thread2.start();

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

thread3.start();

scanner.close();
}
}
Output:
C:\23-515>javac RunnableExample.java
C:\23-515>java RunnableExample
Enter the limit for how many times to print each message: 2
Good Morning
Hello
Good Morning
Welcome
Hello
Welcome
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 java.util.Scanner;
class MyThread extends Thread {
public void run() {
System.out.println(Thread.currentThread().getName() + " is
starting."); try {
Thread.sleep(2000);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " was
interrupted.");
}
System.out.println(Thread.currentThread().getName() + " has
finished.");
}
}
public class ThreadDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of threads to create: ");
int numberOfThreads = scanner.nextInt();
MyThread[] threads = new MyThread[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++) { threads[i] = new
MyThread(); threads[i].start();
System.out.println("Is " + threads[i].getName() + " alive? " +
threads[i].isAlive());
}

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


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

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

System.out.println("All threads have completed execution.");


scanner.close();
}
}

Output:
C:\23-515>javac ThreadDemo.java
C:\23-515>java ThreadDemo
Enter the number of threads to create: 2
Thread-0 is starting.
Thread-1 is starting.
Is Thread-0 alive? true
Is Thread-1 alive? true
Thread-0 has finished.
Thread-1 has finished.
Thread-0 has completed execution.
Thread-1 has completed execution.
All threads have completed execution.
Executed Output:
Enter the number of threads to create: 3
Thread-0 is starting.
Thread-1 is starting.
Thread-2 is starting.
Is Thread-0 alive? true
Is Thread-1 alive? true
Is Thread-2 alive? true
Thread-0 has finished.
Thread-1 has finished.
Thread-2 has finished.
Thread-0 has completed execution.
Thread-1 has completed execution.
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 java.util.Scanner;
class DaemonThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Daemon thread is running: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Daemon thread interrupted.");
}
}
System.out.println("Daemon thread is exiting.");
}
}
public class DaemonThreadExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of iterations for the main
thread: ");
int iterations = scanner.nextInt();
DaemonThread daemonThread = new DaemonThread();
daemonThread.setDaemon(true);
daemonThread.start();
for (int i = 0; i < iterations; i++) {
System.out.println("Main thread is running: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

}
System.out.println("Main thread is exiting.");
scanner.close();
}
}

Output:
C:\23-515>javac DaemonThreadExample.java
C:\23-515>java DaemonThreadExample
Enter the number of iterations for the main thread: 5
Main thread is running: 0
Daemon thread is running: 0
Main thread is running: 1
Daemon thread is running: 1
Main thread is running: 2
Daemon thread is running: 2
Main thread is running: 3
Daemon thread is running: 3
Main thread is running: 4
Daemon 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 java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Buffer {
private final Queue<Integer> queue = new LinkedList<>();
private final int limit;
public Buffer(int limit) {
this.limit = limit;
}
public synchronized void produce(int value) throws
InterruptedException {
while (queue.size() == limit) {
wait();
}
queue.add(value);
System.out.println("Produced: " + value); notifyAll();
}
public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
wait();
}
int value = queue.remove();
System.out.println("Consumed: " + value); notifyAll();
return value;
}
}
class Producer extends Thread {
private final Buffer buffer; private final int itemsToProduce;
public Producer(Buffer buffer, int itemsToProduce) {
this.buffer = buffer;

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Consumer consumer = new Consumer(buffer, itemsToConsume);


producer.start();
consumer.start();
try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Production and consumption completed.");
scanner.close();
}
}
Output:
C:\23-515>javac ProducerConsumerDemo
C:\23-515>java ProducerConsumerDemo
Enter the number of items to produce: 5
Enter the number of items to consume: 8
Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
Produced: 3
Consumed: 3
Produced: 4
Consumed: 4
Consumed: 5
Consumed: 6
Consumed: 7
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 com.example.mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Mysql1
{
public static void main(String[] args)
{
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = " ";
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user,
password);
System.out.println("Connected to the database!");
Statement stmt = con.createStatement();
String query = "SELECT * FROM cricket";
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println(rs.getString(1) + "\t" + rs.getString(2) + "\t" +
rs.getString(3)+"\t" +rs.getString(4) + "\t" + rs.getString(5));
}

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

rs.close();
stmt.close();
con.close();
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
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 java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class JDBC
{
public static void main(String[] args)
{
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String url = "jdbc:ucanaccess://D:\\Database1.accdb";
Connection con = DriverManager.getConnection(url);
System.out.println("Connected to the database Ms Access!");
Statement st = con.createStatement();
st.executeUpdate("INSERT INTO DBTest (ID, Name) VALUES ('1',
'Naveen')");
st.executeUpdate("INSERT INTO DBTest (ID, Name) VALUES ('2',
'Vijay')");
st.executeUpdate("INSERT INTO DBTest (ID, Name) VALUES ('3',
'Rama')");
st.executeUpdate("INSERT INTO DBTest (ID, Name) VALUES ('4',
'Mohith')");
st.executeUpdate("INSERT INTO DBTest (ID, Name) VALUES ('5',
'Bhusan')");
String sql = "SELECT * FROM DBTest ";
ResultSet rs = st.executeQuery(sql);
System.out.println("ID\tName");

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

while (rs.next())
{
String ID = rs.getString("ID");
String Name = rs.getString("Name");
System.out.println(ID + "\t" + Name);
}
rs.close();
st.close();
con.close();
} catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
Output:

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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

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 java.sql.*;
public class OracleConnect
{
public static void main(String[] args)
{
String url = "jdbc:oracle:thin:@//localhost:1521/xe";
String user = "system";
String password = "root";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(url, user,
password);
System.out.println("Connection successful!");
Statement stmt = con.createStatement();
String deleteSQL = "DELETE FROM employees WHERE
EMP_SALARY= 75000";

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

int rows = stmt.executeUpdate(deleteSQL);


if (rows> 0)
{
System.out.println("Successfully deleted " + rows + "
record(s).");
}
else
{
System.out.println("No records found to delete.");
}
ResultSet rs=stmt.executeQuery("select * from employees");
while(rs.next())
{
System.out.println(rs.getString(1)+" \t "+rs.getString(2)+"\t
"+rs.getString(3)+" \t "+rs.getString(4));
}

con.close();
}
catch (ClassNotFoundException e)
{
System.out.println("JDBC Driver not found!");
e.printStackTrace();
} catch (SQLException e)
{
System.out.println("Connection failed!");
e.printStackTrace();
}
}
}
Output:
C:\23-518>javac OracleConnect.java
C:\23-518>java OracleConnect
Connection successful!
Successfully deleted 2 record(s).
3 Chary 65000 IT
2 Sunil 70000 CSE

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

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

PROJECT TITTLE :
A basic console-based To-Do List where users can add, view, and remove
tasks. The tasks are stored in a list, and the user interacts with the app
via a simple text menu.

PROJECT DESCRIPTION :
The To-Do List application is designed for users who need a
straightforward and easy way to track and manage their daily tasks
without a graphical user interface. It runs entirely in the console, making
it lightweight and simple to use. The tasks are stored in a list (usually in
memory or a simple text file), and users can interact with the program by
typing commands into a text-based menu.

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

Team Members:
 K V. NANDA PRIYA(23191A0507)
 S. PRAVEENA(23191A0515)

Roles of TeamMembers:
 K V. NANDA PRIYA -Project researcher
 S. PRAVEENA -Debug the code

Aim:
The aim of a basic console-based To-Do List application is to provide users
with a simple, text-based tool for managing their tasks and improving
their productivity.

Program:
import java.util.ArrayList;
import java.util.Scanner;
public class TodoApp
private static ArrayList<String> todoList = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n------ To-Do List App ------");
System.out.println("1. Add a Task");

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

System.out.println("2. View All Tasks");


System.out.println("3. Remove a Task");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine();
switch (choice) {
case 1:
addTask(scanner);
break;
case 2:
viewTasks();
break;
case 3:
removeTask(scanner);
break;
case 4:
System.out.println("Exiting the application. Goodbye!");
scanner.close();
return;
default:
System.out.println("Invalid choice! Please enter a number
between 1 and 4.");
}
}
}
private static void addTask(Scanner scanner) {
System.out.print("Enter the task description: ");
String task = scanner.nextLine();
todoList.add(task);
System.out.println("Task added successfully!");
}
private static void viewTasks() {
if (todoList.isEmpty()) {
System.out.println("No tasks in the list.");
} else {
System.out.println("\nYour To-Do List:");
for (int i = 0; i < todoList.size(); i++) {
System.out.println((i + 1) + ". " + todoList.get(i));
}

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

}
}
private static void removeTask(Scanner scanner) {
if (todoList.isEmpty()) {
System.out.println("No tasks to remove.");
return;
}
System.out.print("Enter the task number to remove: ");
int taskNumber = scanner.nextInt();
scanner.nextLine();
if (taskNumber > 0 && taskNumber <= todoList.size()) {
todoList.remove(taskNumber - 1);
System.out.println("Task removed successfully.");
} else {
System.out.println("Invalid task number!");
}
}
}

OUTPUT:

------ To-Do List App ------


1. Add a Task
2. View All Tasks
3. Remove a Task
4. Exit
Enter your choice: 1
Enter the task description: Buy groceries
Task added successfully!

------ To-Do List App ------


1. Add a Task
2. View All Tasks
3. Remove a Task
4. Exit
Enter your choice: 2

Your To-Do List:


1. Buy groceries

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

------ To-Do List App ------


1. Add a Task
2. View All Tasks
3. Remove a Task
4. Exit
Enter your choice: 3
Enter the task number to remove: 1
Task removed successfully.

------ To-Do List App ------


1. Add a Task
2. View All Tasks
3. Remove a Task
4. Exit
Enter your choice: 4
Exiting the application. Goodbye!

Result:

The result of developing a basic console-based To-Do List application is a


functional and straightforward tool that enables users to efficiently
manage and track their tasks through a simple text interface

FUTURE SCOPE:
The future scope of the basic console-based To-Do List app includes
features like task categorization, due dates, reminders, cloud syncing,
collaboration, mobile apps, and AI-driven task prioritization to enhance
functionality and user experience.

CONCLUSION:
In conclusion, the basic console-based To-Do List app provides a simple
yet effective way for users to manage their tasks, and with the addition of
features like data persistence, categorization, reminders, cloud syncing,
and AI enhancements, it can evolve into a more powerful and versatile
tool for personal productivity and collaboration. Its scalability and
potential for integration with other platforms make it an ideal foundation
for future development.

OOPS THROUGH JAVA CSE DEPT


Date: Exp No:
Page no:

OOPS THROUGH JAVA CSE DEPT

You might also like