R. B.
Institute of Management
Studies (RBIMS)
LAB MANUAL
FOR
OBJECT ORIENTED PROGRAMMING IN
JAVA(OOPJ) (619402)
INTEGRATED MASTER OF COMPUTER
APPLICATIONS (MCA)
I SEMESTER
2024-2025
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
purpose for which it has been developed.
Lab Manual Prepared By:
Mr. Rohan Solanki.
Assistant Professor
MCA Department
RBIMS
INDEX
SR PROGRAMS PAGE
NO NO
1 Install the JDK (Download the JDK and install it.) · Set path of the jdk/bin
directory. · Create the java program · Compile and run the java program
Write a simple “Hello World” java program, compilation, debugging,
executing using java compiler and interpreter.
2 Write a program to pass Starting and Ending limit and print all prime
numbers and Fibonacci numbers between this ranges.
3 Write a java program to check whether number is palindrome or not.
Input: 528 Output: It is not palindrome number
4 Write a java program to print value of x^n.
5 Write a java program to check
Armstrong number. Input: 153
6 Write a program in Java to find minimum of three numbers using
conditional operator.
7 Write a java program which should display maximum number of given 4
numbers.
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
1.: First Student Name is = Arun
2.: Second Student Name is = Hiren
[Link] Student Name is = Hitesh
9 Write a Java application to count and display frequency of letters and
digits from the String given by user as command-line argument.
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]
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]
13 Write a java program static block which will be executed before main ( )
method in a class.
14 Write programs in Java to use Wrapper class of each primitive data types.
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]
16 Write a program in Java to demonstrate the use of 'final' keyword in the
field declaration. How it is accessed using the objects.
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.
20 Write a java program to accept string to check whether it is in Upper or
Lower case. After checking, case will be reversed.
21 Write a java program to use important methods of String class
22 Write a program in Java to demonstrate use of final class, final variable
and final method.
23 Write a program in Java to demonstrate throw, throws, finally, multiple try
block and multiple catch exception.
24 Write a program to implement the concept of threading by extending
“Thread” Class.
25 Write a program to implement the concept of threading by implementing
“Runnable” Interface.
26 Develop a program to create Array List for “Employee” class objects
references. Employee class has emp_code, emp_name, basic_sal, gross_
sal. Calculate gross_sal for all employees of Array List. Display Array List
and also insert an employee object reference in a particular position
(input) in Array List.
27 Sort “Student” Linked List (mentioned in Q:1) based on std_name using
“Comparator” interface.
28 Write a program in Java to demonstrate use of synchronization of threads
when multiple threads are trying to update common variable for
“Account” class.
1 Install the JDK (Download the JDK and install it.) · Set path of the jdk /bin directory. ·
Create the java program · Compile and run the java program Write a simple “Hello
World” java program, compilation, debugging, executing using java compiler and
interpreter.
public class FirstProgram {
public static void main(String[] args) {
// TODO Auto-generated method stub
[Link]("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 [Link];
public class Second_PrimeAndFibbo {
public static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
public static void printFibonacci(int start, int end) {
int a = 0, b = 1;
while (a <= end) {
if (a >= start) {
[Link](a + " ");
}
int next = a + b;
a = b;
b = next;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the starting limit: ");
int start = [Link]();
[Link]("Enter the ending limit: ");
int end = [Link]();
[Link]("Prime numbers between " + start + " and " + end + ": ");
for (int num = start; num <= end; num++) {
if (isPrime(num)) {
[Link](num + " ");
}
}
[Link]();
[Link]("Fibonacci numbers between " + start + " and " + end + ": ");
printFibonacci(start, end);
[Link]();
[Link]();
}
}
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
3 Write a java program to check whether number is palindrome or not.
Input: 528 Output: It is not palindrome number
import [Link];
public class ThreePolindromeOrNot {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n, s=0,c,r;
[Link]("Enter any number ");
Scanner sc = new Scanner([Link]);
n = [Link]();
c=n;
while(n > 0){
r= n%10;
s=(s*10)+r;
n=n/10;
if(c==s) {
[Link]("Palindrome No");
}
else {
[Link](" It is not Palindrome number ");
}
[Link]();
}
}
Output:
Enter any number
528
It is notPalindrome number
4 Write a java program to print value of x^n.
import [Link];
public class Four_PowerCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the base (x): ");
int x = [Link]();
[Link]("Enter the exponent (n): ");
int n = [Link]();
long result = 1; // Use long to handle large results
for (int i = 0; i < n; i++) {
result *= x;
}
// Print the result
[Link](x + "^" + n + " = " + result);
[Link]();
}
}
Output:
Enter the base (x): 5
Enter the exponent (n): 3
5^3 = 125
5 Write a java program to check
Armstrong number. Input: 153
import [Link];
public class Five_Armstrong_Number {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.i
[Link]("Enter a number: ");
int number = [Link]();
int originalNumber = number;
int sum = 0;
int digits = [Link](number).length(); // Number of digits in the number
// Check if the number is an Armstrong number
while (number > 0) {
int digit = number % 10;
sum += [Link](digit, digits); // Raise digit to the power of the number of digits
number /= 10;
}
// Output the result
if (sum == originalNumber) {
[Link](originalNumber + " is an Armstrong number.");
} else {
[Link](originalNumber + " is not an Armstrong number.");
}
[Link]();
}
}
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 [Link];
public class Six_min_of_three {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter first number: ");
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();
[Link]("Enter third number: ");
int num3 = [Link]();
int min = (num1 < num2) ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 :
num3);
[Link]("The minimum of the three numbers is: " + min);
[Link]();
}
}
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 [Link];
public class Seven_Max_in_Four {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter first number: ");
int num1 = [Link]();
[Link]("Enter second number: ");
int num2 = [Link]();
[Link]("Enter third number: ");
int num3 = [Link]();
[Link]("Enter fourth number: ");
int num4 = [Link]();
int max = (num1 > num2)
? (num1 > num3 ? (num1 > num4 ? num1 : num4) : (num3 > num4 ? num3 : num4))
: (num2 > num3 ? (num2 > num4 ? num2 : num4) : (num3 > num4 ? num3 : num4));
[Link]("The maximum of the four numbers is: " + max);
[Link]();
}
}
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
1.: First Student Name is = Arun
2.: Second Student Name is = Hiren
[Link] Student Name is = Hitesh
public class Eight_StudentNames {
public static void main(String[] args) {
[Link]("Number of arguments = " + [Link]);
// Print each student's name
for (int i = 0; i < [Link]; i++) {
[Link]((i + 1) + ".: Student Name is = " + args[i]);
}
}
}
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 ([Link] != 1) {
[Link]("Usage: java LetterDigitFrequency <input-string>");
return;
}
String input = args[0];
int[] letterCount = new int[26]; // Array to store frequency of each letter
int[] digitCount = new int[10]; // Array to store frequency of each digit
for (char ch : [Link]()) {
if ([Link](ch)) {
letterCount[[Link](ch) - 'a']++;
} else if ([Link](ch)) {
digitCount[ch - '0']++;
}
}
[Link]("Letter Frequency:");
for (int i = 0; i < [Link]; i++) {
if (letterCount[i] > 0) {
[Link]((char) (i + 'a') + ": " + letterCount[i]);
}
}
[Link]("\nDigit Frequency:");
for (int i = 0; i < [Link]; i++) {
if (digitCount[i] > 0) {
[Link](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
}
public Ten_Student(int enrollmentNo, String name) {
this(enrollmentNo, name, "NO Gender", 0.0); // Constructor chaining
public Ten_Student(int enrollmentNo, String name, String gender, double marks) {
[Link] = enrollmentNo;
[Link] = name;
[Link] = gender;
[Link] = marks;
count++; // Increment the count of objects
}
public static int getCount() {
return count;
}
public void display() {
[Link]("Enrollment No: " + enrollmentNo);
[Link]("Name: " + name);
[Link]("Gender: " + gender);
[Link]("Marks: " + marks);
}
// Main method to demonstrate the functionality of classes
public static void main(String[] args) {
Ten_Student student1 = new Ten_Student();
Ten_Student student2 = new Ten_Student(101, "Ranjit");
Ten_Student student3 = new Ten_Student(102, "Tirth", "Female", 85.5);
[Link]("Student 1 Details:");
[Link]();
[Link]("\nStudent 2 Details:");
[Link]();
[Link]("\nStudent 3 Details:");
[Link]();
[Link]("\nTotal Students Created: " + Ten_Student.getCount());
}
}
Output:
Student 1 Details:
Enrollment No: 0
Name: NO Name
Gender: NO Gender
Marks: 0.0
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
Total Students Created: 3
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]
class Example_11 {
private int instanceVariable;
private static int staticVariable;
public Example_11(int instanceVariable) {
[Link] = instanceVariable;
staticVariable++;
}
public void display() {
[Link]("Instance Variable: " + [Link]);
[Link]("Static Variable (via class): " + Example_11.staticVariable);
}
public static void main(String[] args) {
Example_11 obj1 = new Example_11(5);
Example_11 obj2 = new Example_11(10);
[Link]();
[Link]();
[Link]("Static Variable accessed through class: " +
Example_11.staticVariable);
}
}
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;
[Link]("Static Initializer Block: Class loaded, count initialized to 0.");
}
{
[Link]("Instance Initializer Block: Object is being initialized.");
}
// Default constructor
public Rectangle_12() {
this(0, 0); // Calls the parameterized constructor
[Link]("Default Constructor: Rectangle created with default values.");
}
// Parameterized constructor
public Rectangle_12(double length, double width) {
[Link] = length;
[Link] = width;
count++; // Increment the static count for every object created
[Link]("Parameterized Constructor: Rectangle created with given values.");
}
// Copy constructor
public Rectangle_12(Rectangle_12 other) {
this([Link], [Link]); // Calls the parameterized constructor
[Link]("Copy Constructor: Rectangle created by copying another
rectangle.");
}
// Static method to get the current count of Rectangle objects
public static int getCount12() {
return count;
}
// Method to calculate the area of the rectangle
public double getArea() {
return length * width;
}
// Method to display rectangle details
public void display() {
[Link]("Length: " + length);
[Link]("Width: " + width);
[Link]("Area: " + getArea());
}
// Main method to demonstrate functionality and sequence of execution
public static void main(String[] args) {
// [Link]("Main Method: Program starts.");
// Creating objects
Rectangle_12 rect1 = new Rectangle_12();
[Link]();
[Link]();
Rectangle_12 rect2 = new Rectangle_12(5, 3);
[Link]();
[Link]();
Rectangle_12 rect3 = new Rectangle_12(rect2);
[Link]();
[Link]();
// Displaying total count of Rectangle objects
[Link]("Total Rectangles Created: " + Rectangle_12.getCount12());
}
}
Output:
Main Method: Program starts
53
53
13 Write a java program static block which will be executed before main ( ) method in a
class.
public class StaticBlock_13 {
static {
[Link]("Static Block: Executed before the main() method.");
[Link]("Static Block: Initializing resources or performing setup.");
}
//main
public static void main(String[] args) {
[Link]("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.
public class Wrapper_14 {
public static void main(String[] args) {
// 1. Integer (int)
int primitiveInt = 10;
Integer wrapperInt = [Link](primitiveInt); // Boxing
int unboxedInt = [Link](); // Unboxing
[Link]("Integer Wrapper: " + wrapperInt);
[Link]("Unboxed Integer: " + unboxedInt);
// 2. Double (double)
double primitiveDouble = 25.75;
Double wrapperDouble = [Link](primitiveDouble); // Boxing
double unboxedDouble = [Link](); // Unboxing
[Link]("Double Wrapper: " + wrapperDouble);
[Link]("Unboxed Double: " + unboxedDouble);
// 3. Float (float)
float primitiveFloat = 12.34f;
Float wrapperFloat = [Link](primitiveFloat); // Boxing
float unboxedFloat = [Link](); // Unboxing
[Link]("Float Wrapper: " + wrapperFloat);
[Link]("Unboxed Float: " + unboxedFloat);
// 4. Long (long)
long primitiveLong = 123456789L;
Long wrapperLong = [Link](primitiveLong); // Boxing
long unboxedLong = [Link](); // Unboxing
[Link]("Long Wrapper: " + wrapperLong);
[Link]("Unboxed Long: " + unboxedLong);
// 5. Short (short)
short primitiveShort = 100;
Short wrapperShort = [Link](primitiveShort); // Boxing
short unboxedShort = [Link](); // Unboxing
[Link]("Short Wrapper: " + wrapperShort);
[Link]("Unboxed Short: " + unboxedShort);
// 6. Byte (byte)
byte primitiveByte = 50;
Byte wrapperByte = [Link](primitiveByte); // Boxing
byte unboxedByte = [Link](); // Unboxing
[Link]("Byte Wrapper: " + wrapperByte);
[Link]("Unboxed Byte: " + unboxedByte);
// 7. Boolean (boolean)
boolean primitiveBoolean = true;
Boolean wrapperBoolean = [Link](primitiveBoolean); // Boxing
boolean unboxedBoolean = [Link](); // Unboxing
[Link]("Boolean Wrapper: " + wrapperBoolean);
[Link]("Unboxed Boolean: " + unboxedBoolean);
// 8. Character (char)
char primitiveChar = 'A';
Character wrapperChar = [Link](primitiveChar); // Boxing
char unboxedChar = [Link](); // Unboxing
[Link]("Character Wrapper: " + wrapperChar);
[Link]("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) {
[Link] = vehicleType;
}
void display() {
[Link]("Vehicle Type: " + vehicleType);
}
}
class Car extends Vehicle {
String modelType;
String companyName;
Car(String vehicleType, String modelType, String companyName) {
super(vehicleType);
[Link] = modelType;
[Link] = companyName;
}
@Override
void display() {
[Link]();
[Link]("Model Type: " + modelType);
[Link]("Company Name: " + companyName);
}
}
public class Vehicle_15 {
public static void main(String[] args) {
Car myCar = new Car("Four Wheeler", "Sedan", "Toyota");
[Link]();
}
}
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;
// Declaring another final field with initialization in the constructor
final int instanceValue;
// Constructor to initialize the final field
public FinalFieldExample(int value) {
[Link] = value;
}
// Method to display the values of the final fields
public void display() {
[Link]("CONSTANT_VALUE: " + CONSTANT_VALUE);
[Link]("instanceValue: " + instanceValue);
}
}
public class Final_16 {
public static void main(String[] args) {
// Creating objects of FinalFieldExample
FinalFieldExample obj1 = new FinalFieldExample(200);
FinalFieldExample obj2 = new FinalFieldExample(300);
// Accessing final fields using objects
[Link]("Accessing values using obj1:");
[Link]();
[Link]("\nAccessing values using obj2:");
[Link]();
// Uncommenting the following line would result in a compilation error
// obj1.CONSTANT_VALUE = 500; // Error: cannot assign a value to final variable
}
}
Output:
Accessing values using obj1:
CONSTANT_VALUE: 100
instanceValue: 200
Accessing values using obj2:
CONSTANT_VALUE: 100
instanceValue: 300
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
abstract class GeometricShape {
abstract void area();
}
class Triangle extends GeometricShape {
double base, height;
Triangle(double base, double height) {
[Link] = base;
[Link] = height;
}
@Override
void area() {
double result = 0.5 * base * height;
[Link]("Area of Triangle: " + result);
}
}
class Rectangle17 extends GeometricShape {
double length, width;
Rectangle17(double length, double width) {
[Link] = length;
[Link] = width;
}
@Override
void area() {
double result = length * width;
[Link]("Area of Rectangle: " + result);
}
}
class Circle extends GeometricShape {
double radius;
Circle(double radius) {
[Link] = radius;
}
@Override
void area() {
double result = [Link] * radius * radius;
[Link]("Area of Circle: " + result);
}
}
public class GeometricShape_17 {
public static void main(String[] args) {
GeometricShape triangle = new Triangle(10, 5);
GeometricShape rectangle = new Rectangle17(4, 6);
GeometricShape circle = new Circle(3);
[Link]();
[Link]();
[Link]();
}
}
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 [Link];
import [Link];
public class main {
public static void Main(String[] args) {
int[] marks = {85, 90, 78, 92};
student student = new student("Monjulika", 200, marks);
[Link](student);
}
}
package student;
public class student {
private String name;
private int rollNumber;
private int[] marks;
public student(String name, int rollNumber, int[] marks) {
[Link] = name;
[Link] = rollNumber;
[Link] = marks;
}
public String getName() {
return name;
}
public int getRollNumber() {
return rollNumber;
}
public int[] getMarks() {
return marks;
}
}
package exam;
import [Link];
public class result {
public static void generateMarksheet(student student) {
[Link]("Marksheet for: " + [Link]());
[Link]("Roll Number: " + [Link]());
[Link]("Marks:");
int[] marks = [Link]();
int total = 0;
for (int i = 0; i < [Link]; i++) {
[Link]("Subject " + (i + 1) + ": " + marks[i]);
total += marks[i];
}
double average = (double) total / [Link];
[Link]("Total Marks: " + total);
[Link]("Average Marks: " + average);
}
}
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.
public class Main19 {
public static void main(String[] args) {
// Using Number_1 with Integer
Number_1<Integer> intNumber = new Number_1<>(10);
[Link]();
[Link]("Double value: " + [Link]());
// Using Number_1 with Float
Number_1<Float> floatNumber = new Number_1<>(10.5f);
[Link]();
[Link]("Double value: " + [Link]());
}
}
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 [Link];
public class Upper_Lower_20 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String input = [Link]();
if ([Link]([Link]())) {
[Link]("The string is in uppercase.");
} else if ([Link]([Link]())) {
[Link]("The string is in lowercase.");
} else {
[Link]("The string is mixed case.");
}
// Reverse the case of the string
StringBuilder reversedCaseString = new StringBuilder();
for (char ch : [Link]()) {
if ([Link](ch)) {
[Link]([Link](ch));
} else if ([Link](ch)) {
[Link]([Link](ch));
} else {
[Link](ch); // Keep non-alphabetic characters as is
}
}
// Display the result
[Link]("Reversed case string: " + [Link]());
// Close the scanner
[Link]();
}
}
Output:
Enter a string: Ranjit
The string is mixed case.
Reversed case string: rANJIT
21 Write a java program to use important methods of String class
public class StringMethods21 {
public static void main(String[] args) {
// Create a string
String originalString = " Hello, World! ";
// 1. length(): Returns the length of the string
[Link]("Length: " + [Link]());
// 2. charAt(): Returns the character at a specific index
[Link]("Character at index 7: " + [Link](7));
// 3. substring(): Extracts a portion of the string
[Link]("Substring from index 3 to 8: " + [Link](3, 8));
// 4. toLowerCase() and toUpperCase(): Converts the string to lower and upper case
[Link]("Lowercase: " + [Link]());
[Link]("Uppercase: " + [Link]());
// 5. trim(): Removes leading and trailing whitespace
[Link]("Trimmed: '" + [Link]() + "'");
// 6. indexOf(): Finds the position of a character or substring
[Link]("Index of 'World': " + [Link]("World"));
// 7. replace(): Replaces all occurrences of a character or substring
[Link]("Replace 'World' with 'Java': " + [Link]("World",
"Java"));
// 8. contains(): Checks if a substring is present in the string
[Link]("Contains 'Hello': " + [Link]("Hello"));
// 9. startsWith() and endsWith(): Checks prefix and suffix
[Link]("Starts with ' Hello': " + [Link](" Hello"));
[Link]("Ends with '! ': " + [Link]("! "));
// 10. equals() and equalsIgnoreCase(): Compares two strings for equality
String anotherString = " hello, world! ";
[Link]("Equals (case-sensitive): " + [Link](anotherString));
[Link]("Equals (case-insensitive): " +
[Link](anotherString));
// 11. split(): Splits the string into an array of substrings
String[] parts = [Link]().split(", ");
[Link]("Split into parts:");
for (String part : parts) {
[Link]("- " + part);
}
// 12. isEmpty() and isBlank(): Checks if the string is empty or contains only whitespace
String emptyString = "";
[Link]("Is empty: " + [Link]());
[Link]("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 class cannot be subclassed
final class FinalClass {
// A final variable must be initialized when declared or in the constructor
final int finalVariable = 100;
// A final method cannot be overridden by subclasses (if the class were not final)
final void display() {
[Link]("This is a final method.");
}
}
public class FinalDemo22 {
public static void main(String[] args) {
// Creating an instance of the final class
FinalClass obj = new FinalClass();
// Accessing the final variable
[Link]("Value of final variable: " + [Link]);
// Calling the final method
[Link]();
}
}
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 [Link];
public class ExceptionDemo_23 {
// A method demonstrating `throws` to declare exceptions
static void checkNumber(int num) throws IllegalArgumentException {
if (num < 0) {
throw new IllegalArgumentException("Number cannot be negative!"); //
Demonstrating `throw`
}
[Link]("Number is valid: " + num);
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
try {
// First try block
[Link]("Enter a number: ");
int num = [Link]();
checkNumber(num); // Method may throw IllegalArgumentException
} catch (IllegalArgumentException e) {
// First catch block
[Link]("Caught an exception: " + [Link]());
} finally {
// `finally` block ensures execution
[Link]("First try-catch block is complete.");
}
try {
// Second try block
[Link]("Enter a divisor: ");
int divisor = [Link]();
int result = 10 / divisor; // May throw ArithmeticException
[Link]("Result: " + result);
} catch (ArithmeticException e) {
// Second catch block
[Link]("Caught an exception: Division by zero is not allowed.");
} catch (Exception e) {
// General catch block for any other exceptions
[Link]("Caught a general exception: " + [Link]());
} finally {
// `finally` block ensures execution
[Link]("Second try-catch block is complete.");
}
[Link]("Program execution continues...");
[Link]();
}
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.
// A class that extends Thread
class MyThread extends Thread {
// Override the run method to define the thread's task
@Override
public void run() {
for (int i = 1; i <= 3; i++) {
[Link]([Link]().getName() + " - Count: " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
}
}
}
public class ThreadDemo24 {
public static void main(String[] args) {
// Creating instances of MyThread
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
// Setting names for the threads (optional)
[Link]("Thread-1");
[Link]("Thread-2");
// Starting the threads
[Link]();
[Link]();
[Link]("Main thread execution continues...");
}
}
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++) {
[Link]([Link]().getName() + " - Count: " + i);
try {
[Link](500); // Pause for 500 milliseconds
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
}
}
}
public class RunnableDemo25 {
public static void main(String[] args) {
// Creating instances of MyRunnable
MyRunnable runnableTask = new MyRunnable();
// Creating Thread objects and associating them with runnable tasks
Thread thread1 = new Thread(runnableTask, "Thread-1");
Thread thread2 = new Thread(runnableTask, "Thread-2");
// Starting the threads
[Link]();
[Link]();
[Link]("Main thread execution continues...");
}
}
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
26 Develop a program to create Array List for “Employee” class objects
references. Employee class has emp_code, emp_name, basic_sal, gross_
sal. Calculate gross_sal for all employees of Array List. Display Array List
and also insert an employee object reference in a particular position
(input) in Array List.
import [Link];
import [Link];
// 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) {
[Link] = empCode;
[Link] = empName;
[Link] = basicSal;
[Link] = calculateGrossSal();
}
// Method to calculate gross salary
private double calculateGrossSal() {
double hra = 0.2 * basicSal; // 20% of basic salary
double da = 0.1 * basicSal; // 10% of basic salary
return basicSal + hra + da;
}
// Method to display employee details
public void display() {
[Link]("Emp Code: " + empCode + ", Name: " + empName
+ ", Basic Salary: " + basicSal + ", Gross Salary: " + grossSal);
}
}
public class EmployeeArrayListDemo26 {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Creating an ArrayList to store Employee objects
ArrayList<Employee> employeeList = new ArrayList<>();
// Adding Employee objects to the ArrayList
[Link](new Employee(101, "Alice", 50000));
[Link](new Employee(102, "Bob", 60000));
[Link](new Employee(103, "Charlie", 55000));
// Displaying all employees
[Link]("Employee List:");
for (Employee emp : employeeList) {
[Link]();
}
// Inserting a new employee at a specific position
[Link]("\nEnter position to insert new employee (0-based index): ");
int position = [Link]();
[Link]("Enter Employee Code: ");
int empCode = [Link]();
[Link](); // Consume newline
[Link]("Enter Employee Name: ");
String empName = [Link]();
[Link]("Enter Basic Salary: ");
double basicSal = [Link]();
Employee newEmployee = new Employee(empCode, empName, basicSal);
if (position >= 0 && position <= [Link]()) {
[Link](position, newEmployee);
} else {
[Link]("Invalid position! Adding to the end of the list.");
[Link](newEmployee);
}
// Displaying updated Employee List
[Link]("\nUpdated Employee List:");
for (Employee emp : employeeList) {
[Link]();
}
[Link]();
}
}
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
Enter position to insert new employee (0-based index):
27 Sort “Student” Linked List (mentioned in Q:1) based on std_name using “Comparator”
interface.
import [Link];
import [Link];
import [Link];
class Student {
private int rollNo;
private String stdName;
public Student(int rollNo, String stdName) {
[Link] = rollNo;
[Link] = stdName;
}
public int getRollNo() {
return rollNo;
}
public String getStdName() {
return stdName;
}
public void display() {
[Link]("Roll No: " + rollNo + ", Name: "
+ stdName);
}}
public class Comparator_27 {
public static void main(String[] args) {
LinkedList<Student> students = new LinkedList<>();
[Link](new Student(101, "Arun"));
[Link](new Student(103, "Charlie"));
[Link](new Student(102, "Bob"));
[Link]("Unsorted Student List:");
for (Student student : students) {
[Link]();
}
[Link](students, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return [Link]().compareTo([Link]());
}
});
[Link]("\nSorted Student List:");
for (Student student : students) {
[Link]();
}
}
}
Output:
Unsorted Student List:
Roll No: 101, Name: Ranjit
Roll No: 103, Name: Isha
Roll No: 102, Name: Aakash
Sorted Student List:
Roll No: 101, Name: Ranjit
Roll No: 102, Name: Aakash
Roll No: 103, Name: Isha
28 Write a program in Java to demonstrate use of synchronization of threads when
multiple threads are trying to update common variable for “Account” class.
// Account class with a synchronized method
class Account {
private int balance = 1000; // Initial balance
// Synchronized method to withdraw money
public synchronized void withdraw(int amount) {
if (balance >= amount) {
[Link]([Link]().getName() + " is about to withdraw: " +
amount);
try {
[Link](500); // Simulate some delay
} catch (InterruptedException e) {
[Link]("Thread interrupted: " + [Link]());
}
balance -= amount;
[Link]([Link]().getName() + " completed withdrawal.
Remaining balance: " + balance);
} else {
[Link]([Link]().getName() + " cannot withdraw.
Insufficient balance.");
}
}
// Getter for balance
public int getBalance() {
return balance;
}
}
// Runnable class for account operations
class AccountTask implements Runnable {
private final Account account;
private final int amount;
public AccountTask(Account account, int amount) {
[Link] = account;
[Link] = amount;
}
@Override
public void run() {
[Link](amount);
}
}
public class SynchronizedAccountDemo28 {
public static void main(String[] args) {
Account sharedAccount = new Account();
// Creating threads that share the same Account object
Thread t1 = new Thread(new AccountTask(sharedAccount, 700), "Thread-1");
Thread t2 = new Thread(new AccountTask(sharedAccount, 500), "Thread-2");
Thread t3 = new Thread(new AccountTask(sharedAccount, 300), "Thread-3");
// Starting threads
[Link]();
[Link]();
[Link]();
}
}
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.