0% found this document useful (0 votes)
14 views72 pages

Sample Experiments-2

Java programming

Uploaded by

ajaygutthaajay
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)
14 views72 pages

Sample Experiments-2

Java programming

Uploaded by

ajaygutthaajay
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/ 72

EXERCISE -1

A). Write a JAVA program to display default values of all primitive data
type of java.

public class DefaultValues {


// Declare variables of each primitive data type
static byte defaultByte;
static short defaultShort;
static int defaultInt;
static long defaultLong;
static float defaultFloat;
static double defaultDouble;
static char defaultChar;
static boolean defaultBoolean;

public static void main(String[] args) {


// Display the default values of each primitive data type
System.out.println("Default values of primitive data type in Java:");
System.out.println("byte: " + defaultByte);
System.out.println("short: " + defaultShort);
System.out.println("int: " + defaultInt);
System.out.println("long: " + defaultLong);
System.out.println("float: " + defaultFloat);
System.out.println("double: " + defaultDouble);
System.out.println("char: '" + defaultChar + "'");
System.out.println("boolean: " + defaultBoolean);
}
}

Expected output:

Default values of primitive data types in Java:


byte: 0
short: 0
int: 0
long: 0
float: 0.0
double: 0.0
char: ''
boolean: false
Notes:

Primitive Data Types: 8

1. int - Integer numbers (e.g., 1, -3)


2. double - Decimal numbers (e.g., 3.14, -0.001)
3. char - Single character (e.g., 'a', 'Z')
4. Boolean - True or false values (e.g., `true`, `false`)
5. byte - Small integer (-128 to 127)
6. short - Small integer (-32,768 to 32,767)
7. long - Large integer
8. float - Decimal numbers (less precision than double)

Non-Primitive Data Types:

1. String - Text (e.g., "Hello")


2. Arrays - Collection of items (e.g., int[ ] numbers = {1, 2, 3};)
3. Classes - Custom data types you define (e.g., objects)
4. Interfaces - Define methods that other classes can implement
5. Enums - Lists of constants (e.g., Days of the week)

These are the basic building blocks for handling data in Java
EXERCISE -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.

import java.util.Scanner;

public class QuadraticEquationSolver {

public static void main(String[] args) {


Scanner = new Scanner(System.in);

// Input coefficients a, b, and c


System.out.print("Enter coefficient a: ");
double a = scanner.nextDouble();

System.out.print("Enter coefficient b: ");


double b = scanner.nextDouble();

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


double c = scanner.nextDouble();

// Calculate the discriminant D


double discriminant = b * b - 4 * a * c;
System.out.println("Discriminant (D) = " + discriminant);

// Determine the nature of the roots based on D


if (discriminant > 0) {
// Two distinct real roots
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The equation has two distinct real roots:");
System.out.println("Root 1 = " + root1);
System.out.println("Root 2 = " + root2);
} else if (discriminant == 0) {
// Two equal real roots (one root)
double root = -b / (2 * a);
System.out.println("The equation has two equal real roots:");
System.out.println("Root = " + root);
} else {
// Two complex roots
double realPart = -b / (2 * a);
double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
System.out.println("The equation has two complex roots:");
System.out.println("Root 1 = " + realPart + " + " + imaginaryPart +
"i");
System.out.println("Root 2 = " + realPart + " - " + imaginaryPart + "i");
}

scanner.close();
}
}
Expected output:

Enter coefficient a: 2
Enter coefficient b: 4
Enter coefficient c: 0
Discriminant (D) = 16.0
The equation has two distinct real roots:
Root 1 = 0.0
Root 2 = -2.0

Note

The discriminant helps you figure out how many solutions a quadratic equation
has and what kind they are. For an equation like:
Ax2 + bx +c = 0
The discriminant is:
Δ = b2 – 4ac
What It Means:
 If Δ > 0: There are two different real solutions.
 If Δ = 0: There is one real solution.
 If Δ < 0: There are no real solutions (solutions are complex).
It’s a quick way to know the type and number of solutions without solving the
whole equation!
EXERCISE -2

A) Write a JAVA program to search for an element in a given list of


elements using binary search mechanism.

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearchExample {

// Binary search method


public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2; // Avoids overflow

if (array[mid] == target) {
return mid; // Return the index of the target
}

// If target is greater, ignore the left half


if (array[mid] < target) {
left = mid + 1;
} else {
// If target is smaller, ignore the right half
right = mid - 1;
}
}

// Target not found


return -1;
}

public static void main(String[] args) {


Scanner = new Scanner(System.in);

// Input the number of elements


System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

// Input the elements of the array


int[] array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}

// Input the target value to search for


System.out.print("Enter the target element to search for: ");
int target = scanner.nextInt();

// Sort the array before performing binary search


Arrays.sort(array);
System.out.println("Sorted array: " + Arrays.toString(array));

// Perform binary search


int result = binarySearch(array, target);

// Display the result


if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found in the array.");
}

scanner.close();
}
}
Expected output:

Case i:
Enter the number of elements in the array: 6
Enter the elements of the array:
123456
Enter the target element to search for: 8
Sorted array: [1, 2, 3, 4, 5, 6]
Element not found in the array.

Case ii:

Enter the number of elements in the array: 6


Enter the elements of the array:
123456
Enter the target element to search for: 5
Sorted array: [1, 2, 3, 4, 5, 6]
Element found at index: 4
EXERCISE -2

B) Write a JAVA program to sort for an element in a given list of elements


using bubble sort.

import java.util.Scanner;

public class BubbleSortProgram {

// Bubble sort method


public static void bubbleSort(int[] array) {
int n = array.length;
boolean swapped;

// Loop through each element in the array


for (int i = 0; i < n - 1; i++) {
swapped = false;

// Compare adjacent elements and swap if needed


for (int j = 0; j < n - 1 - i; j++) {
if (array[j] > array[j + 1]) {
// Swap the elements
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;

// Mark as swapped
swapped = true;
}
}

// If no elements were swapped, the array is already sorted


if (!swapped) {
break;
}
}
}

public static void main(String[] args) {


Scanner = new Scanner(System.in);

// Input the number of elements


System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();

// Input the elements of the array


int[] array = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
array[i] = scanner.nextInt();
}
bubbleSort(array);

// Display the sorted array


System.out.println("Sorted array using bubble sort:");
for (int i = 0; i < n; i++) {
System.out.print(array[i] + " ");
}

scanner.close();
}
}

Expected output:

Enter the elements of the array:


36
35
96
11
24
Sorted array using bubble sort:
11 24 35 36 96
EXERCISE -2

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

import java.util.Scanner;

public class StringBufferExample {

public static void main(String[] args) {


Scanner = new Scanner(System.in);

// Input the string


System.out.print("Enter a string: ");
String input = scanner.nextLine();

// Create a StringBuffer object with the input string


StringBuffer = new StringBuffer(input);

// Display the original string


System.out.println("Original String: " + stringBuffer);

// Demonstrate deleting a substring


System.out.print("Enter start index to delete from: ");
int startIndex = scanner.nextInt();
System.out.print("Enter end index to delete to: ");
int endIndex = scanner.nextInt();
// Delete substring from start index to end index
if (startIndex >= 0 && endIndex <= stringBuffer.length() && startIndex
< endIndex) {
stringBuffer.delete(startIndex, endIndex);
System.out.println("String after deletion: " + stringBuffer);
} else {
System.out.println("Invalid indices for deletion.");
}

// Demonstrate removing a specific character


System.out.print("Enter the index of the character to remove: ");
int charIndex = scanner.nextInt();

// Delete character at the specified index


if (charIndex >= 0 && charIndex < stringBuffer.length()) {
stringBuffer.deleteCharAt(charIndex);
System.out.println("String after removing character: " + stringBuffer);
} else {
System.out.println("Invalid index for removing character.");
}

scanner.close();
}
}
Expected output:

Enter a string: EXAMPLE


Original String: EXAMPLE
Enter start index to delete from: 5
Enter end index to delete to: 7
String after deletion: EXAMP
Enter the index of the character to remove: 2
String after removing character: EXMP
EXERCISE -3

A) Write a JAVA program to implement class mechanism. Create a class,


methods and invoke them inside main method.

// Define the Rectangle class


class Rectangle {
// Fields (attributes) of the class
private double length;
private double width;

// Constructor to initialize the Rectangle object


public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Method to calculate the area of the rectangle


public double calculateArea() {
return length * width;
}

// Method to calculate the perimeter of the rectangle


public double calculatePerimeter() {
return 2 * (length + width);
}

// Method to display the dimensions of the rectangle


public void displayDimensions() {
System.out.println("Length: " + length + ", Width: " + width);
}
}

// Main class to run the program


public class RectangleDemo {
public static void main(String[] args) {
// Create an object of the Rectangle class
Rectangle rect = new Rectangle(5.0, 3.0);

// Invoke methods of the Rectangle class


rect.displayDimensions();
double area = rect.calculateArea();
double perimeter = rect.calculatePerimeter();

// Display the results


System.out.println("Area of the rectangle: " + area);
System.out.println("Perimeter of the rectangle: " + perimeter);
}
}
Expected output:

Length: 5.0, Width: 3.0


Area of the rectangle: 15.0
Perimeter of the rectangle: 16.0
EXERCISE -3

B) Write a JAVA program implement method overloading.

// Define a class named MathOperations


class MathOperations {

// Overloaded method to add two integers


public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two double values


public double add(double a, double b) {
return a + b;
}

// Overloaded method to concatenate two strings


public String add(String a, String b) {
return a + b;
}
}

// Main class to demonstrate method overloading


public class MethodOverloadingDemo {
public static void main(String[] args) {
// Create an object of the MathOperations class
MathOperations operations = new MathOperations();

// Invoke overloaded methods


int sum1 = operations.add(5, 10); // Calls the method with two int
parameters
int sum2 = operations.add(5, 10, 15); // Calls the method with three
int parameters
double sum3 = operations.add(5.5, 10.5); // Calls the method with two
double parameters
String concat = operations.add("Hello, ", "World!"); // Calls the method
with two String parameters

// Display the results


System.out.println("Sum of two integers: " + sum1);
System.out.println("Sum of three integers: " + sum2);
System.out.println("Sum of two doubles: " + sum3);
System.out.println("Concatenation of two strings: " + concat);
}
}
Expected output:

Sum of two integers: 15


Sum of three integers: 30
Sum of two doubles: 16.0
Concatenation of two strings: Hello, World!
EXERCISE -3

C) Write a JAVA program to implement constructor.

// Define the Person class


class Person {
// Instance variables
String name;
int age;

// Constructor to initialize the Person object


Person(String name, int age) {
this.name = name;
this.age = age;
}

// Method to display the details of the Person


void display() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}

// Main class to run the program


public class Main {
public static void main(String[] args) {
// Creating a new Person object using the constructor
Person person1 = new Person("Alice", 25);

// Display the details of the Person object


person1.display();
}
}

Expected output:

Name: Alice
Age: 25
EXERCISE -3

D) Write a JAVA program to implement constructor overloading.

// Define the Rectangle class


class Rectangle {
// Instance variables
double length;
double width;

// Constructor with no parameters (default constructor)


Rectangle() {
this.length = 1.0; // Default length
this.width = 1.0; // Default width
}

// Constructor with one parameter (square constructor)


Rectangle(double side) {
this.length = side;
this.width = side;
}

// Constructor with two parameters (rectangle constructor)


Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Method to calculate the area of the rectangle
double calculateArea() {
return length * width;
}

// Method to display the dimensions and area of the rectangle


void display() {
System.out.println("Length: " + length + ", Width: " + width);
System.out.println("Area: " + calculateArea());
}
}

// Main class to run the program


public class Constructoroverloadingexample{
public static void main(String[] args) {
// Creating Rectangle objects using different constructors
Rectangle rect1 = new Rectangle(); // Uses the default constructor
Rectangle rect2 = new Rectangle(5.0); // Uses the square constructor
Rectangle rect3 = new Rectangle(4.0, 6.0); // Uses the rectangle
constructor

// Display the details of each rectangle


System.out.println("Rectangle 1:");
rect1.display();

System.out.println("\nRectangle 2:");
rect2.display();
System.out.println("\nRectangle 3:");
rect3.display();
}
}

Expected output:

Rectangle 1:
Length: 1.0, Width: 1.0
Area: 1.0

Rectangle 2:
Length: 5.0, Width: 5.0
Area: 25.0

Rectangle 3:
Length: 4.0, Width: 6.0
Area: 24.0
EXERCISE -4

A) Write a JAVA program to implement Single Inheritance.

// Parent class
class Animal {
// Method in the parent class
void eat() {
System.out.println("The animal eats food.");
}
}

// Child class that inherits from Animal


class Dog extends Animal {
// Method in the child class
void bark() {
System.out.println("The dog barks.");
}

public void breathe() {


// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method
'breathe'");
}
}

// Main class to run the program


public class SingleInheritanceDemo {
public static void main(String[] args) {
// Creating an object of the Dog class
Dog myDog = new Dog();

// Calling methods from both the parent class and child class
myDog.eat(); // Method from the Animal class
myDog.bark(); // Method from the Dog class
}
}

Expected output:

The animal eats food.


The dog barks.
EXERCISE -4

B) Write a JAVA program to implement Multi level Inheritance.

// Base class
class Animals {
// Method in the base class
void eat() {
System.out.println("The animal eats.");
}
}

// Derived class from Animal


class Mammal extends Animals {
// Method in the derived class
void breathe() {
System.out.println("The mammal breathes.");
}
}

// Derived class from Mammal


class Dogs extends Mammal {
// Method in the derived class
void bark() {
System.out.println("The dog barks.");
}
}
// Main class to run the program
public class MultiLevelInheritanceDemo {
public static void main(String[] args) {
// Creating an object of the Dog class
Dogs myDog = new Dogs();

// Calling methods from all levels of the inheritance hierarchy


myDog.eat(); // Method from Animal class
myDog.breathe(); // Method from Mammal class
myDog.bark(); // Method from Dog class
}
}

Expected output:

The animal eats.


The mammal breathes.
The dog barks.
EXERCISE -4

C) Write a JAVA program for abstract class to find areas of different


shapes.

// Abstract class Shape


abstract class Shape {
// Abstract method to calculate area
abstract double calculateArea();
}

// Class Circle extending Shape


class Circle extends Shape {
double radius;

// Constructor for Circle


Circle(double radius) {
this.radius = radius;
}

// Overriding calculateArea method for Circle


@Override
double calculateArea() {
return Math.PI * radius * radius; // Formula for area of a circle
}
}

// Class Rectangle extending Shape


class Rectangle extends Shape {
double length, width;

// Constructor for Rectangle


Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Overriding calculateArea method for Rectangle


@Override
double calculateArea() {
return length * width; // Formula for area of a rectangle
}
}

// Class Triangle extending Shape


class Triangle extends Shape {
double base, height;

// Constructor for Triangle


Triangle(double base, double height) {
this.base = base;
this.height = height;
}

// Overriding calculateArea method for Triangle


@Override
double calculateArea() {
return 0.5 * base * height; // Formula for area of a triangle
}
}

// Main class to test the program


public class AstractClassExample {
public static void main(String[] args) {
// Creating objects for different shapes
Shape circle = new Circle(5.0);
Shape rectangle = new Rectangle(4.0, 6.0);
Shape triangle = new Triangle(4.0, 5.0);

// Calculating and displaying areas of the shapes


System.out.println("Area of Circle: " + circle.calculateArea());
System.out.println("Area of Rectangle: " + rectangle.calculateArea());
System.out.println("Area of Triangle: " + triangle.calculateArea());
}
}
Expected output:

Area of Circle: 78.53981633974483


Area of Rectangle: 24.0
Area of Triangle: 10.0
EXERCISE -5

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


// Superclass Animal
class Animal {
// Instance variable
String name = "Animal";

// Constructor of the superclass


public Animal() {
System.out.println("Animal constructor called");
}

// Method in the superclass


public void sound() {
System.out.println("Animal makes a sound");
}
}

// Subclass Dog extending Animal


class Dog extends Animal {
// Instance variable with the same name as in the superclass
String name = "Dog";

// Constructor of the subclass


public Dog() {
// Using super() to call the superclass constructor
super();
System.out.println("Dog constructor called");
}

// Overridden method in the subclass


@Override
public void sound() {
// Using super to call the superclass method
super.sound();
System.out.println("Dog barks");
}

// Method to demonstrate accessing superclass variable


public void printNames() {
// Accessing superclass variable using super
System.out.println("Superclass name: " + super.name);
System.out.println("Subclass name: " + this.name);
}
}

// Main class to run the example


public class SuperKeywordExample {
public static void main(String[] args) {
// Create an instance of Dog
Dog dog = new Dog();

// Call the overridden sound method


dog.sound();

// Call the method to demonstrate accessing variables


dog.printNames();
}
}

Expected output:
Animal constructor called
Dog constructor called
Animal makes a sound
Dog barks
Superclass name: Animal
Subclass name: Dog
EXERCISE -5

b) Write a JAVA program to implement Interface. What kind of


Inheritance can be achieved?

// Defining the first interface


interface Animal {
void sound(); // Abstract method (no body, implementation will be provided
by the class)
}

// Defining another interface


interface Mammal {
void habitat(); // Abstract method
}

// Implementing both interfaces in the same class


class Dog implements Animal, Mammal {
// Implementing the method from the Animal interface
public void sound() {
System.out.println("The dog barks");
}

// Implementing the method from the Mammal interface


public void habitat() {
System.out.println("The dog lives on land");
}
}
// Another class implementing both interfaces
class Dolphin implements Animal, Mammal {
// Implementing the method from the Animal interface
public void sound() {
System.out.println("The dolphin clicks");
}

// Implementing the method from the Mammal interface


public void habitat() {
System.out.println("The dolphin lives in water");
}
}

public class InterfaceInheritanceExample {


public static void main(String[] args) {
// Creating objects for Dog and Dolphin
Dog dog = new Dog();
Dolphin dolphin = new Dolphin();

// Calling methods on Dog object


System.out.println("Dog:");
dog.sound();
dog.habitat();

// Calling methods on Dolphin object


System.out.println("\nDolphin:");
dolphin.sound();
dolphin.habitat();
}
}

Expected output:

Dog:
The dog barks
The dog lives on land

Dolphin:
The dolphin clicks
The dolphin lives in water
EXERCISE -5

c) Write a JAVA program that implements Runtime polymorphism.


// Parent class
class Shape {
// Method that will be overridden
void draw() {
System.out.println("Drawing a shape");
}
}

// Child class 1: Circle


class Circle extends Shape {
// Overriding the draw method in Circle class
@Override
void draw() {
System.out.println("Drawing a circle");
}
}

// Child class 2: Rectangle


class Rectangle extends Shape {
// Overriding the draw method in Rectangle class
@Override
void draw() {
System.out.println("Drawing a rectangle");
}
}

public class RuntimePolymorphismShapeExample {


public static void main(String[] args) {
// Parent class reference
Shape myShape;

// Assigning a Circle object to the parent reference


myShape = new Circle();
myShape.draw(); // Calls Circle's overridden method

// Assigning a Rectangle object to the parent reference


myShape = new Rectangle();
myShape.draw(); // Calls Rectangle's overridden method
}
}

Expected output:

Drawing a circle
Drawing a rectangle
EXERCISE -6

a) Write a JAVA program that describes exception handling.

public class ExceptionHandlingExample {


public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
int result = 0;

try {
// Attempt division
result = numerator / denominator;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handle division by zero error
System.out.println("Error: Division by zero is not allowed.");
} finally {
// This block always executes
System.out.println("Execution completed in the 'finally' block.");
}

System.out.println("Program continues after exception handling.");


}
}
Expected output:

Error: Division by zero is not allowed.


Execution completed in the 'finally' block.
Program continues after exception handling.
EXERCISE -6

b) Write a JAVA program Illustrating Multiple catch clauses

public class MultipleExceptionsExample {


public static void main(String[] args) {
int[] numbers = {10, 5, 0};
String text = null; // This will cause NullPointerException when
accessed
int index = 2; // Invalid index for the array
int result = 0;

try {
// Attempting division by zero
result = numbers[0] / numbers[1];
System.out.println("Result of division: " + result);

// Accessing an invalid array index


System.out.println("Accessing element at index " + index + ": " +
numbers[index]);

// Attempting to access a method on a null object


System.out.println("Length of text: " + text.length());
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index is out of bounds.");
} catch (NullPointerException e) {
System.out.println("Error: Attempted to access a method on a null
object.");
} catch (Exception e) {
System.out.println("Error: An unexpected error occurred.");
}

System.out.println("Program continues after exception handling.");


}
}

Expected output:

Error: Cannot divide by zero.


Program continues after exception handling.

Result of division: 2
Error: Array index is out of bounds.
Program continues after exception handling.

Result of division: 2
Accessing element at index 2: 0
Error: Attempted to access a method on a null object.
Program continues after exception handling.
EXERCISE -6

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

public class BuiltInExceptionsUseCases {

public static void main(String[] args) {


triggerArithmeticException();
triggerArrayIndexOutOfBoundsException();
triggerNullPointerException();
triggerNumberFormatException();
triggerClassCastException();

System.out.println("Program continues after handling all


exceptions.");
}

// Method to demonstrate ArithmeticException


public static void triggerArithmeticException() {
try {
int a = 10;
int b = 0; // Division by zero
int result = a / b; // ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: Cannot divide
by zero. Please check the item count.");
}
}
// Method to demonstrate ArrayIndexOutOfBoundsException
public static void triggerArrayIndexOutOfBoundsException() {
try {
int[] items = {5, 10, 15};
int index = 5; // Invalid index
System.out.println("Item at index " + index + ": " + items[index]);
// ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught:
Invalid index. Please check the array size.");
}
}

// Method to demonstrate NullPointerException


public static void triggerNullPointerException() {
try {
String userInput = null; // Null object
System.out.println("User input length: " + userInput.length()); //
NullPointerException
} catch (NullPointerException e) {
System.out.println("NullPointerException caught: Object is null.
Ensure input is properly initialized.");
}
}

// Method to demonstrate NumberFormatException


public static void triggerNumberFormatException() {
try {
String userAge = "twenty"; // Non-numeric input
int age = Integer.parseInt(userAge); // NumberFormatException
System.out.println("User age: " + age);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: Invalid
format for parsing a number. Please enter a valid integer.");
}
}

// Method to demonstrate ClassCastException


public static void triggerClassCastException() {
try {
Object obj = "Hello"; // String object
Integer num = (Integer) obj; // ClassCastException
System.out.println("Number: " + num);
} catch (ClassCastException e) {
System.out.println("ClassCastException caught: Invalid type cast.
Check object type before casting.");
}
}
}
Expected output:

ArithmeticException caught: Cannot divide by zero. Please check the


item count.
ArrayIndexOutOfBoundsException caught: Invalid index. Please check
the array size.
NullPointerException caught: Object is null. Ensure input is properly
initialized.
NumberFormatException caught: Invalid format for parsing a number.
Please enter a valid integer.
ClassCastException caught: Invalid type cast. Check object type before
casting.
Program continues after handling all exceptions.
EXERCISE -6

D ) Write a JAVA program for creation of User Defined Exception.

// Custom exception class extending Exception


class InvalidAgeException extends Exception {
// Constructor to accept custom error message
public InvalidAgeException(String message) {
super(message);
}
}

// Main class to demonstrate usage of user-defined exception


public class UserDefinedExceptionDemo {

// Method to check age validity


public static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
// Throw custom exception if age is below 18
throw new InvalidAgeException("Invalid Age: Age must be 18 or
above to register.");
} else {
System.out.println("Age is valid. You are allowed to register.");
}
}

public static void main(String[] args) {


try {
// Test case 1: Valid age
validateAge(20); // Should pass without exception

// Test case 2: Invalid age


validateAge(15); // Should throw InvalidAgeException
} catch (InvalidAgeException e) {
System.out.println("Caught the exception: " + e.getMessage());
}

System.out.println("Program continues after exception handling.");


}
}

Expected output:

Age is valid. You are allowed to register.


Caught the exception: Invalid Age: Age must be 18 or above to register.
Program continues after exception handling.
EXERCISE - 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)

// Approach 1: Extending the Thread class


class GoodMorningThread extends Thread {
@Override
public void run() {
while (true) {
try {
System.out.println("Good Morning");
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

class HelloThread extends Thread {


@Override
public void run() {
while (true) {
try {
System.out.println("Hello");
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

class WelcomeThread extends Thread {


@Override
public void run() {
while (true) {
try {
System.out.println("Welcome");
Thread.sleep(3000); // Sleep for 3 seconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

// Approach 2: Implementing Runnable interface


class GoodMorningRunnable implements Runnable {
@Override
public void run() {
while (true) {
try {
System.out.println("Good Morning (Runnable)");
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

class HelloRunnable implements Runnable {


@Override
public void run() {
while (true) {
try {
System.out.println("Hello (Runnable)");
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

class WelcomeRunnable implements Runnable {


@Override
public void run() {
while (true) {
try {
System.out.println("Welcome (Runnable)");
Thread.sleep(3000); // Sleep for 3 seconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class Threads {


public static void main(String[] args) {
// Using Thread class
System.out.println("Using Thread class:");
GoodMorningThread goodMorningThread = new
GoodMorningThread();
HelloThread helloThread = new HelloThread();
WelcomeThread welcomeThread = new WelcomeThread();

goodMorningThread.start(); // Start the first thread


helloThread.start(); // Start the second thread
welcomeThread.start(); // Start the third thread

// Using Runnable interface


System.out.println("\nUsing Runnable interface:");
Thread goodMorningRunnableThread = new Thread(new
GoodMorningRunnable());
Thread helloRunnableThread = new Thread(new HelloRunnable());
Thread welcomeRunnableThread = new Thread(new
WelcomeRunnable());

goodMorningRunnableThread.start(); // Start the first thread with


Runnable
helloRunnableThread.start(); // Start the second thread with
Runnable
welcomeRunnableThread.start(); // Start the third thread with
Runnable
}
}

Expected output:

Using Runnable interface:


Hello
Good Morning
Welcome
Good Morning (Runnable)
Hello (Runnable)
Welcome (Runnable)
Good Morning
Good Morning (Runnable)
Good Morning
Hello (Runnable)
Hello
Good Morning (Runnable)
Welcome
Welcome (Runnable)
Good Morning
Good Morning (Runnable)
EXERCISE – 7

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

class MyThread extends Thread {

@Override

public void run() {

try {

System.out.println(Thread.currentThread().getName() + " is
starting.");

Thread.sleep(2000); // Sleep for 2 seconds

System.out.println(Thread.currentThread().getName() + " has


finished.");

} catch (InterruptedException e) {

System.out.println(e);

public class ThreadAliveJoinExample {

public static void main(String[] args) {

MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();


// Start the threads

thread1.start();

thread2.start();

// Check if threads are alive

System.out.println("Thread1 is alive: " + thread1.isAlive()); //


Before join

System.out.println("Thread2 is alive: " + thread2.isAlive()); //


Before join

try {

// Wait for threads to complete

thread1.join(); // Main thread will wait for thread1 to finish

thread2.join(); // Main thread will wait for thread2 to finish

} catch (InterruptedException e) {

System.out.println(e);

// After join, threads should be finished

System.out.println("Thread1 is alive: " + thread1.isAlive()); // After


join
System.out.println("Thread2 is alive: " + thread2.isAlive()); // After
join

System.out.println("Main thread has finished.");

Expected output:

Thread1 is alive: true

Thread2 is alive: true

Thread-0 is starting.

Thread-1 is starting

Thread-0 has finished.

Thread-1 has finished.

Thread1 is alive: false

Thread2 is alive: false

Main thread has finished.


EXERCISE – 7

c) Write a Program illustrating Daemon Threads.

class BackgroundDaemon extends Thread {

@Override

public void run() {

// Infinite loop to simulate background work

while (true) {

System.out.println(Thread.currentThread().getName() + "
(Daemon) is running in the background.");

try {

Thread.sleep(1000); // Sleep for 1 second

} catch (InterruptedException e) {

System.out.println(e);

class UserTask extends Thread {

@Override
public void run() {

System.out.println(Thread.currentThread().getName() + " (User) is


starting.");

try {

Thread.sleep(3000); // Simulate a task by sleeping for 3 seconds

} catch (InterruptedException e) {

System.out.println(e);

System.out.println(Thread.currentThread().getName() + " (User) has


finished.");

public class DaemonThreadExample {

public static void main(String[] args) {

// Create instances of the daemon and user threads

BackgroundDaemon daemonThread = new BackgroundDaemon();

UserTask userThread = new UserTask();

// Set the daemon thread to run as a daemon

daemonThread.setDaemon(true);
// Start both threads

daemonThread.start();

userThread.start();

try {

// Wait for the user thread to complete

userThread.join();

} catch (InterruptedException e) {

System.out.println(e);

System.out.println("Main thread has finished.");

Expected output:
Thread-1 (User) is starting.

Thread-0 (Daemon) is running in the background.

Thread-0 (Daemon) is running in the background.

Thread-0 (Daemon) is running in the background.

Thread-1 (User) has finished.

Main thread has finished.


EXERCISE – 7

d) Write a JAVA program Producer Consumer Problem

import java.util.LinkedList;
import java.util.Queue;

class Buffer {
private Queue<Integer> queue = new LinkedList<>();
private int capacity;

public Buffer(int capacity) {


this.capacity = capacity;
}

// Method for the producer to add items to the buffer


public synchronized void produce(int value) throws InterruptedException {
while (queue.size() == capacity) {
System.out.println("Buffer is full. Producer is waiting...");
wait(); // Wait until there's space in the buffer
}
queue.add(value);
System.out.println("Produced: " + value);
notify(); // Notify the consumer that there's a new item to consume
}

// Method for the consumer to consume items from the buffer


public synchronized int consume() throws InterruptedException {
while (queue.isEmpty()) {
System.out.println("Buffer is empty. Consumer is waiting...");
wait(); // Wait until there's something in the buffer to consume
}
int value = queue.poll();
System.out.println("Consumed: " + value);
notify(); // Notify the producer that there's space in the buffer
return value;
}
}

class Producer extends Thread {


private Buffer buffer;

public Producer(Buffer buffer) {


this.buffer = buffer;
}

@Override
public void run() {
int value = 0;
try {
while (true) {
buffer.produce(value);
value++;
Thread.sleep(500); // Simulate time taken to produce an item
}
} catch (InterruptedException e) {
System.out.println("Producer interrupted");
}
}
}

class Consumer extends Thread {


private Buffer buffer;

public Consumer(Buffer buffer) {


this.buffer = buffer;
}

@Override
public void run() {
try {
while (true) {
buffer.consume();
Thread.sleep(1000); // Simulate time taken to consume an item
}
} catch (InterruptedException e) {
System.out.println("Consumer interrupted");
}
}
}
public class ProducerConsumerProblem {
public static void main(String[] args) {
Buffer buffer = new Buffer(5); // Create a buffer with a capacity of 5

Producer producer = new Producer(buffer);


Consumer consumer = new Consumer(buffer);

producer.start();
consumer.start();
}
}

Expected output:

Produced: 0
Consumed: 0
Produced: 1
Consumed: 1
Produced: 2
Produced: 3
Consumed: 2
Produced: 4
Produced: 5
Consumed: 3
Produced: 6
Produced: 7
Consumed: 4
Produced: 8
Produced: 9
Consumed: 5
Produced: 10
Buffer is full. Producer is waiting...
Consumed: 6
Produced: 11
Buffer is full. Producer is waiting...
Consumed: 7
Produced: 12
Buffer is full. Producer is waiting...
Consumed: 8
Produced: 13
Buffer is full. Producer is waiting...
Consumed: 9
Produced: 14
Buffer is full. Producer is waiting...
Consumed: 10
Produced: 15
Buffer is full. Producer is waiting...
Consumed: 11
Produced: 16
Buffer is full. Producer is waiting….
EXERCISE – 8

a) Write a java program that import and use the user defined packages

Step 1: Create a User-Defined Package


1. First, create a directory structure for the package. For example, create a
folder named myutils.
2. Inside the myutils folder, create a file named MathOperations.java.

// Save this file as MathOperations.java inside a folder named "myutils"


package myutils;

public class MathOperations {


// Method to add two numbers
public int add(int a, int b) {
return a + b;
}

// Method to subtract two numbers


public int subtract(int a, int b) {
return a - b;
}

// Method to multiply two numbers


public int multiply(int a, int b) {
return a * b;
}
// Method to divide two numbers
public double divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return (double) a / b;
}
}

Step 2: Compile the User-Defined Package


To compile MathOperations.java, navigate to the folder where myutils is located
and run:

Step 3: Create the Main Program


Now, create another Java file that imports the myutils package and uses the
MathOperations class.

MainProgram.java (Using the User-Defined Package)


// Importing the user-defined package
import myutils.MathOperations;

public class MainProgram {


public static void main(String[] args) {
// Create an instance of MathOperations from the user-defined package
MathOperations mathOps = new MathOperations();

// Use methods from MathOperations


int sum = mathOps.add(10, 5);
int difference = mathOps.subtract(10, 5);
int product = mathOps.multiply(10, 5);
double quotient = mathOps.divide(10, 5);

// Display the results


System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
}
}

Expected output:

Sum: 15
Difference: 5
Product: 50
Quotient: 2.0

You might also like