0% found this document useful (0 votes)
34 views

Java Labbook Amol - Shinde

Here is the code to solve the above problem: class Rectangle { int length; int breadth; Rectangle(int l, int b) { length = l; breadth = b; } int area() { return length * breadth; } int perimeter() { return 2 * (length + breadth); } } class Square extends Rectangle { Square(int s) { super(s, s); } public static void main(String args[]) { Rectangle r = new Rectangle(10, 5); System.out.println("Area of rectangle is: " + r.area()); System.out.println("Perimeter of rectangle is

Uploaded by

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

Java Labbook Amol - Shinde

Here is the code to solve the above problem: class Rectangle { int length; int breadth; Rectangle(int l, int b) { length = l; breadth = b; } int area() { return length * breadth; } int perimeter() { return 2 * (length + breadth); } } class Square extends Rectangle { Square(int s) { super(s, s); } public static void main(String args[]) { Rectangle r = new Rectangle(10, 5); System.out.println("Area of rectangle is: " + r.area()); System.out.println("Perimeter of rectangle is

Uploaded by

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

Laboratory Workbook

Subject: Java Programming Lab

Course: MCA I - [Semester: I]

Prepared by,
Name : Kunal Awate>
Roll No : 23123

Program Index
Page Completion Remark S
Program
No. Date
allation of jdk environment & following utilities. What is javac,
p and javadoc.
e a program to count the number of objects of a class.
e a program to assign object reference variable to another and
e the reference to object and garbage collection.
d only one parameter from command line argument and
ay the welcome message also check the length.
te a class named 'Rectangle' with two data members 'length'
breadth' and two methods to print the area and perimeter of
ectangle respectively. Its constructor having parameters for
h and breadth is used to initialize length and breadth of the
angle. Let class 'Square' inherit the 'Rectangle' class with its
tructor having a parameter for its side (suppose s) calling the
tructor of its parent class as 'super(s,s)'. Print the area and
meter of a rectangle and a square.
te a class named 'Member' having the following members:
members : Name, Age, Phone number, Address, Salary. It
has a method named 'printSalary' which prints the salary of
members. Two classes 'Employee' and 'Manager' inherits the
mber' class. The 'Employee' and 'Manager' classes have data
bers 'specialization' and 'department' respectively. Now,
gn name, age, phone number, address and salary to an
oyee and a manager by making an object of both of these
ses and print the same.
gn a java program using interface, which performs simple
metic such as addition, subtraction, multiplication and
ion.
e a program having interface A containing two methods
h1() and meth2(). interface B extends A which contain method
h3() and create one class which implements B. call all the
hod and print the output.
e a program to implement the polymorphism by creating one
rclass Beaches and three subclasses Mumbai, Kanyakumari,
gluru. Subclasses extend the superclass and override its
ion() and famousfor() methods. Call the location and
usfor methods of parent class i.e. beaches.
e a program to implement a user defined exception “NotPrime
ption”. Read number from command line and cjheck whether
number is prime or not. If it is prime then display message
mber is prime” and if it is not prime throw the exception
PrimeException”.
e a java code to create thread object and start it.
e a program that creates and run the following threads-
. To print letter ‘A’ 75 times.
. To print letter ‘B’ 100 times.
. To print integer 1 to 100.
e a program to Create multiple Threads
e a program to change name and priority of Thread
gn a program to create an *ArrayList*. Create a *Student*
s, assign rollno, name and marks to him using constructor.
e 5 objects of Student class in ArrayList. And display the
rds of the students who has more than 60 marks.
gn a program to create an *LinkedList*. Create a Employee
s, assign emp_id, emp_name and emp_salary to him using
tructor. Store 5 objects of Employee class in LinkedList.
ate the salary of the all the Employees with 10%.
Question 1: Installation of jdk environment & following utilities. What is
javac, javap and javadoc.

*********************************************************************************

Ans: Step 1: Download and Install JDK

1. Go to the Oracle JDK download page


(https://www.oracle.com/java/technologies/javase-downloads.html) or another source
like OpenJDK (https://adoptopenjdk.net/ or https://openjdk.java.net/), depending on
your preference. Note that Oracle JDK may require you to create an Oracle account or
accept their terms of use.
2. Download the JDK version that suits your needs (e.g., JDK 8, 11, 16, etc.). Ensure
you download the appropriate version for your operating system (Windows, macOS,
or Linux).
3. Run the installer executable and follow the installation wizard instructions. This will
install the Java Development Kit (JDK) on your system. Make a note of the
installation directory (e.g., C:\Program Files\Java\jdk1.8.0_311).

Step 2: Set up Environment Variables

1. After installing the JDK, you need to set the environment variables to make it
accessible from the command line.
o Right-click on "This PC" (or "My Computer") and select "Properties."
o Click on "Advanced system settings" on the left.
o In the "System Properties" window, click the "Environment Variables" button.
o Under "System Variables," scroll down to find "Path," select it, and click "Edit."
o Click "New" and add the path to the "bin" directory inside your JDK installation
directory (e.g., C:\Program Files\Java\jdk1.8.0_311\bin). Separate
multiple paths with semicolons.
o Click "OK" to save the changes.

2. Additionally, you might need to set a JAVA_HOME system variable:


o Click on "New" under "System Variables."
o Set "Variable Name" to JAVA_HOME.
o Set "Variable Value" to the root directory of your JDK installation (e.g., C:\Program
Files\Java\jdk1.8.0_311).

Step 3: Verify JDK Installation

1. Open a command prompt (cmd).


2. To verify the installation, type the following command:

2. java -version
3. This should display the version of the installed JDK.

Step 4: Understanding javac, javap, and javadoc

 javac: This is the Java compiler. It is used to compile Java source code files (.java)
into bytecode files (.class). For example, to compile a Java file called
MyProgram.java, you would use javac MyProgram.java.
 javap: This is a disassembler for Java class files. It allows you to inspect the structure
and bytecode of compiled Java classes. For example, to view the details of a class
called MyClass, you would use javap -c MyClass.
 javadoc: This tool is used to generate HTML documentation from Java source code.
It reads specially formatted comments in the code (JavaDoc comments) and creates
API documentation. To generate documentation for a Java class, use the javadoc
command followed by the name of the class.
Question 2: Write a program to count the number of objects of a class.

***************************************************************************

Ans: public class ObjectCounter {

// Static variable to keep track of the object count

private static int objectCount = 0;

public ObjectCounter() {

objectCount++;

public static int getObjectCount() {

return objectCount;

public static void main(String[] args) {

// Create several objects of the ObjectCounter class

ObjectCounter obj1 = new ObjectCounter();

ObjectCounter obj2 = new ObjectCounter();

ObjectCounter obj3 = new ObjectCounter();

// Get the count of objects

int count = ObjectCounter.getObjectCount();

System.out.println("Total number of ObjectCounter objects: " + count);

}
Output:- Total number of ObjectCounter objects: 3

Name :Kunal Awate

Roll No :23123

Question 3: Write a program to assign object reference variable to another


and delete the reference to object and garbage collection.

*************************************************************************************

Ans: public class ObjectReferenceDemo {

public static void main(String[] args) {

// Create an object

MyClass obj1 = new MyClass(1);

// Assign the reference to another variable

MyClass obj2 = obj1;

// Set obj1 to null, removing the reference to the object

obj1 = null;

// Force garbage collection (Note: This is usually not necessary)

System.gc();

// Check if obj1 and obj2 are still valid

if (obj1 == null) {

System.out.println("obj1 is null.");

if (obj2 != null) {
System.out.println("obj2 is still valid.");

} else {

System.out.println("obj2 is null.");

class MyClass {

private int value;

public MyClass(int value) {

this.value = value;

public int getValue() {

return value;

@Override

protected void finalize() {

System.out.println("Object is being garbage collected. Value: " + value);

Output :- obj1 is null obj2 is still valid.

Name :Kunal Awate


Roll No :23123

Question 4: Read only one parameter from command line argument and
display the welcome message also check the length.

Ans: public class CommandLineArgsDemo {

public static void main(String[] args) {

if (args.length == 1) {

String input = args[0];

int length = input.length();

System.out.println("Welcome, " + input + "!");

System.out.println("Your name has " + length + " characters.");

} else {

System.out.println("Usage: Please provide your name as a


command-line argument.");

Output:- Welcome, Amar!

Your name has 4 characters.

Name :Kunal Awate

Roll No :23123
Question 5: Create a class named 'Rectangle' with two data members
'length' and 'breadth' and two methods to print the area and perimeter
of the rectangle respectively. Its constructor having parameters for
length and breadth is used to initialize length and breadth of the
rectangle. Let class 'Square' inherit the 'Rectangle' class with its
constructor having a parameter for its side (suppose s) calling the
constructor of its parent class as 'super(s,s)'. Print the area and
perimeter of a rectangle and a square.

*************************************************************************************

Ans: class Rectangle {

private double length;

private double breadth;

public Rectangle(double length, double breadth) {

this.length = length;

this.breadth = breadth;

public void calculateArea() {

double area = length * breadth;

System.out.println("Area of the Rectangle: " + area);

public void calculatePerimeter() {

double perimeter = 2 * (length + breadth);

System.out.println("Perimeter of the Rectangle: " + perimeter);


}

class Square extends Rectangle {

public Square(double side) {

super(side, side); // Call the parent class constructor with both sides
being the same

public class Main {

public static void main(String[] args) {

Rectangle rectangle = new Rectangle(4.0, 6.0);

rectangle.calculateArea();

rectangle.calculatePerimeter();

Square square = new Square(5.0);

square.calculateArea();

square.calculatePerimeter();

Output :- Area of the Rectangle: 24.0

Perimeter of the Rectangle: 20.0

Area of the Rectangle: 25.0

Perimeter of the Rectangle: 20.0

Name :Kunal Awate


Roll No :23123

Question 6: Create a class named 'Member' having the following members:


Data members : Name, Age, Phone number, Address, Salary. It also has
a method named 'printSalary' which prints the salary of the members.
Two classes 'Employee' and 'Manager' inherits the 'Member' class. The
'Employee' and 'Manager' classes have data members 'specialization'
and 'department' respectively. Now, assign name, age, phone number,
address and salary to an employee and a manager by making an object
of both of these classes and print the same.

*********************************************************************************

Ans: class Member {

String name;

int age;

String phoneNumber;

String address;

double salary;

public Member(String name, int age, String phoneNumber, String address, double salary) {

this.name = name;

this.age = age;

this.phoneNumber = phoneNumber;

this.address = address;

this.salary = salary;

public void printSalary() {

System.out.println("Salary: " + salary);

}
}

class Employee extends Member {

String specialization;

public Employee(String name, int age, String phoneNumber, String address, double salary,
String specialization) {

super(name, age, phoneNumber, address, salary);

this.specialization = specialization;

class Manager extends Member {

String department;

public Manager(String name, int age, String phoneNumber, String address, double salary,
String department) {

super(name, age, phoneNumber, address, salary);

this.department = department;

public class Main {

public static void main(String[] args) {

Employee employee = new Employee("John Doe", 30, "555-123-4567", "123 Main St",
50000.0, "Programming");

Manager manager = new Manager("Jane Smith", 35, "555-987-6543", "456 Oak St",
75000.0, "Operations");
// Print employee details

System.out.println("Employee Details:");

System.out.println("Name: " + employee.name);

System.out.println("Age: " + employee.age);

System.out.println("Phone Number: " + employee.phoneNumber);

System.out.println("Address: " + employee.address);

employee.printSalary();

System.out.println("Specialization: " + employee.specialization);

// Print manager details

System.out.println("\nManager Details:");

System.out.println("Name: " + manager.name);

System.out.println("Age: " + manager.age);

System.out.println("Phone Number: " + manager.phoneNumber);

System.out.println("Address: " + manager.address);

manager.printSalary();

System.out.println("Department: " + manager.department);

Output:- Employee Details:


Name: John Doe
Age: 30
Phone Number: 555-123-4567
Address: 123 Main St

Salary: 50000.0
Specialization: Programming

Manager Details:
Name: Jane Smith
Age: 35
Name :Kunal Awate

Roll No :23123

Question 7: Design a java program using interface, which performs


simple arithmetic such as addition, subtraction, multiplication and
division.
*********************************************************************************

Ans: // Define an interface for arithmetic operations


interface Arithmetic {
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
}

// Create a class that implements the Arithmetic interface


class Calculator implements Arithmetic {
@Override
public double add(double a, double b) {
return a + b;
}

@Override
public double subtract(double a, double b) {
return a - b;
}

@Override
public double multiply(double a, double b) {
return a * b;
}

@Override
public double divide(double a, double b) {
if (b == 0) {
System.out.println("Division by zero is not allowed.");
return Double.NaN; // Not-a-Number
}
return a / b;
}
}

public class Main {


public static void main(String[] args) {
Calculator calculator = new Calculator();

double num1 = 10.0;


double num2 = 5.0;

System.out.println("Addition: " + num1 + " + " + num2 + " = " +


calculator.add(num1, num2));
System.out.println("Subtraction: " + num1 + " - " + num2 + " = " +
calculator.subtract(num1, num2));
System.out.println("Multiplication: " + num1 + " * " + num2 + " = " +
calculator.multiply(num1, num2));
System.out.println("Division: " + num1 + " / " + num2 + " = " +
calculator.divide(num1, num2));
}
}

Output :-
Addition: 10.0 + 5.0 = 15.0
Subtraction: 10.0 - 5.0 = 5.0
Multiplication: 10.0 * 5.0 = 50.0
Division: 10.0 / 5.0 = 2.0

Name :Kunal Awate

Roll No :23123
Question 8: Write a program having interface A containing two methods
meth1() and meth2(). interface B extends A which contain method
meth3() and create one class which implements B. call all the method
and print the output
*********************************************************************************

Ans: // Define interface A


interface A {
void meth1();

void meth2();
}

// Define interface B that extends A


interface B extends A {
void meth3();
}

// Create a class that implements interface B


class MyClass implements B {
@Override
public void meth1() {
System.out.println("Method meth1() from interface A");
}

@Override
public void meth2() {
System.out.println("Method meth2() from interface A");
}

@Override
public void meth3() {
System.out.println("Method meth3() from interface B");
}
}

public class Main {


public static void main(String[] args) {
MyClass myClass = new MyClass();

// Call methods from interface A


myClass.meth1();
myClass.meth2();

// Call method from interface B


myClass.meth3();
}
}

Output:-
Method meth1() from interface A
Method meth2() from interface A
Method meth3() from interface B

Name :Kunal Awate

Roll No :23123
Question 9: Write a program to implement the polymorphism by
creating one superclass Beaches and three subclasses Mumbai,
Kanyakumari, Mangluru. Subclasses extend the superclass and override
its location() and famousfor() methods. Call the location and famousfor
methods of parent class i.e. beaches.
*********************************************************************************

Ans: class Beaches {


public void location() {
System.out.println("This is a beach.");
}

public void famousfor() {


System.out.println("It is known for its scenic beauty.");
}
}

class Mumbai extends Beaches {


@Override
public void location() {
System.out.println("Mumbai Beach is located in Mumbai,
Maharashtra.");
}

@Override
public void famousfor() {
System.out.println("Mumbai Beach is famous for the Gateway of
India.");
}
}

class Kanyakumari extends Beaches {


@Override
public void location() {
System.out.println("Kanyakumari Beach is located in Kanyakumari,
Tamil Nadu.");
}

@Override
public void famousfor() {
System.out.println("Kanyakumari Beach is famous for its sunrise and
sunset views.");
}
}

class Mangaluru extends Beaches {


@Override
public void location() {
System.out.println("Mangaluru Beach is located in Mangaluru,
Karnataka.");
}

@Override
public void famousfor() {
System.out.println("Mangaluru Beach is famous for its pristine
shores.");
}
}

public class Main {


public static void main(String[] args) {
Beaches mumbaiBeach = new Mumbai();
Beaches kanyakumariBeach = new Kanyakumari();
Beaches mangaluruBeach = new Mangaluru();

// Call methods using polymorphism


mumbaiBeach.location();
mumbaiBeach.famousfor();

kanyakumariBeach.location();
kanyakumariBeach.famousfor();

mangaluruBeach.location();
mangaluruBeach.famousfor();
}
}

Output :- Mumbai Beach is located in Mumbai, Maharashtra.


Mumbai Beach is famous for the Gateway of India.
Kanyakumari Beach is located in Kanyakumari, Tamil Nadu.
Kanyakumari Beach is famous for its sunrise an...

Name :Kunal Awate

Roll No :23123
Question 10: Write a program to implement a user defined exception
“NotPrime Exception”. Read number from command line and cjheck
whether the number is prime or not. If it is prime then display message
“Number is prime” and if it is not prime throw the exception
“NotPrimeException”.

*********************************************************************************

Ans:- import java.util.Scanner;

class NotPrimeException extends Exception {

NotPrimeException(String s) {

super(s);

public class CommandLineArgsDemo {

public static void main(String[] args) {

try {

if (args.length == 0) {

throw new IllegalArgumentException("No command line


arguments found.");

int num = Integer.parseInt(args[0]);

if (isPrime(num)) {

System.out.println("Number is prime.");

} else {

throw new NotPrimeException("Number is not prime.");

} catch (NumberFormatException e) {

System.out.println("Invalid format: " + e.getMessage());


} catch (IllegalArgumentException e) {

System.out.println("Invalid argument: " + e.getMessage());

} catch (NotPrimeException e) {

System.out.println("Caught an exception: " + e.getMessage());

public static boolean isPrime(int num) {

if (num <= 1) {

return false;

for (int i = 2; i <= Math.sqrt(num); i++) {

if (num % i == 0) {

return false;

return true;

Output:-

java CommandLineArgsDemo 7

Number is prime.

java CommandLineArgsDemo 10

Caught an exception: Number is not prime.

Name :Kunal Awate

Roll No :23123
Question 11: Write a java code to create thread object and start it.

*************************************************************************************

Ans:- public class MyThread extends Thread {

public void run() {

System.out.println("This is a thread running.");

public static void main(String[] args) {

MyThread myThread = new MyThread();

myThread.start();

Output :- This is a thread running.

Name :Kunal Awate

Roll No :23123
Question 12: Write a program that creates and run the following threads-

1. To print letter ‘A’ 75 times.


2. To print letter ‘B’ 100 times.
3. print integer 1 to 100.
******************************************************************************
Ans: class PrintA implements Runnable {
public void run() {
for (int i = 0; i < 75; i++) {
System.out.print('A');
}
}
}

class PrintB implements Runnable {


public void run() {
for (int i = 0; i < 100; i++) {
System.out.print('B');
}
}
}

class PrintNumbers implements Runnable {


public void run() {
for (int i = 1; i <= 100; i++) {
System.out.print(i + " ");
}
}
}

public class ThreadDemo {


public static void main(String[] args) {
Thread threadA = new Thread(new PrintA());
Thread threadB = new Thread(new PrintB());
Thread threadNumbers = new Thread(new PrintNumbers());

threadA.start();
threadB.start();
threadNumbers.start();
}
}

Output :-

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB1 2 3 4 5 6 7 8 9 10 11
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
96 97 98 99 100.

Name :Kunal Awate

Roll No :23123
Question 13: Write a program to Create multiple Threads

*************************************************************************************
Ans: public class MultiThreadDemo {
public static void main(String[] args) {
int numThreads = 5;

// Create an array to hold thread objects


Thread[] threads = new Thread[numThreads];

// Create and start multiple threads


for (int i = 0; i < numThreads; i++) {
threads[i] = new Thread(new MyRunnable("Thread " + (i + 1)));
threads[i].start();
}

// Wait for all threads to complete


for (int i = 0; i < numThreads; i++) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

System.out.println("All threads have finished.");


}
}

class MyRunnable implements Runnable {


private String threadName;

public MyRunnable(String name) {


this.threadName = name;
}

@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(threadName + " - Count: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Question 14: Write a program to change name and priority of Thread

*************************************************************************************
Ans:- public class ThreadNamePriorityDemo {
public static void main(String[] args) {
// Create a thread and specify its behavior
Thread customThread = new Thread(() -> {
System.out.println("Thread name: " + Thread.currentThread().getName());
System.out.println("Thread priority: " + Thread.currentThread().getPriority());
});

// Set the name and priority of the thread


customThread.setName("CustomThread");
customThread.setPriority(Thread.MAX_PRIORITY);

// Start the thread


customThread.start();
}
}

Output :- Thread name: CustomThread


Thread priority: 10

Name :Kunal Awate

Roll No :23123
Question 15: Design a program to create an *ArrayList*. Create a
*Student* class, assign rollno, name and marks to him using
constructor. Store 5 objects of Student class in ArrayList. And
display the records of the students who has more than 60 marks.

******************************************************************************

Ans:- import java.util.ArrayList;

class Student {
private int rollNo;
private String name;
private int marks;

public Student(int rollNo, String name, int marks) {


this.rollNo = rollNo;
this.name = name;
this.marks = marks;
}

public int getMarks() {


return marks;
}

@Override
public String toString() {
return "Roll No: " + rollNo + ", Name: " + name + ", Marks: " +
marks;
}
}

public class StudentRecord {


public static void main(String[] args) {
// Create an ArrayList to store Student objects
ArrayList<Student> studentList = new ArrayList<>();

// Add 5 Student objects to the ArrayList


studentList.add(new Student(1, "John", 75));
studentList.add(new Student(2, "Alice", 50));
studentList.add(new Student(3, "Bob", 80));
studentList.add(new Student(4, "Eva", 65));
studentList.add(new Student(5, "Mike", 45));

// Display the records of students with more than 60 marks


System.out.println("Students with more than 60 marks:");
for (Student student : studentList) {
if (student.getMarks() > 60) {
System.out.println(student);
}
}
}
}

Output :-
Students with more than 60 marks:
Roll No: 1, Name: John, Marks: 75
Roll No: 3, Name: Bob, Marks: 80
Roll No: 4, Name: Eva, Marks: 65

Name :Kunal Awate

Roll No :23123

You might also like