KEMBAR78
Java Practical | PDF | Java (Programming Language) | Java (Software Platform)
0% found this document useful (0 votes)
5 views62 pages

Java Practical

The document outlines a series of Java practical exercises aimed at teaching fundamental programming concepts, including installation of JDK, writing simple programs, and using various programming constructs like loops, methods, and classes. Each practical includes an aim, a solution with code examples, and common errors with their solutions. The exercises cover topics such as matrix multiplication, method overloading, constructor overloading, and the use of keywords like 'this' and 'static'.

Uploaded by

gjgaming291
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)
5 views62 pages

Java Practical

The document outlines a series of Java practical exercises aimed at teaching fundamental programming concepts, including installation of JDK, writing simple programs, and using various programming constructs like loops, methods, and classes. Each practical includes an aim, a solution with code examples, and common errors with their solutions. The exercises cover topics such as matrix multiplication, method overloading, constructor overloading, and the use of keywords like 'this' and 'static'.

Uploaded by

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

Java Practical

Practical - 1
Aim - AIM: Install JDK, write a simple “Hello World” or similar java program,
compilation, debugging, executing using java compiler and interpreter.
Solution
Install JDK, write a simple “Hello World” or similar java program, compilation, debugging,
executing using java compiler and interpreter.
Setp1:-
Download JDK 1.6 [whatever the version you want] from www.oracle.com / any sharing sites, its
just about 50 – 60 Mb in size.

Setp2:-
Now just double click on this application and just follow the bellow steps…

Click on Accept >


Click on Next >

Let is install>
Now you will get one new window with title SE Runtime Environment 6, which is nothing but
JRE, JDK needs JRE to be install first, so click Next
Then finally it will show you one window with Finish button just click on that, and that’s it, let us
see the class path settings….
Its simple mates, just right click on My Computer Icon then choose Advanced system
settings..click on that Advanced system settings then it will shows like..

Now just click on Environment Variables button at bottom-right then…


Then select path, and click on Edit button…. Now there, just append your bin folder path of jdk
folder, it is like…
c:\Program Files (x86)\Java\jdk1.0.6\bin;
Compiling Java Programs
1. Open the Notepad text editor Start > All Programs > Accessories >Notepad and type the
following program into it:
classHelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
2. Save the program to the C:\ drive in a file named HelloWorld.java. Make sure toselect "All
Files" in the Type field of the Save As dialog box.
3. To compile the program, open the Dos Prompt Start > All Programs >Accessories >
Command Prompt and type:
cd\
javac HelloWorld.java

If you don't get any errors then everything went well. If you get errors, check firstly thatyou
saved the program on the C:\ drive and that it is named HelloWorld.java.

Running Java Programs


1. To run the program, type:
2. java HelloWorld
3. you should get the following output:
Hello World!

Common Errors and Solutions


1. Exception in thread "main" java.lang.NoSuchMethodError: mainYou must define a main
method as: public static void main(String[]args) {...}
2. HelloWorld.java:3: illegal character: \8220
System.out.println(öHelloWorld!ö);
Do not type your code in a word processor application that uses smart quotes!!
3. HelloWorld.class Exception in thread "main"java.lang.NoClassDefFoundError:
HelloWorld/class
The correct way to call a program is java HelloWorldwithout the ".java" or ".class"
Practical – 2
Aim - Write a Java program to find maximum of three numbers.
Solution
import java.util.Scanner;

public class MaximumofThree {


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

System.out.println("Enter three numbers:");

// Input three numbers


double num1 = scanner.nextDouble();
double num2 = scanner.nextDouble();
double num3 = scanner.nextDouble();

// Find the maximum


double max = num1;
if (num2 > max) {
max = num2;
}
if (num3 > max) {
max = num3;
}
// Print the result
System.out.println("Maximum of the three numbers is: " + max);

scanner.close();
}
}

Practical – 3
Aim - Write a simple Java program using loops.
Solution
public class loop {
public static void main(String[] args) {
// Using a for loop to print numbers from 1 to 10
System.out.println("Printing numbers from 1 to 10:");
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
System.out.println(); // Just for a new line

// Using a while loop to print numbers from 10 to 1


System.out.println("Printing numbers from 10 to 1:");
int j = 10;
while (j >= 1) {
System.out.print(j + " ");
j--;
}
System.out.println(); // Just for a new line

// Using a do-while loop to print numbers from 1 to 10


System.out.println("Printing numbers from 1 to 10 with a do-while loop:");
int k = 1;
do {
System.out.print(k + " ");
k++;
} while (k <= 10);
System.out.println(); // Just for a new line
}
}
Practical – 4
Aim - Write a Java program for matrix multiplication.
Solution
import java.util.Scanner;

public class MatrixMultiplication {


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

System.out.println("Enter the number of rows and columns for matrix A:");


int rowsA = scanner.nextInt();
int colsA = scanner.nextInt();

System.out.println("Enter the number of rows and columns for matrix B:");


int rowsB = scanner.nextInt();
int colsB = scanner.nextInt();
// Check if matrix multiplication is possible
if (colsA != rowsB) {
System.out.println("Matrix multiplication is not possible.");
scanner.close();
return;
}

// Input elements for matrix A


System.out.println("Enter elements for matrix A:");
int[][] matrixA = new int[rowsA][colsA];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsA; j++) {
matrixA[i][j] = scanner.nextInt();
}
}

// Input elements for matrix B


System.out.println("Enter elements for matrix B:");
int[][] matrixB = new int[rowsB][colsB];
for (int i = 0; i < rowsB; i++) {
for (int j = 0; j < colsB; j++) {
matrixB[i][j] = scanner.nextInt();
}
}
// Perform matrix multiplication
int[][] result = new int[rowsA][colsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}

// Display the result


System.out.println("Resultant matrix after multiplication:");
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}

scanner.close();
}
}
Practical – 5
Aim - Write a Java program to use of Wrapper class of each primitive data types
Solution
public class WrapperClassDemo {
public static void main(String[] args) {
// Primitive data types
int intValue = 10;
double doubleValue = 3.14;
char charValue = 'A';
boolean booleanValue = true;

// Wrapper classes
Integer integerWrapper = Integer.valueOf(intValue);
Double doubleWrapper = Double.valueOf(doubleValue);
Character charWrapper = Character.valueOf(charValue);
Boolean booleanWrapper = Boolean.valueOf(booleanValue);

// Printing values
System.out.println("Integer Wrapper: " + integerWrapper);
System.out.println("Double Wrapper: " + doubleWrapper);
System.out.println("Character Wrapper: " + charWrapper);
System.out.println("Boolean Wrapper: " + booleanWrapper);

// Converting back to primitive data types


int intValueFromWrapper = integerWrapper.intValue();
double doubleValueFromWrapper = doubleWrapper.doubleValue();
char charValueFromWrapper = charWrapper.charValue();
boolean booleanValueFromWrapper = booleanWrapper.booleanValue();

// Printing values
System.out.println("Integer Value: " + intValueFromWrapper);
System.out.println("Double Value: " + doubleValueFromWrapper);
System.out.println("Character Value: " + charValueFromWrapper);
System.out.println("Boolean Value: " + booleanValueFromWrapper);
}
}
Practical – 6
Aim - Write a Java program to use of command line arguments
Solution
public class CommandLineArguments {
public static void main(String[] args) {
// Checking if command-line arguments are provided
if (args.length == 0) {
System.out.println("No command-line arguments provided.");
} else {
System.out.println("Number of command-line arguments: " + args.length);
System.out.println("Command-line arguments:");
// Displaying each command-line argument
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + (i + 1) + ": " + args[i]);
}
}
}
}

Practical – 7
Aim - Write a Java program to demonstrate class and object. To understand and
Solution
// Define a class named "Car"
class Car {
// Data members or fields
String brand;
String model;
int year;

// Constructor to initialize the object


Car(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}

// Method to display information about the car


void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}

// Main class to demonstrate class and object


public class CarInfo {
public static void main(String[] args) {
// Creating objects of class "Car"
Car car1 = new Car("Toyota", "Camry", 2021);
Car car2 = new Car("Honda", "Civic", 2020);

// Calling method to display information about the cars


System.out.println("Car 1:");
car1.displayInfo();

System.out.println("\nCar 2:");
car2.displayInfo();
}
}
Practical – 8
Aim - Write a Java program for method overloading.
Solution
public class MethodOverloadingDemo {
// Method to add two integers
public static int add(int a, int b) {
return a + b;
}

// Method to add three integers


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

// Method to add two doubles


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

// Method to concatenate two strings


public static String add(String str1, String str2) {
return str1 + str2;
}

public static void main(String[] args) {


System.out.println("Sum of 5 and 10: " + add(5, 10));
System.out.println("Sum of 5, 10, and 15: " + add(5, 10, 15));
System.out.println("Sum of 3.5 and 2.5: " + add(3.5, 2.5));
System.out.println("Concatenated string: " + add("Hello", " World"));
}
}
Practical – 9
Aim - Write a Java program for constructor overloading.
Solution
public class ConstructorOverloadingDemo {
private String name;
private int age;

// Constructor with no parameters


public ConstructorOverloadingDemo() {
name = "Unknown";
age = 0;
}

// Constructor with one parameter (name)


public ConstructorOverloadingDemo(String name) {
this.name = name;
age = 0;
}

// Constructor with two parameters (name and age)


public ConstructorOverloadingDemo(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display information
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}

public static void main(String[] args) {


// Creating objects using different constructors
ConstructorOverloadingDemo obj1 = new ConstructorOverloadingDemo();
ConstructorOverloadingDemo obj2 = new
ConstructorOverloadingDemo("John");
ConstructorOverloadingDemo obj3 = new
ConstructorOverloadingDemo("Alice", 25);

// Displaying information using the displayInfo() method


System.out.println("Object 1:");
obj1.displayInfo();
System.out.println("\nObject 2:");
obj2.displayInfo();
System.out.println("\nObject 3:");
obj3.displayInfo();
}
}
Practical – 10
Aim - Write a program in Java to demonstrate use of this keyword
Solution
public class Person {
private String name;
private int age;

// Constructor with parameters


public Person(String name, int age) {
// Using 'this' to distinguish between instance variable and parameter with the
same name
this.name = name;
this.age = age;
}

// Method to display information


public void displayInfo() {
// Using 'this' to refer to the current object's instance variables
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}

// Method to update age


public void updateAge(int age) {
// Using 'this' to refer to the current object's instance variable
this.age = age;
}

public static void main(String[] args) {


// Creating an object of the Person class
Person person1 = new Person("John", 30);

// Displaying information using the displayInfo() method


System.out.println("Information of person1:");
person1.displayInfo();

// Updating age using the updateAge() method


person1.updateAge(35);

// Displaying updated information


System.out.println("\nUpdated information of person1:");
person1.displayInfo();
}
}

Practical – 11
Aim - Write a program in Java to demonstrate use of static keyword
Solution
class Example {
static int staticVariable = 5; // Static variable

int instanceVariable; // Instance variable

static void staticMethod() { // Static method


System.out.println("This is a static method.");
}

void instanceMethod() { // Instance method


System.out.println("This is an instance method.");
}
}

public class StaticKeywordDemo {


public static void main(String[] args) {
// Accessing static variable and method directly using class name
System.out.println("Static variable: " + Example.staticVariable); // Output:
Static variable: 5
Example.staticMethod(); // Output: This is a static method.

// Creating objects of the Example class


Example obj1 = new Example();
Example obj2 = new Example();

// Accessing instance variable and method using object


obj1.instanceVariable = 10;
obj2.instanceVariable = 20;

System.out.println("Instance variable of obj1: " + obj1.instanceVariable); //


Output: Instance variable of obj1: 10
System.out.println("Instance variable of obj2: " + obj2.instanceVariable); //
Output: Instance variable of obj2: 20

obj1.instanceMethod(); // Output: This is an instance method.


obj2.instanceMethod(); // Output: This is an instance method.
}
}

Practical – 12
Aim - Develop minimum four programs based on variation in methods i.e. passing
by value, passing by reference, returning values and returning objects from
methods.
Solution
public class PassingByValue {
public static void main(String[] args) {
int num = 10;
System.out.println("Before method call: " + num);
modifyValue(num);
System.out.println("After method call: " + num);
}

public static void modifyValue(int value) {


value = value * 2;
System.out.println("Inside method: " + value);
}
}

class Person {
String name;

Person(String name) {
this.name = name;
}
}

public class PassingByReference {


public static void main(String[] args) {
Person person = new Person("Alice");
System.out.println("Before method call: " + person.name);
modifyReference(person);
System.out.println("After method call: " + person.name);
}

public static void modifyReference(Person p) {


p.name = "Bob"; // This modifies the object that person points to
}
}

public class ReturningValues {


public static void main(String[] args) {
int result = calculateSum(5, 10);
System.out.println("Sum is: " + result);
}

public static int calculateSum(int a, int b) {


return a + b; // Returning the sum of a and b
}
}

class Rectangle {
int width;
int height;

Rectangle(int width, int height) {


this.width = width;
this.height = height;
}

int area() {
return width * height;
}
}

public class ReturningObjects {


public static void main(String[] args) {
Rectangle rect = createRectangle(4, 5);
System.out.println("Rectangle area: " + rect.area());
}

public static Rectangle createRectangle(int width, int height) {


return new Rectangle(width, height); // Returning a new Rectangle object
}
}
Practical – 13
Aim - Write a program in Java perform create, write and read operations on a text
file.
Solution
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;

public class TextFileOperations {


public static void main(String[] args) {
String fileName = "example.txt"; // File name

// Create a new text file


createFile(fileName);

// Write data to the text file


writeToFile(fileName, "Hello, world!");
// Read data from the text file
String data = readFromFile(fileName);
System.out.println("Data read from file: " + data);
}

// Method to create a new text file


public static void createFile(String fileName) {
try {
File file = new File(fileName);
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred while creating the file.");
e.printStackTrace();
}
}

// Method to write data to a text file


public static void writeToFile(String fileName, String data) {
try {
FileWriter writer = new FileWriter(fileName);
writer.write(data);
writer.close();
System.out.println("Data written to file.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}

// Method to read data from a text file


public static String readFromFile(String fileName) {
StringBuilder content = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
return content.toString();
}
}
Practical – 14
Aim - Write a program in Java to demonstrate single inheritance, multilevel
inheritance and hierarchical inheritance.
Solution
// Single Inheritance
class Parent {
void displayParent() {
System.out.println("Parent class method");
}
}

class Child extends Parent {


void displayChild() {
System.out.println("Child class method");
}
}

// Multilevel Inheritance
class GrandParent {
void displayGrandParent() {
System.out.println("GrandParent class method");
}
}

class Parent2 extends GrandParent {


void displayParent2() {
System.out.println("Parent2 class method");
}
}

class Child2 extends Parent2 {


void displayChild2() {
System.out.println("Child2 class method");
}
}

// Hierarchical Inheritance
class Parent3 {
void displayParent3() {
System.out.println("Parent3 class method");
}
}

class Child3A extends Parent3 {


void displayChild3A() {
System.out.println("Child3A class method");
}
}

class Child3B extends Parent3 {


void displayChild3B() {
System.out.println("Child3B class method");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
// Single Inheritance
Child child = new Child();
child.displayParent();
child.displayChild();

// Multilevel Inheritance
Child2 child2 = new Child2();
child2.displayGrandParent();
child2.displayParent2();
child2.displayChild2();

// Hierarchical Inheritance
Child3A child3A = new Child3A();
child3A.displayParent3();
child3A.displayChild3A();

Child3B child3B = new Child3B();


child3B.displayParent3();
child3B.displayChild3B();
}
}

Practical – 15
Aim - Write a program in Java to demonstrate method overriding.
Solution
// Parent class
class Animal {
// Method in parent class
void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Subclass extending Parent class


class Dog extends Animal {
// Overriding the method in subclass
@Override
void makeSound() {
System.out.println("Dog barks");
}
}

// Subclass extending Parent class


class Cat extends Animal {
// Overriding the method in subclass
@Override
void makeSound() {
System.out.println("Cat meows");
}
}

public class MethodOverridingDemo {


public static void main(String[] args) {
// Creating objects of each subclass
Animal animal1 = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new Cat();

// Calling the method for each object


animal1.makeSound(); // Output: Animal makes a sound
animal2.makeSound(); // Output: Dog barks
animal3.makeSound(); // Output: Cat meows
}
}

Practical – 16
Aim - Write a program in Java to demonstrate the use of 'super' keyword.
Solution
class Parent {
int parentVariable = 10;

void displayParent() {
System.out.println("Parent class method");
}
}

class Child extends Parent {


int childVariable = 20;

void displayChild() {
System.out.println("Child class method");
}

void displayParentVariable() {
// Accessing parent class variable using super keyword
System.out.println("Parent variable accessed from Child class: " +
super.parentVariable);
}

void displayParentMethod() {
// Invoking parent class method using super keyword
super.displayParent();
}
}

public class SuperKeywordDemo {


public static void main(String[] args) {
Child child = new Child();
// Accessing child class variable
System.out.println("Child variable: " + child.childVariable);

// Accessing parent class variable through child object using super


child.displayParentVariable();

// Invoking parent class method through child object using super


child.displayParentMethod();
}
}

Practical – 17
Aim – Write a program in Java to demonstrate the use of 'final' keyword.
Solution
// Final variable example
class FinalVariableExample {
final int finalVar = 10; // Final variable

void changeFinalVar() {
// Trying to change the value of finalVar will result in a compilation error
// finalVar = 20; // Compilation error: cannot assign a value to final variable
}
}

// Final method example


class Parent {
final void finalMethod() {
System.out.println("Final method in Parent class");
}
}

class Child extends Parent {


// Trying to override a final method will result in a compilation error
// void finalMethod() {} // Compilation error: cannot override final method
}

// Final class example


final class FinalClass {
// This class cannot be subclassed
}

// Trying to extend a final class will result in a compilation error


// class AnotherClass extends FinalClass {} // Compilation error: cannot inherit
from final class

public class FinalKeywordDemo {


public static void main(String[] args) {
FinalVariableExample finalExample = new FinalVariableExample();
System.out.println("Final variable: " + finalExample.finalVar); // Output: 10

Parent parent = new Parent();


parent.finalMethod(); // Output: Final method in Parent class
}
}

Practical – 18
Aim - Write a program in Java for use of abstract method and class
Solution
// Abstract class
abstract class Shape {
// Abstract method
abstract void draw();

// Concrete method
void display() {
System.out.println("This is a shape.");
}
}

// Concrete subclass
class Circle extends Shape {
// Implementation of abstract method
void draw() {
System.out.println("Drawing a circle.");
}
}

// Concrete subclass
class Rectangle extends Shape {
// Implementation of abstract method
void draw() {
System.out.println("Drawing a rectangle.");
}
}

public class AbstractClassDemo {


public static void main(String[] args) {
// Cannot instantiate an abstract class
// Shape shape = new Shape(); // Compilation error: Cannot instantiate the
type Shape

// Creating objects of concrete subclasses


Shape circle = new Circle();
Shape rectangle = new Rectangle();

// Calling abstract method


circle.draw(); // Output: Drawing a circle.
rectangle.draw(); // Output: Drawing a rectangle.

// Calling concrete method


circle.display(); // Output: This is a shape.
rectangle.display(); // Output: This is a shape.
}
}

Practical – 19
Aim - Write a program that illustrates interface inheritance. Interface P12 inherited
from both P1 and P2. Each interface declares one constant and one method. The
class Q implements P12. Instantiate Q and invoke each of its methods. Each
method displays one of the constants.
Solution
// Interface P1
interface P1 {
int CONSTANT_P1 = 10; // Constant

void methodP1(); // Method declaration


}

// Interface P2
interface P2 {
int CONSTANT_P2 = 20; // Constant

void methodP2(); // Method declaration


}

// Interface P12 inherits from both P1 and P2


interface P12 extends P1, P2 {
// No additional constants or methods declared
}

// Class Q implements interface P12


class Q implements P12 {
// Implementing methodP1 from P1 interface
public void methodP1() {
System.out.println("Constant from P1: " + CONSTANT_P1);
}
// Implementing methodP2 from P2 interface
public void methodP2() {
System.out.println("Constant from P2: " + CONSTANT_P2);
}
}

public class InterfaceInheritanceDemo {


public static void main(String[] args) {
// Instantiate Q
Q q = new Q();

// Invoke methods of Q
q.methodP1(); // Output: Constant from P1: 10
q.methodP2(); // Output: Constant from P2: 20
}
}
Practical – 20
Aim - Write an application that illustrates method overriding in the same package
and different packages. Also demonstrate accessibility rules in inside and outside
packages.
Solution
package com.example.base;

public class Animal {


// Public method
public void makeSound() {
System.out.println("Some generic animal sound");
}

// Protected method
protected void eat() {
System.out.println("Animal is eating");
}

// Default method (package-private)


void sleep() {
System.out.println("Animal is sleeping");
}
}

package com.example.base;
public class Dog extends Animal {
// Overriding the public method
@Override
public void makeSound() {
System.out.println("Dog barks");
}

// Overriding the protected method


@Override
protected void eat() {
System.out.println("Dog is eating");
}

// Cannot override the default method with a more restrictive access level
@Override
void sleep() {
System.out.println("Dog is sleeping");
}
}

package com.example.extended;

import com.example.base.Animal;

public class Cat extends Animal {


// Overriding the public method
@Override
public void makeSound() {
System.out.println("Cat meows");
}

// Cannot override the protected method with a default access level


// protected void eat() { ... } // This would cause a compile-time error

// Overriding the default method is not possible here


// void sleep() { ... } // This would cause a compile-time error
}

import com.example.base.Animal;
import com.example.base.Dog;
import com.example.extended.Cat;

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

// Demonstrating method overriding within the same package


System.out.println("Animal sound:");
myAnimal.makeSound(); // Outputs: Some generic animal sound
myDog.makeSound(); // Outputs: Dog barks
myCat.makeSound(); // Outputs: Cat meows

// Demonstrating accessibility rules


System.out.println("\nAnimal eating:");
myAnimal.eat(); // Outputs: Animal is eating
myDog.eat(); // Outputs: Dog is eating
// myCat.eat(); // This line would cause a compile-time error

System.out.println("\nAnimal sleeping:");
myAnimal.sleep(); // Outputs: Animal is sleeping
myDog.sleep(); // Outputs: Dog is sleeping
// myCat.sleep(); // This line would cause a compile-time error
}
}

Output
Animal sound:
Some generic animal sound
Dog barks
Cat meows

Animal eating:
Animal is eating
Dog is eating

Animal sleeping:
Animal is sleeping
Dog is sleeping

Practical – 21
Aim - Write a program in Java to develop user defined exception for 'Divide by
Zero' error.
Solution
class DivideByZeroException extends Exception {
// Constructor to set the error message
public DivideByZeroException(String message) {
super(message);
}
}

// Main class to demonstrate the custom exception


public class DivideByZeroExample {
// Method that performs division and throws DivideByZeroException if divisor
is zero
public static double divide(int numerator, int denominator) throws
DivideByZeroException {
if (denominator == 0) {
// Throw the custom exception if denominator is zero
throw new DivideByZeroException("Error: Divide by zero");
}
// Perform the division
return (double) numerator / denominator;
}

// Main method to test the custom exception


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

try {
// Attempt division
double result = divide(numerator, denominator);
System.out.println("Result of division: " + result);
} catch (DivideByZeroException e) {
// Catch the custom exception and handle it
System.out.println("Error caught: " + e.getMessage());
// Optionally, handle the exception further
}
}
}
Practical – 22
Aim - Write a program in Java to demonstrate multiple try block and multiple
catch exceptions.
Solution
public class MultipleCatchDemo {
public static void main(String[] args) {
try {
// Trying to convert a string to an integer
String str = "abc";
int num = Integer.parseInt(str);
System.out.println("Parsed integer: " + num);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " + e.getMessage());
}

try {
// Trying to access an element out of bounds in an array
int[] arr = new int[5];
System.out.println("Value at index 10: " + arr[10]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
}

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

try {
// Trying to access a non-existing file
java.io.FileInputStream fis = new
java.io.FileInputStream("nonexistent.txt");
} catch (java.io.FileNotFoundException e) {
System.out.println("FileNotFoundException caught: " + e.getMessage());
}
}
}
Practical – 23
Aim - Write a small application in Java to develop Banking Application in which
user deposits the amount Rs 1000.00 and then starts withdrawing of Rs 400.00, Rs
300.00 and it throws exception "Not Sufficient Fund" when user withdraws Rs.
500 thereafter.
Solution
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}

class Account {
private double balance;
public Account(double initialBalance) {
this.balance = initialBalance;
}

public synchronized void deposit(double amount) {


balance += amount;
System.out.println("Deposited: Rs " + amount);
}

public synchronized void withdraw(double amount) throws


InsufficientFundsException {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: Rs " + amount);
} else {
throw new InsufficientFundsException("Not Sufficient Funds. Current
Balance: Rs " + balance);
}
}
}

public class BankingApplication {


public static void main(String[] args) {
Account account = new Account(1000.00);
try {
account.deposit(1000.00);
account.withdraw(400.00);
account.withdraw(300.00);
account.withdraw(500.00); // This will throw an exception
} catch (InsufficientFundsException e) {
System.out.println(e.getMessage());
}
}
}

Practical – 24
Aim - Write a program that executes two threads. One thread will print the even
numbers and another thread will print odd numbers between 1 to 50.
Solution
public class Threads {
public static void main(String[] args) {
// Create threads for printing even and odd numbers
Thread evenThread = new Thread(new EvenNumbers());
Thread oddThread = new Thread(new OddNumbers());

// Start the threads


evenThread.start();
oddThread.start();
}
}

class EvenNumbers implements Runnable {


public void run() {
for (int i = 2; i <= 50; i += 2) {
System.out.println("Even: " + i);
try {
Thread.sleep(500); // Sleep for a short time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class OddNumbers implements Runnable {


public void run() {
for (int i = 1; i <= 50; i += 2) {
System.out.println("Odd: " + i);
try {
Thread.sleep(500); // Sleep for a short time
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Practical – 25
Aim - Write a program that executes two threads. One thread displays “Thread1”
every 2,000 milliseconds, and the other displays “Thread2” every 4,000
milliseconds. Create the threads by extending the Thread class.
Solution
public class Main {
public static void main(String[] args) {
// Create and start the first thread
Thread1 thread1 = new Thread1();
thread1.start();

// Create and start the second thread


Thread2 thread2 = new Thread2();
thread2.start();
}
}

class Thread1 extends Thread {


public void run() {
while (true) {
System.out.println("Thread1");
try {
Thread.sleep(2000); // Sleep for 2000 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

class Thread2 extends Thread {


public void run() {
while (true) {
System.out.println("Thread2");
try {
Thread.sleep(4000); // Sleep for 4000 milliseconds
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

You might also like