java
java
Practical List
Semester: 4th
Subject Name: Object Oriented Programming with java (4341602)
Name of faculty: Prof. Bina B. Sathavara
21. Develop a java program that demonstrates the use of Abstract class
22. Develop a java program that illustrates interface inheritance. Interface ‘A1’ and ‘A2’ are
extended from interface ‘A’. Interface ‘A12’ inherited from both ‘A1’ and ‘A2’. Each
interface declares one method and one constant. Class ‘Interface_Imple’ implements
‘A12’. Instantiate ‘Interface_Imple’ and invoke each of its methods. Each method
displays one of the constants.
23. Develop a program to create a Package and demonstrate how packages are used in java.
And use java access modifier to demonstrate the access rules in a package.
24. Develop a program to demonstrate the use of ‘super’ and ‘final’ keywords.
25. Develop programs to demonstrate the use of Exception Handling using predefined
Exception Classes.
26. Develop a program to handle multiple exceptions using multiple try blocks and multiple
catch blocks.
27. Develop a program to implement user defined exceptions.
28. Develop a program to demonstrate use of throw, throws, and finally keyword
29. Develop a program that executes two threads. One thread displays “Java Programming”
every 2 seconds, and the other displays “Semester - 4th” every 5 seconds.(Create the
threads by extending the Thread class)
30. Develop a program that executes two threads. One thread will print the even numbers and
the another thread will print odd numbers between 1 to 10.(Create the thread by
implementing runnable interface)
31. Develop a program to demonstrate use of synchronization of threads when multiple
threads are trying to update a common variable
32. Develop programs to create, write, modify, read operations on Text files.
Practical-1
Aim : Install JDK and Setup a Java Programming development environment by using: 1)
Command Prompt (SET PATH command and using Environment Variable). 2) Any open source
IDE (Eclipse, Jcreater etc).
1. Download JDK:
o Visit the official Oracle JDK or OpenJDK website:
Oracle JDK
OpenJDK
o Download the appropriate version based on your system (Windows, macOS,
Linux).
2. Install JDK:
o Run the downloaded installer and follow the setup instructions.
o Note the installation directory (e.g., C:\Program Files\Java\jdk-XX.X.X).
pgsql
CopyEdit
set PATH=C:\Program Files\Java\jdk-XX.X.X\bin;%PATH%
nginx
CopyEdit
java -version
nginx
CopyEdit
javac -version
pgsql
CopyEdit
java -version
javac -version
Practical-2
Aim: Test the java development environment setup by implementing a simple java
program (print: “OOP with JAVA”).
Step 1: Create a Simple Java Program
1. Open Notepad (or any text editor) and write the following Java program:
java
CopyEdit
public class TestJava {
public static void main(String[] args) {
System.out.println("OOP with JAVA");
}
}
bash
CopyEdit
cd C:\JavaProjects
nginx
CopyEdit
javac TestJava.java
nginx
CopyEdit
java TestJava
6. Expected output:
csharp
CopyEdit
OOP with JAVA
csharp
CopyEdit
OOP with JAVA
csharp
CopyEdit
OOP with JAVA
Practical-3
Aim: Develop a basic java program that demonstrates data types of JAVA.
public class DataTypesDemo {
public static void main(String[] args) {
// Integer data type
int age = 25;
Output:
Integer (int) Age: 25
Floating-point (double) Height: 5.9
Character (char) Grade: A
Boolean is Java Fun?: true
String Message: Learning Java Data Types
Byte Value: 10
Short Value: 3000
Long Value: 1000000000
Float Value: 3.1415
Practical-4
Aim: Develop a Java program to swap two numbers without using a temporary
variable and with using a temporary variable (use command line argument to
accept value from user).
public class SwapNumbers {
public static void main(String[] args) {
// Check if two arguments are provided
if (args.length < 2) {
System.out.println("Please provide two numbers as command-line arguments.");
return;
}
System.out.println("Before Swapping:");
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
Output:
Before Swapping:
Number 1: 10
Number 2: 20
Practical-5
Aim: Develop programs to demonstrate use of - 1) if statement and its different
form 2) switch case statement
import java.util.Scanner;
// Simple if statement
if (number > 0) {
System.out.println("The number is positive.");
}
// if-else statement
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
// if-else-if ladder
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
scanner.close();
}
}
Output:
Enter a number: 5
The number is positive.
The number is odd.
The number is positive.
Practical-6
Aim: Develop program to demonstrate use of1) for loop 2) ‘while’ and ‘do while’
loop
For loop:
Output:
Numbers from 1 to 10 using for loop:
1 2 3 4 5 6 7 8 9 10
While loop:
public class WhileLoopDemo {
public static void main(String[] args) {
int i = 2; // Start from 2
System.out.println("Even numbers from 1 to 10 using while loop:");
Output:
Even numbers from 1 to 10 using while loop:
2 4 6 8 10
Do..while :
import java.util.Scanner;
Output:
Enter a number (enter 5 to stop): 3
Enter a number (enter 5 to stop): 8
Enter a number (enter 5 to stop): 5
You entered 5, program terminated.
Practical-7
Aim: Develop a Java program to find maximum and minimum numbers from array
elements.
import java.util.Scanner;
Output:
Enter the number of elements: 5
Enter 5 numbers:
38162
Minimum number: 1
Maximum number: 8
Practical-8
Aim: Develop a basic java program that demonstrates the use of Class & Object.
// Defining a class
class Car {
// Attributes (variables)
String brand;
int speed;
Output:
Car Brand: Toyota
Car Speed: 120 km/h
Practical-9
Aim: Develop a java program to find the factorial of a given number using a
recursive function.
import java.util.Scanner;
scanner.close();
}
}
Output:
Enter a number: 5
Factorial of 5 is: 120
Practical-10
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
Output:
Sum of 5 and 10: 15
Sum of 2, 3, and 4: 9
Sum of 4.5 and 3.2: 7.7
Practical-11
Aim: Develop a program for implementation of different functions of String class .
// String Length
System.out.println("Length of the string: " + str.length());
// Convert to Uppercase
System.out.println("Uppercase: " + str.toUpperCase());
// Convert to Lowercase
System.out.println("Lowercase: " + str.toLowerCase());
// Extract Substring
System.out.println("Substring (7 to 11): " + str.substring(7, 11));
// Replace a Word
System.out.println("Replace 'Java' with 'Python': " + str.replace("Java", "Python"));
// Trim Spaces
String spacedStr = " Hello World ";
System.out.println("Trimmed String: '" + spacedStr.trim() + "'");
}
}
Output:
Length of the string: 24
Uppercase: HELLO, JAVA PROGRAMMING!
Lowercase: hello, java programming!
Contains 'Java': true
Substring (7 to 11): Java
Replace 'Java' with 'Python': Hello, Python Programming!
Index of 'J': 7
Starts with 'Hello': true
Ends with '!': true
Trimmed String: 'Hello World'
Practical-12
Aim: Develop a program for implementation of Wrapper Class to convert
primitive value into object (Boxing) and object into primitive value (Un-boxing).
Output:
Primitive int: 10
Boxed Integer object: 10
Auto-Boxed Integer object: 10
Integer Object: 20
Unboxed primitive int: 20
Auto-Unboxed primitive int: 20
Practical-13
Aim: Develop a program with a static block and show that it will be executed
before the main ( ) method in a class.
public class StaticBlockDemo {
// Static block - executes before main()
static {
System.out.println("Static block executed before main() method.");
}
Output:
Static block executed before main() method.
Inside main() method.
Practical-14
class MathOperations {
// Static method to calculate the square of a number
static int square(int num) {
return num * num;
}
Output:
Square of 5: 25
Sum of 10 and 20: 30
Practical-15
class Student {
// Private variables (only accessible within the class)
private String name;
private int age;
Output:
Name: Alice
Age: 20
Practical-16
Aim: Develop a program with an overloaded constructor. Also develop the copy
constructor to create a new object with the state of the existing object.
class Person {
String name;
int age;
// Default Constructor
public Person() {
this.name = "Unknown";
this.age = 0;
}
// Parameterized Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Copy Constructor (creates a new object with the state of an existing object)
public Person(Person p) {
this.name = p.name;
this.age = p.age;
}
person2.display();
Output:
Person1: Name: Unknown, Age: 0
Person2: Name: Alice, Age: 25
Person3 (Copy of Person2): Name: Alice, Age: 25
Practical-17
Aim: Develop a program to demonstrate the use of private constructor and also
write a method which will count the number of instances created using default
constructor only.
class InstanceCounter {
private static int count = 0; // Static variable to count instances
// Private Constructor
private InstanceCounter() {
count++; // Increments count when an object is created
}
Output:
Total instances created: 3
Practical-18
System.out.println("\nMultilevel Inheritance:");
puppy.eat(); // Inherited from Animal
puppy.bark(); // Inherited from Dog
puppy.weep();
Output:
Single Inheritance:
This animal eats food.
Dog barks.
Multilevel Inheritance:
This animal eats food.
Dog barks.
Puppy weeps.
Hierarchical Inheritance:
This animal eats food.
Cat meows.
Practical-19
Aim: Develop a program with one class named shape which has two member
functions named erase () and draw (). In the program we have three other
subclasses: circle, triangle and square. override methods of the superclass into
subclasses.
// Base class
class Shape {
// Method to be overridden
void draw() {
System.out.println("Drawing a shape.");
}
void erase() {
System.out.println("Erasing a shape.");
}
}
// Subclass 1: Circle
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle.");
}
@Override
void erase() {
System.out.println("Erasing a Circle.");
}
}
// Subclass 2: Triangle
class Triangle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Triangle.");
}
@Override
void erase() {
System.out.println("Erasing a Triangle.");
}
}
// Subclass 3: Square
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a Square.");
}
void erase() {
System.out.println("Erasing a Square.");
}
}
System.out.println("\nTriangle:");
shape2.draw();
shape2.erase();
System.out.println("\nSquare:");
shape3.draw();
shape3.erase();
}
}
Output:
Circle:
Drawing a Circle.
Erasing a Circle.
Triangle:
Drawing a Triangle.
Erasing a Triangle.
Square:
Drawing a Square.
Erasing a Square.
Practical-20
// Superclass
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
// Subclass 1: Dog
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
// Subclass 2: Cat
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
}
}
Output:
Dog barks
Cat meows
Practical-21
Aim: Develop a java program that demonstrates the use of Abstract class.
// Abstract class
abstract class Shape {
// Abstract method (to be implemented by subclasses)
abstract void draw();
// Subclass 1: Circle
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a Circle.");
}
}
// Subclass 2: Square
class Square extends Shape {
@Override
void draw() {
System.out.println("Drawing a Square.");
}
}
// Calling methods
shape1.display(); // Calls concrete method from Shape
shape1.draw(); // Calls overridden method in Circle
shape2.display();
shape2.draw(); // Calls overridden method in Square
}
}
Output:
This is a shape.
Drawing a Circle.
This is a shape.
Drawing a Square.
Practical-22
Aim: Develop a java program that illustrates interface inheritance. Interface ‘A1’
and ‘A2’ are extended from interface ‘A’. Interface ‘A12’ inherited from both
‘A1’and ‘A2’. Each interface declares one method and one constant. Class
‘Interface_Imple’ implements ‘A12’. Instantiate ‘Interface_Imple’ and invoke each
of its methods. Each method displays one of the constants.
// Base interface
interface A {
int CONST_A = 10; // Constant in A
void methodA(); // Abstract method in A
}
// Interface A1 extends A
interface A1 extends A {
int CONST_A1 = 20; // Constant in A1
void methodA1(); // Abstract method in A1
}
// Interface A2 extends A
interface A2 extends A {
int CONST_A2 = 30; // Constant in A2
void methodA2(); // Abstract method in A2
}
@Override
public void methodA1() {
System.out.println("Inside methodA1, CONST_A1: " + CONST_A1);
}
@Override
public void methodA2() {
System.out.println("Inside methodA2, CONST_A2: " + CONST_A2);
}
@Override
public void methodA12() {
System.out.println("Inside methodA12, CONST_A12: " + CONST_A12);
}
}
// Calling methods
obj.methodA();
obj.methodA1();
obj.methodA2();
obj.methodA12();
}
}
Output:
Inside methodA, CONST_A: 10
Inside methodA1, CONST_A1: 20
Inside methodA2, CONST_A2: 30
Inside methodA12, CONST_A12: 40
Practical-23
Aim: Develop a program to create a Package and demonstrate how packages are
used in java. And use java access modifier to demonstrate the access rules in a
package.
Output:
Public: Accessible everywhere
Private: Accessible only within this class
Practical-24
Aim: Develop a program to demonstrate the use of ‘super’ and ‘final’ keywords
// Parent class
class Parent {
int num = 100;
// Constructor
Parent() {
System.out.println("Parent class constructor.");
}
}
void display() {
System.out.println("Child class variable num: " + num);
System.out.println("Parent class variable num using super: " + super.num);
}
Output:
Parent class constructor.
Child class constructor.
Child class variable num: 200
Parent class variable num using super: 100
This is a final method in Parent class.
Value of PI: 3.14159
Practical-25
Aim: Develop programs to demonstrate the use of Exception Handling using
predefined Exception Classes.
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
try {
// 2. ArrayIndexOutOfBoundsException
int[] numbers = {1, 2, 3};
System.out.println("Fourth element: " + numbers[3]); // Out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
try {
// 3. NullPointerException
String str = null;
System.out.println("String length: " + str.length()); // This will throw
NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
}
Output:
Practical-26
Aim: Develop a program to handle multiple exceptions using multiple try blocks
and multiple catch blocks.
try {
// Second Try Block: ArrayIndexOutOfBoundsException
int[] numbers = {1, 2, 3};
System.out.println("Fourth element: " + numbers[3]); // Out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
}
try {
// Third Try Block: NullPointerException
String str = null;
System.out.println("String length: " + str.length()); // This will throw
NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException: " + e.getMessage());
Output:
Practical-28
Aim: Develop a program to demonstrate use of throw, throws, and finally
keyword.
Output:
Caught Exception: Number cannot be negative!
Finally block executed: Cleaning up resources...
Program continues after handling exceptions.
Practical-29
Aim: Develop a program that executes two threads. One thread displays “Java
Programming” every 2 seconds, and the other displays “Semester - 4th” every 5
seconds.(Create the threads by extending the Thread class)
// Main Class
public class MultiThreadDemo {
public static void main(String[] args) {
// Creating thread objects
JavaThread thread1 = new JavaThread();
SemesterThread thread2 = new SemesterThread();
Output:
Java Programming
Java Programming
Semester - 4th
Java Programming
Java Programming
Java Programming
Semester - 4th
...
Practical-30
Aim: Develop a program that executes two threads. One thread will print the even
numbers and the another thread will print odd numbers between 1 to 10.(Create the
thread by implementing runnable interface)
// Main Class
public class EvenOddThreadDemo {
public static void main(String[] args) {
// Creating runnable objects
EvenNumberThread evenTask = new EvenNumberThread();
OddNumberThread oddTask = new OddNumberThread();
Output:
Even: 2
Odd: 1
Even: 4
Odd: 3
Even: 6
Odd: 5
Even: 8
Odd: 7
Even: 10
Odd: 9
Practical-31
Aim: Develop a program to demonstrate use of synchronization of threads when
multiple threads are trying to update a common variable.
Output:
Final count: 2000
Practical-32
Aim: Develop programs to create, write, modify, read operations on Text files.
import java.io.*;
}
}
// Create file
createFile(fileName);