Java_Practical_Lab_Manuals
Java_Practical_Lab_Manuals
Institute of Management
Studies (RBIMS)
LAB MANUAL
FOR
OBJECT ORIENTED PROGRAMMING IN
JAVA(OOPJ) (619402)
PREPARED BY
Ranjit Mukeshbhai Vaghela
SUBMITTED TO
MR. ROHAN SOLANKI
(Assistant Professor)
JAVA PRACTICAL BOOK
DEPARTMENT OF MCA
PREFACE
It gives us immense pleasure to present the first edition of Java Practical Book for the MCA
1st year students of R.B. Institute of management and studies. The Java theory and
laboratory course is designed in such a way that students develop the basic understanding
of the subject in the theory classes and gain hands-on practical experience during their
laboratory sessions. The Lab Manual has been designed in such a way that students will get
exposure to different kinds of programs. Difficulty level of programs is increased with each
subsequent practical. Students will get an opportunity to use various set of instructions. It
will surely help students to recall the theoretical knowledge acquired during lectures and
apply it for practical execution of practical. Hopefully this JAVA Practical Book will serve the
10 Create a class “Student” that would contain enrollment No, name, and
gender and marks as instance variables and count as static variable which
stores the count of the objects; constructors and display(). Implement
constructors to initialize instance variables. Also demonstrate constructor
chaining. Create objects of class “Student” and displays all values of
objects.
11 Write a program in Java to demonstrate use of this keyword. Check
whether this can access the Static variables of the class or not. [Refer
class student in Q12 to perform the task]
14 Write programs in Java to use Wrapper class of each primitive data types.
17 Describe abstract class called Shape which has three subclasses say
Triangle, Rectangle, and Circle. Define one method area () in the abstract
class and override this area () in these three subclasses to calculate for
specific object i.e. area () of Triangle subclass should calculate area of
triangle etc. Same for Rectangle and Circle
18 Assume that there are two packages, student and exam. A student
package contains Student class and the exam package contains Result
class. Write a program that generates mark sheet for students.
19 Write a java program to implement Generic class Number_1 for both data
type int and float in java.
System.out.println("Hello World");
Output:
Hello World
2 Write a program to pass Starting and Ending limit and print all prime numbers and
Fibonacci numbers between this ranges.
import java.util.Scanner;
System.out.print("Prime numbers between " + start + " and " + end + ": ");
for (int num = start; num <= end; num++) {
if (isPrime(num)) {
System.out.print(num + " ");
}
}
System.out.println();
System.out.print("Fibonacci numbers between " + start + " and " + end + ": ");
printFibonacci(start, end);
System.out.println();
scanner.close();
}
}
Output:
Enter the starting limit: 10
Enter the ending limit: 20
Prime numbers between 10 and 20: 11 13 17 19
Fibonacci numbers between 10 and 20: 13
import java.util.Scanner;
int n, s=0,c,r;
System.out.println("Enter any number ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
c=n;
r= n%10;
s=(s*10)+r;
n=n/10;
if(c==s) {
System.out.println("Palindrome No");
}
else {
System.out.println(" It is not Palindrome number ");
}
sc.close();
}
}
Output:
Enter any number
528
It is notPalindrome number
Output:
Enter the base (x): 5
Enter the exponent (n): 3
5^3 = 125
import java.util.Scanner;
scanner.close();
}
}
Output:
Enter a number: 56
56 is not an Armstrong number.
6 Write a program in Java to find minimum of three numbers using conditional operator.
import java.util.Scanner;
Output:
Enter first number: 25
Enter second number: 12
Enter third number: 1
The minimum of the three numbers is: 1
7 Write a java program which should display maximum number of given 4 numbers.
import java.util.Scanner;
scanner.close();
}
}
Output:
Enter first number: 25
Enter second number: 11
Enter third number: 12
Enter fourth number: 48
The maximum of the four numbers is: 48
8 Write a Java application which takes several command line arguments, which are
supposed to be names of students and prints output as given below: (Suppose we
enter 3 names then output should be as follows).. Number of arguments = 3
Output:
Enter first number: 25
Enter second number: 11
Enter third number: 12
Enter fourth number: 48
The maximum of the four numbers is: 48
9 Write a Java application to count and display frequency of letters and digits from the
String given by user as command-line argument.
public class LetterDigitFrequency {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java LetterDigitFrequency <input-string>");
return;
}
System.out.println("Letter Frequency:");
for (int i = 0; i < letterCount.length; i++) {
if (letterCount[i] > 0) {
System.out.println((char) (i + 'a') + ": " + letterCount[i]);
}
}
System.out.println("\nDigit Frequency:");
for (int i = 0; i < digitCount.length; i++) {
if (digitCount[i] > 0) {
System.out.println(i + ": " + digitCount[i]);
}
}
}
}
Output:
Letter Frequency:
d: 1
e: 1
h: 1
l: 3
o: 2
r: 1
w: 1
Digit Frequency:
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
10 Create a class “Student” that would contain enrollment No, name, and gender and
marks as instance variables and count as static variable which stores the count of the
objects; constructors and display(). Implement constructors to initialize instance
variables. Also demonstrate constructor chaining. Create objects of class “Student”
and displays all values of objects.
class Ten_Student {
private int enrollmentNo;
private String name;
private String gender;
private double marks;
private static int count = 0; //for count object
public Ten_Student() {
this(0, "NO Name", "NO Gender", 0.0); // Constructor chaining
}
System.out.println("Student 1 Details:");
student1.display();
System.out.println("\nStudent 2 Details:");
student2.display();
System.out.println("\nStudent 3 Details:");
student3.display();
Student 2 Details:
Enrollment No: 101
Name: Ranjit
Gender: NO Gender
Marks: 0.0
Student 3 Details:
Enrollment No: 102
Name: Tirth
Gender: Female
Marks: 85.5
class Example_11 {
private int instanceVariable;
private static int staticVariable;
public Example_11(int instanceVariable) {
this.instanceVariable = instanceVariable;
staticVariable++;
}
public void display() {
System.out.println("Instance Variable: " + this.instanceVariable);
Output:
Instance Variable: 5
Static Variable (via class): 2
Instance Variable: 10
Static Variable (via class): 2
Static Variable accessed through class: 2
12 Create a class “Rectangle” that would contain length and width as an instance variable
and count as a static variable. Define constructors [constructor overloading (default,
parameterized and copy)] to initialize variables of objects. Define methods to find area
and to display variables’ value of objects which are created. [Note: define initializer
block, static initializer block and the static variable and method. Also demonstrate the
sequence of execution of initializer block and static initialize block]
class Rectangle_12 {
private double length;
private double width;
private static int count;
static {
count = 0;
System.out.println("Static Initializer Block: Class loaded, count initialized to 0.");
}
{
System.out.println("Instance Initializer Block: Object is being initialized.");
}
// Default constructor
public Rectangle_12() {
this(0, 0); // Calls the parameterized constructor
System.out.println("Default Constructor: Rectangle created with default values.");
}
// Parameterized constructor
public Rectangle_12(double length, double width) {
this.length = length;
this.width = width;
count++; // Increment the static count for every object created
System.out.println("Parameterized Constructor: Rectangle created with given values.");
}
// Copy constructor
public Rectangle_12(Rectangle_12 other) {
this(other.length, other.width); // Calls the parameterized constructor
System.out.println("Copy Constructor: Rectangle created by copying another
rectangle.");
}
// Static method to get the current count of Rectangle objects
public static int getCount12() {
return count;
}
// Creating objects
Rectangle_12 rect1 = new Rectangle_12();
rect1.display();
System.out.println();
System.out.println();
System.out.println();
static {
System.out.println("Static Block: Executed before the main() method.");
System.out.println("Static Block: Initializing resources or performing setup.");
}
//main
public static void main(String[] args) {
System.out.println("Main Method: Program execution starts from here.");
}
}
Output:
Static Block: Executed before the main() method.
Static Block: Initializing resources or performing setup.
Main Method: Program execution starts from here.
14 Write programs in Java to use Wrapper class of each primitive data types.
// 2. Double (double)
double primitiveDouble = 25.75;
Double wrapperDouble = Double.valueOf(primitiveDouble); // Boxing
double unboxedDouble = wrapperDouble.doubleValue(); // Unboxing
System.out.println("Double Wrapper: " + wrapperDouble);
System.out.println("Unboxed Double: " + unboxedDouble);
// 3. Float (float)
float primitiveFloat = 12.34f;
Float wrapperFloat = Float.valueOf(primitiveFloat); // Boxing
float unboxedFloat = wrapperFloat.floatValue(); // Unboxing
System.out.println("Float Wrapper: " + wrapperFloat);
System.out.println("Unboxed Float: " + unboxedFloat);
// 4. Long (long)
long primitiveLong = 123456789L;
Long wrapperLong = Long.valueOf(primitiveLong); // Boxing
long unboxedLong = wrapperLong.longValue(); // Unboxing
System.out.println("Long Wrapper: " + wrapperLong);
System.out.println("Unboxed Long: " + unboxedLong);
// 5. Short (short)
short primitiveShort = 100;
Short wrapperShort = Short.valueOf(primitiveShort); // Boxing
short unboxedShort = wrapperShort.shortValue(); // Unboxing
System.out.println("Short Wrapper: " + wrapperShort);
System.out.println("Unboxed Short: " + unboxedShort);
// 6. Byte (byte)
byte primitiveByte = 50;
Byte wrapperByte = Byte.valueOf(primitiveByte); // Boxing
byte unboxedByte = wrapperByte.byteValue(); // Unboxing
System.out.println("Byte Wrapper: " + wrapperByte);
System.out.println("Unboxed Byte: " + unboxedByte);
// 7. Boolean (boolean)
boolean primitiveBoolean = true;
Boolean wrapperBoolean = Boolean.valueOf(primitiveBoolean); // Boxing
boolean unboxedBoolean = wrapperBoolean.booleanValue(); // Unboxing
System.out.println("Boolean Wrapper: " + wrapperBoolean);
System.out.println("Unboxed Boolean: " + unboxedBoolean);
// 8. Character (char)
char primitiveChar = 'A';
Character wrapperChar = Character.valueOf(primitiveChar); // Boxing
char unboxedChar = wrapperChar.charValue(); // Unboxing
System.out.println("Character Wrapper: " + wrapperChar);
System.out.println("Unboxed Character: " + unboxedChar);
}
}
Output:
Integer Wrapper: 10
Unboxed Integer: 10
Double Wrapper: 25.75
Unboxed Double: 25.75
Float Wrapper: 12.34
Unboxed Float: 12.34
Long Wrapper: 123456789
Unboxed Long: 123456789
Short Wrapper: 100
Unboxed Short: 100
Byte Wrapper: 50
Unboxed Byte: 50
Boolean Wrapper: true
Unboxed Boolean: true
Character Wrapper: A
Unboxed Character: A
15 Create a class “Vehicle” with instance variable vehicle_type. Inherit the class in a class
called “Car” with instance model_type, company name etc.
display the information of the vehicle by defining the display() in both super and sub
class [ Method Overriding]
class Vehicle {
String vehicleType;
Vehicle(String vehicleType) {
this.vehicleType = vehicleType;
}
void display() {
System.out.println("Vehicle Type: " + vehicleType);
}
}
@Override
void display() {
super.display();
System.out.println("Model Type: " + modelType);
System.out.println("Company Name: " + companyName);
}
}
myCar.display();
}
}
Output:
Vehicle Type: Four Wheeler
Model Type: RJ1
Company Name: Toyota
16 Write a program in Java to demonstrate the use of 'final' keyword in the field
declaration. How it is accessed using the objects.
class FinalFieldExample {
// Declaring final field
final int CONSTANT_VALUE = 100;
Output:
Accessing values using obj1:
CONSTANT_VALUE: 100
instanceValue: 200
@Override
void area() {
double result = 0.5 * base * height;
System.out.println("Area of Triangle: " + result);
}
}
@Override
void area() {
double result = length * width;
System.out.println("Area of Rectangle: " + result);
}
}
Circle(double radius) {
this.radius = radius;
}
@Override
void area() {
double result = Math.PI * radius * radius;
System.out.println("Area of Circle: " + result);
}
}
triangle.area();
rectangle.area();
circle.area();
}
}
Output:
Area of Triangle: 25.0
Area of Rectangle: 24.0
Area of Circle: 28.274333882308138
18 Assume that there are two packages, student and exam. A student package contains
Student class and the exam package contains Result class. Write a program that
generates mark sheet for students.
import student.student;
import exam.result;
result.generateMarksheet(student);
}
}
package student;
import student.student;
Output:
Marksheet for: Ranjit
Roll Number:176
Marks :
Subject1 :50
Subject :50
Total Marks: 100
Average Marks: 50
19 Write a java program to implement Generic class Number_1 for both data type int and
float in java.
Output:
The number is: 10
Double value: 10.0
The number is: 10.5
Double value: 10.5
20 Write a java program to accept string to check whether it is in Upper or Lower case.
After checking, case will be reversed.
import java.util.Scanner;
if (input.equals(input.toUpperCase())) {
System.out.println("The string is in uppercase.");
} else if (input.equals(input.toLowerCase())) {
System.out.println("The string is in lowercase.");
} else {
System.out.println("The string is mixed case.");
}
Output:
Enter a string: Ranjit
The string is mixed case.
Reversed case string: rANJIT
// 4. toLowerCase() and toUpperCase(): Converts the string to lower and upper case
System.out.println("Lowercase: " + originalString.toLowerCase());
System.out.println("Uppercase: " + originalString.toUpperCase());
// 12. isEmpty() and isBlank(): Checks if the string is empty or contains only whitespace
String emptyString = "";
System.out.println("Is empty: " + emptyString.isEmpty());
System.out.println("Is blank: '" + " ".isEmpty() + "'");
}
}
Output:
Length: 17
Character at index 7: ,
Substring from index 3 to 8: ello,
Lowercase: hello, world!
Uppercase: HELLO, WORLD!
Trimmed: 'Hello, World!'
Index of 'World': 9
Replace 'World' with 'Java': Hello, Java!
Contains 'Hello': true
Starts with ' Hello': true
Ends with '! ': true
Equals (case-sensitive): false
Equals (case-insensitive): true
Split into parts:
- Hello
- World!
Is empty: true
Is blank: 'false'
22 Write a program in Java to demonstrate use of final class, final variable and final
method.
// A final method cannot be overridden by subclasses (if the class were not final)
final void display() {
System.out.println("This is a final method.");
}
}
Output:
Value of final variable: 100
This is a final method.
23 Write a program in Java to demonstrate throw, throws, finally, multiple try block and
multiple catch exception.
import java.util.Scanner;
try {
// First try block
System.out.print("Enter a number: ");
int num = scanner.nextInt();
checkNumber(num); // Method may throw IllegalArgumentException
} catch (IllegalArgumentException e) {
// First catch block
System.out.println("Caught an exception: " + e.getMessage());
} finally {
// `finally` block ensures execution
System.out.println("First try-catch block is complete.");
}
try {
// Second try block
System.out.print("Enter a divisor: ");
int divisor = scanner.nextInt();
int result = 10 / divisor; // May throw ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Second catch block
System.out.println("Caught an exception: Division by zero is not allowed.");
} catch (Exception e) {
// General catch block for any other exceptions
System.out.println("Caught a general exception: " + e.getMessage());
} finally {
// `finally` block ensures execution
System.out.println("Second try-catch block is complete.");
}
Output:
Enter a number: 15
Number is valid: 15
First try-catch block is complete.
Enter a divisor: 0
Caught an exception: Division by zero is not allowed.
Second try-catch block is complete.
Program execution continues...
24 Write a program to implement the concept of threading by extending “Thread” Class.
Output:
Main thread execution continues...
Thread-1 - Count: 1
Thread-2 - Count: 1
Thread-1 - Count: 2
Thread-2 - Count: 2
Thread-1 - Count: 3
Thread-2 - Count: 3
25 Write a program to implement the concept of threading by implementing “Runnable”
Interface.
// A class that implements Runnable
class MyRunnable implements Runnable {
// Override the run method to define the thread's task
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " - Count: " + i);
try {
Thread.sleep(500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
}
}
}
Output:
Main thread execution continues...
Thread-1 - Count: 1
Thread-2 - Count: 1
Thread-1 - Count: 2
Thread-2 - Count: 2
Thread-1 - Count: 3
Thread-2 - Count: 3
Thread-2 - Count: 4
Thread-1 - Count: 4
Thread-1 - Count: 5
Thread-2 - Count: 5
import java.util.ArrayList;
import java.util.Scanner;
// Employee class
class Employee {
private int empCode;
private String empName;
private double basicSal;
private double grossSal;
// Constructor
public Employee(int empCode, String empName, double basicSal) {
this.empCode = empCode;
this.empName = empName;
this.basicSal = basicSal;
this.grossSal = calculateGrossSal();
}
Output:
Employee List:
Emp Code: 101, Name: Alice, Basic Salary: 50000.0, Gross Salary: 65000.0
Emp Code: 102, Name: Bob, Basic Salary: 60000.0, Gross Salary: 78000.0
Emp Code: 103, Name: Charlie, Basic Salary: 55000.0, Gross Salary: 71500.0
27 Sort “Student” Linked List (mentioned in Q:1) based on std_name using “Comparator”
interface.
import java.util.LinkedList;
import java.util.Collections;
import java.util.Comparator;
class Student {
private int rollNo;
private String stdName;
public Student(int rollNo, String stdName) {
this.rollNo = rollNo;
this.stdName = stdName;
}
public int getRollNo() {
return rollNo;
}
public String getStdName() {
return stdName;
}
public void display() {
System.out.println("Roll No: " + rollNo + ", Name: "
+ stdName);
}}
public class Comparator_27 {
public static void main(String[] args) {
LinkedList<Student> students = new LinkedList<>();
students.add(new Student(101, "Arun"));
students.add(new Student(103, "Charlie"));
students.add(new Student(102, "Bob"));
System.out.println("Unsorted Student List:");
for (Student student : students) {
student.display();
}
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getStdName().compareTo(s2.getStdName());
}
});
System.out.println("\nSorted Student List:");
for (Student student : students) {
student.display();
}
}
}
Output:
Unsorted Student List:
Roll No: 101, Name: Ranjit
Roll No: 103, Name: Isha
Roll No: 102, Name: Aakash
@Override
public void run() {
account.withdraw(amount);
}
}
// Starting threads
t1.start();
t2.start();
t3.start();
}
}
Output:
Thread-1 is about to withdraw: 700
Thread-1 completed withdrawal. Remaining balance: 300
Thread-3 is about to withdraw: 300
Thread-3 completed withdrawal. Remaining balance: 0
Thread-2 cannot withdraw. Insufficient balance.