Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java_Practical_Lab_Manuals

The document is a lab manual for Object Oriented Programming in Java for the Integrated Master of Computer Applications (MCA) first semester at R.B. Institute of Management Studies for the academic year 2024-2025. It includes a preface explaining the purpose of the manual and an index of programming tasks designed to enhance students' understanding and practical skills in Java. The manual covers a range of topics from basic Java installation to advanced concepts like threading and exception handling.

Uploaded by

Ranjit Vaghela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Java_Practical_Lab_Manuals

The document is a lab manual for Object Oriented Programming in Java for the Integrated Master of Computer Applications (MCA) first semester at R.B. Institute of Management Studies for the academic year 2024-2025. It includes a preface explaining the purpose of the manual and an index of programming tasks designed to enhance students' understanding and practical skills in Java. The manual covers a range of topics from basic Java installation to advanced concepts like threading and exception handling.

Uploaded by

Ranjit Vaghela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

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

3.Third 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

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;

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) {
System.out.print(a + " ");
}
int next = a + b;
a = b;
b = next;
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the starting limit: ");


int start = scanner.nextInt();
System.out.print("Enter the ending limit: ");
int end = scanner.nextInt();

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

3 Write a java program to check whether number is palindrome or not.


Input: 528 Output: It is not palindrome number

import java.util.Scanner;

public class ThreePolindromeOrNot {

public static void main(String[] args) {


// TODO Auto-generated method stub

int n, s=0,c,r;
System.out.println("Enter any number ");
Scanner sc = new Scanner(System.in);
n = sc.nextInt();

c=n;

while(n > 0){

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

4 Write a java program to print value of x^n.


import java.util.Scanner;

public class Four_PowerCalculator {


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

System.out.print("Enter the base (x): ");


int x = scanner.nextInt();
System.out.print("Enter the exponent (n): ");
int n = scanner.nextInt();

long result = 1; // Use long to handle large results


for (int i = 0; i < n; i++) {
result *= x;
}

// Print the result


System.out.println(x + "^" + n + " = " + result);
scanner.close();
}
}

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 java.util.Scanner;

public class Five_Armstrong_Number {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.i
System.out.print("Enter a number: ");
int number = scanner.nextInt();

int originalNumber = number;


int sum = 0;
int digits = String.valueOf(number).length(); // Number of digits in the number

// Check if the number is an Armstrong number


while (number > 0) {
int digit = number % 10;
sum += Math.pow(digit, digits); // Raise digit to the power of the number of digits
number /= 10;
}

// Output the result


if (sum == originalNumber) {
System.out.println(originalNumber + " is an Armstrong number.");
} else {
System.out.println(originalNumber + " is not an Armstrong number.");
}

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;

public class Six_min_of_three {


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

System.out.print("Enter first number: ");


int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();
int min = (num1 < num2) ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 :
num3);

System.out.println("The minimum of the three numbers is: " + min);


scanner.close();
}
}

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;

public class Seven_Max_in_Four {


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

System.out.print("Enter first number: ");


int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();
System.out.print("Enter fourth number: ");
int num4 = scanner.nextInt();

int max = (num1 > num2)


? (num1 > num3 ? (num1 > num4 ? num1 : num4) : (num3 > num4 ? num3 : num4))
: (num2 > num3 ? (num2 > num4 ? num2 : num4) : (num3 > num4 ? num3 : num4));

System.out.println("The maximum of the four numbers is: " + max);

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

1.: First Student Name is = Arun

2.: Second Student Name is = Hiren

3.Third Student Name is = Hitesh

public class Eight_StudentNames {


public static void main(String[] args) {
System.out.println("Number of arguments = " + args.length);

// Print each student's name


for (int i = 0; i < args.length; i++) {
System.out.println((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 (args.length != 1) {
System.out.println("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 : input.toCharArray()) {


if (Character.isLetter(ch)) {
letterCount[Character.toLowerCase(ch) - 'a']++;
} else if (Character.isDigit(ch)) {
digitCount[ch - '0']++;
}
}

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
}

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) {


this.enrollmentNo = enrollmentNo;
this.name = name;
this.gender = gender;
this.marks = marks;
count++; // Increment the count of objects
}

public static int getCount() {


return count;
}
public void display() {
System.out.println("Enrollment No: " + enrollmentNo);
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("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);

System.out.println("Student 1 Details:");
student1.display();
System.out.println("\nStudent 2 Details:");
student2.display();
System.out.println("\nStudent 3 Details:");
student3.display();

System.out.println("\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) {
this.instanceVariable = instanceVariable;
staticVariable++;
}
public void display() {
System.out.println("Instance Variable: " + this.instanceVariable);

System.out.println("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);
obj1.display();
obj2.display();
System.out.println("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;
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;
}

// Method to calculate the area of the rectangle


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

// Method to display rectangle details


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

// Main method to demonstrate functionality and sequence of execution


public static void main(String[] args) {
// System.out.println("Main Method: Program starts.");

// Creating objects
Rectangle_12 rect1 = new Rectangle_12();
rect1.display();

System.out.println();

Rectangle_12 rect2 = new Rectangle_12(5, 3);


rect2.display();

System.out.println();

Rectangle_12 rect3 = new Rectangle_12(rect2);


rect3.display();

System.out.println();

// Displaying total count of Rectangle objects


System.out.println("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 {
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.

public class Wrapper_14 {

public static void main(String[] args) {


// 1. Integer (int)
int primitiveInt = 10;
Integer wrapperInt = Integer.valueOf(primitiveInt); // Boxing
int unboxedInt = wrapperInt.intValue(); // Unboxing
System.out.println("Integer Wrapper: " + wrapperInt);
System.out.println("Unboxed Integer: " + unboxedInt);

// 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);
}
}

class Car extends Vehicle {


String modelType;
String companyName;
Car(String vehicleType, String modelType, String companyName) {
super(vehicleType);
this.modelType = modelType;
this.companyName = companyName;
}

@Override
void display() {
super.display();
System.out.println("Model Type: " + modelType);
System.out.println("Company Name: " + companyName);
}
}

public class Vehicle_15 {


public static void main(String[] args) {

Car myCar = new Car("Four Wheeler", "Sedan", "Toyota");

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;

// Declaring another final field with initialization in the constructor


final int instanceValue;
// Constructor to initialize the final field
public FinalFieldExample(int value) {
this.instanceValue = value;
}

// Method to display the values of the final fields


public void display() {
System.out.println("CONSTANT_VALUE: " + CONSTANT_VALUE);
System.out.println("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


System.out.println("Accessing values using obj1:");
obj1.display();

System.out.println("\nAccessing values using obj2:");


obj2.display();

// 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) {


this.base = base;
this.height = height;
}

@Override
void area() {
double result = 0.5 * base * height;
System.out.println("Area of Triangle: " + result);
}
}

class Rectangle17 extends GeometricShape {


double length, width;

Rectangle17(double length, double width) {


this.length = length;
this.width = width;
}

@Override
void area() {
double result = length * width;
System.out.println("Area of Rectangle: " + result);
}
}

class Circle extends GeometricShape {


double radius;

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

@Override
void area() {
double result = Math.PI * radius * radius;
System.out.println("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);

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;

public class main {

public static void Main(String[] args) {


int[] marks = {85, 90, 78, 92};
student student = new student("Monjulika", 200, marks);

result.generateMarksheet(student);
}
}
package student;

public class student {


private String name;
private int rollNumber;
private int[] marks;

public student(String name, int rollNumber, int[] marks) {


this.name = name;
this.rollNumber = rollNumber;
this.marks = marks;
}

public String getName() {


return name;
}

public int getRollNumber() {


return rollNumber;
}

public int[] getMarks() {


return marks;
}
}
package exam;

import student.student;

public class result {


public static void generateMarksheet(student student) {
System.out.println("Marksheet for: " + student.getName());
System.out.println("Roll Number: " + student.getRollNumber());
System.out.println("Marks:");

int[] marks = student.getMarks();


int total = 0;
for (int i = 0; i < marks.length; i++) {
System.out.println("Subject " + (i + 1) + ": " + marks[i]);
total += marks[i];
}

double average = (double) total / marks.length;


System.out.println("Total Marks: " + total);
System.out.println("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);
intNumber.display();
System.out.println("Double value: " + intNumber.getDoubleValue());
// Using Number_1 with Float
Number_1<Float> floatNumber = new Number_1<>(10.5f);
floatNumber.display();
System.out.println("Double value: " + floatNumber.getDoubleValue());
}
}

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;

public class Upper_Lower_20 {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

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.");
}

// Reverse the case of the string


StringBuilder reversedCaseString = new StringBuilder();
for (char ch : input.toCharArray()) {
if (Character.isUpperCase(ch)) {
reversedCaseString.append(Character.toLowerCase(ch));
} else if (Character.isLowerCase(ch)) {
reversedCaseString.append(Character.toUpperCase(ch));
} else {
reversedCaseString.append(ch); // Keep non-alphabetic characters as is
}
}

// Display the result


System.out.println("Reversed case string: " + reversedCaseString.toString());

// Close the scanner


scanner.close();
}
}

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


System.out.println("Length: " + originalString.length());

// 2. charAt(): Returns the character at a specific index


System.out.println("Character at index 7: " + originalString.charAt(7));

// 3. substring(): Extracts a portion of the string


System.out.println("Substring from index 3 to 8: " + originalString.substring(3, 8));

// 4. toLowerCase() and toUpperCase(): Converts the string to lower and upper case
System.out.println("Lowercase: " + originalString.toLowerCase());
System.out.println("Uppercase: " + originalString.toUpperCase());

// 5. trim(): Removes leading and trailing whitespace


System.out.println("Trimmed: '" + originalString.trim() + "'");

// 6. indexOf(): Finds the position of a character or substring


System.out.println("Index of 'World': " + originalString.indexOf("World"));
// 7. replace(): Replaces all occurrences of a character or substring
System.out.println("Replace 'World' with 'Java': " + originalString.replace("World",
"Java"));

// 8. contains(): Checks if a substring is present in the string


System.out.println("Contains 'Hello': " + originalString.contains("Hello"));

// 9. startsWith() and endsWith(): Checks prefix and suffix


System.out.println("Starts with ' Hello': " + originalString.startsWith(" Hello"));
System.out.println("Ends with '! ': " + originalString.endsWith("! "));

// 10. equals() and equalsIgnoreCase(): Compares two strings for equality


String anotherString = " hello, world! ";
System.out.println("Equals (case-sensitive): " + originalString.equals(anotherString));
System.out.println("Equals (case-insensitive): " +
originalString.equalsIgnoreCase(anotherString));

// 11. split(): Splits the string into an array of substrings


String[] parts = originalString.trim().split(", ");
System.out.println("Split into parts:");
for (String part : parts) {
System.out.println("- " + part);
}

// 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 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() {
System.out.println("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


System.out.println("Value of final variable: " + obj.finalVariable);

// Calling the final method


obj.display();
}
}

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;

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`
}
System.out.println("Number is valid: " + num);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

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.");
}

System.out.println("Program execution continues...");


scanner.close();
}

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++) {
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());
}
}
}
}

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)
thread1.setName("Thread-1");
thread2.setName("Thread-2");

// Starting the threads


thread1.start();
thread2.start();

System.out.println("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++) {
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());
}
}
}
}

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


thread1.start();
thread2.start();

System.out.println("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 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();
}

// 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() {
System.out.println("Emp Code: " + empCode + ", Name: " + empName
+ ", Basic Salary: " + basicSal + ", Gross Salary: " + grossSal);
}
}

public class EmployeeArrayListDemo26 {


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

// Creating an ArrayList to store Employee objects


ArrayList<Employee> employeeList = new ArrayList<>();

// Adding Employee objects to the ArrayList


employeeList.add(new Employee(101, "Alice", 50000));
employeeList.add(new Employee(102, "Bob", 60000));
employeeList.add(new Employee(103, "Charlie", 55000));

// Displaying all employees


System.out.println("Employee List:");
for (Employee emp : employeeList) {
emp.display();
}

// Inserting a new employee at a specific position


System.out.print("\nEnter position to insert new employee (0-based index): ");
int position = scanner.nextInt();
System.out.print("Enter Employee Code: ");
int empCode = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter Employee Name: ");
String empName = scanner.nextLine();
System.out.print("Enter Basic Salary: ");
double basicSal = scanner.nextDouble();

Employee newEmployee = new Employee(empCode, empName, basicSal);


if (position >= 0 && position <= employeeList.size()) {
employeeList.add(position, newEmployee);
} else {
System.out.println("Invalid position! Adding to the end of the list.");
employeeList.add(newEmployee);
}

// Displaying updated Employee List


System.out.println("\nUpdated Employee List:");
for (Employee emp : employeeList) {
emp.display();
}
scanner.close();
}
}

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 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

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) {
System.out.println(Thread.currentThread().getName() + " is about to withdraw: " +
amount);
try {
Thread.sleep(500); // Simulate some delay
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " + e.getMessage());
}
balance -= amount;
System.out.println(Thread.currentThread().getName() + " completed withdrawal.
Remaining balance: " + balance);
} else {
System.out.println(Thread.currentThread().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) {


this.account = account;
this.amount = amount;
}

@Override
public void run() {
account.withdraw(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
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.

You might also like