0% found this document useful (0 votes)
7 views53 pages

Vaishnavi Java Programming Journal

The document outlines a series of practical lab exercises for a Java programming course, covering topics such as JDK installation, Java utilities (javac, javap, javadoc), and various programming concepts including arrays, inheritance, interfaces, and abstract classes. Each exercise includes source code examples and expected outputs, demonstrating key Java functionalities like method overloading, constructor overloading, and the use of built-in Java APIs. The document serves as a comprehensive guide for students to practice and understand Java programming principles.

Uploaded by

Vaishnavi Pujari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views53 pages

Vaishnavi Java Programming Journal

The document outlines a series of practical lab exercises for a Java programming course, covering topics such as JDK installation, Java utilities (javac, javap, javadoc), and various programming concepts including arrays, inheritance, interfaces, and abstract classes. Each exercise includes source code examples and expected outputs, demonstrating key Java functionalities like method overloading, constructor overloading, and the use of built-in Java APIs. The document serves as a comprehensive guide for students to practice and understand Java programming principles.

Uploaded by

Vaishnavi Pujari
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:1


Q. Installation of JDK environment & following utilities. What is javac ,javap and
javadoc.

Description:
1. Installation of JDK Environment
The Java Development Kit (JDK) is required to write, compile, and run Java programs.
To install the JDK, follow these steps:
Step 1: Download JDK
• Visit Oracle’s official website or OpenJDK website
• Download the latest version of JDK for your operating system (Windows, Linux,
macOS)
Step 2: Install JDK
• Run the installer
• Follow the installation wizard
• Default installation path (Windows):
• C:\Program Files\Java\jdk<version>
Step 3: Set Environment Variables
To make Java accessible from any directory:
Add JAVA_HOME
JAVA_HOME = C:\Program Files\Java\jdk<version>
Add Java to PATH
Add the following to the PATH variable:
%JAVA_HOME%\bin
Step 4: Verify Installation
Open Command Prompt:
java -version
javac -version
If both run successfully, the JDK is installed correctly.

2. Java Utilities (javac, javap, javadoc)


A) javac
• javac is the Java compiler.
• It converts the .java (source file) into .class (bytecode).
• Syntax:
• javac [Link]
B) javap
• javap is the Java Class File Disassembler.
• It shows information about the compiled class, such as:
o methods
o fields
o bytecode
• Syntax:

MCA II SEM III CBCS Page |1


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
• javap FileName
C) javadoc
• javadoc is the documentation generator.
• It creates HTML documentation from Java source files that include comment blocks
(/** ... */).
• Commonly used for generating API documentation.
• Syntax:
• javadoc [Link]

Source Code:

public class simpleprogram


{
private int value;
public String pbS1;
float num1;
protected Boolean b1;
public simpleprogram(int value,String pbS1,float num1, Boolean b1) {
[Link] = value;
this.pbS1 = pbS1;
this.num1 = num1;
this.b1 = b1;
}
public int getValue() {
return value;
}
public void setValue(int value) {
[Link] = value;
}
}
Output:

MCA II SEM III CBCS Page |2


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

MCA II SEM III CBCS Page |3


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

MCA II SEM III CBCS Page |4


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:2


Q. Write a Program to design a Java application using array. (Implement Sorting of
given list of names in ascending order).
Source Code:
package mca;
import [Link];
import [Link];
public class SortNames {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter number of names: ");
int n = [Link]();
[Link]();
String[] names = new String[n];
[Link]("\nEnter the names:");
for (int i = 0; i < n; i++) {
[Link]("Name " + (i + 1) + ": ");
names[i] = [Link]();
}
[Link](names);
[Link]("\nSorted Names in Ascending Order:");
for (String name : names) {
[Link](name);
}
[Link]();
}
}
Output:

MCA II SEM III CBCS Page |5


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:3


Q. Write a Java program for Implementation of functionality provided by any five built
in Java API / packages. B. Implementation of custom defined Package – Illustrate the
visibility of classes and their members in packages using different access modifiers.

Source Code:
package mca;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class BuiltInDemo {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner([Link]);
// [Link]
[Link]("Enter three numbers: 45 12 78");
List<Integer> numbers = [Link](45, 12, 78);
[Link](numbers);
[Link]("Sorted numbers: " + numbers);
// [Link]
File file = new File("[Link]");
[Link]();
[Link]("File created: " + [Link]());
// [Link]
LocalDate today = [Link](2025, 11, 30);
LocalTime now = [Link](17, 40, 12);
[Link]("Today's date: " + today);
[Link]("Current time: " + now);
// [Link]
BigInteger big1 = new BigInteger("12345678901234567890");
BigInteger big2 = new BigInteger("98765432109876543210");
[Link]("BigInteger sum: " + [Link](big2));
// [Link]
double sqrtVal = [Link](144);
[Link]("Square root of 144: " + sqrtVal);
}
}

MCA II SEM III CBCS Page |6


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
Output:

MCA II SEM III CBCS Page |7


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:4


Q. Program using Abstract Class: Write a java program to create an abstract class
named Shape that contains two integers and an empty method named printArea().
Provide three classes named Rectangle, Triangle and Circle such that each one of the
classes extends the class Shape. Each one of the classes contain only the method
printArea( ) that prints the area of the given shape.
Source Code:
package mca;
abstract class Shape {
int dimension1, dimension2;
Shape(int d1, int d2) {
this.dimension1 = d1;
this.dimension2 = d2;
}
abstract void printArea();
}
class Rectangle extends Shape {
Rectangle(int length, int width) {
super(length, width);
}
void printArea() {
int area = dimension1 * dimension2;
[Link]("Area of Rectangle: " + area);
}
}
class Triangle extends Shape {
Triangle(int base, int height) {
super(base, height);
}
void printArea() {
double area = 0.5 * dimension1 * dimension2;
[Link]("Area of Triangle: " + area);
}
}
class Circle extends Shape {
Circle(int radius) {
super(radius, 0);
}
void printArea() {
double area = [Link] * dimension1 * dimension1;
[Link]("Area of Circle: " + area);
}
}

MCA II SEM III CBCS Page |8


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
public class ShapeTest {
public static void main(String[] args) {
Shape rectangle = new Rectangle(10, 5);
Shape triangle = new Triangle(8, 12);
Shape circle = new Circle(7);
[Link]();
[Link]();
[Link]();
}
}
Output:

MCA II SEM III CBCS Page |9


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:5


Q. Write a java program to illustrate the use of Interface.
Source Code:
package mca;
interface Animal {
void sound();
void sleep();
}
class Dog implements Animal {
public void sound() {
[Link]("Dog barks: Woof Woof!");
}
public void sleep() {
[Link]("Dog is sleeping...");
}
}
class Cat implements Animal {
public void sound() {
[Link]("Cat meows: Meow Meow!");
}
public void sleep() {
[Link]("Cat is sleeping...");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Animal myDog = new Dog();
[Link]();
[Link]();
Animal myCat = new Cat();
[Link]();
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 10


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:6


Q. Design application using String and StringBuilder (Function to count the number of
words in a given text, function to check the given string is palindrome or not.)
Source Code:
package mca;
import [Link];
public class StringApplication {
public static int countWords(String text) {
if (text == null || [Link]().isEmpty()) {
return 0;
}
String[] words = [Link]().split("\\s+");
return [Link];
}
public static boolean isPalindrome(String str) {
if (str == null || [Link]()) {
return false;
}
str = [Link]("\\s+", "").toLowerCase();
StringBuilder sb = new StringBuilder(str);
String reversed = [Link]().toString();
return [Link](reversed);
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a sentence: ");
String sentence = [Link]();
[Link]("Number of words: " + countWords(sentence));
[Link]("Enter a string to check palindrome: ");
String input = [Link]();
if (isPalindrome(input)) {
[Link]("\"" + input + "\" is a Palindrome.");
} else {
[Link]("\"" + input + "\" is NOT a Palindrome.");
}
[Link]();
}
}

MCA II SEM III CBCS P a g e | 11


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Output:

MCA II SEM III CBCS P a g e | 12


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:7


Q.a)Write a Java program to overload class method sum() – each method accepting 2
parameters – performing summation of either integer or floating point values.
Source Code:
package mca;
class Calculator {
int sum(int a, int b) {
return a + b;
}
double sum(double a, double b) {
return a + b;
}
}
public class MethodOverloadingDemo {
public static void main(String[] args) {
Calculator calc = new Calculator();
int intResult = [Link](10, 20);
[Link]("Sum of integers: " + intResult);
double doubleResult = [Link](12.5, 7.3);
[Link]("Sum of floating point numbers: " + doubleResult);
}
}
Output:

Q.b)Write a program to implement constructor overloading – parameterized


constructors, default constructor, copy constructor.
Source Code:
package mca;
class Student {
int id;
String course;
double marks;
Student() {
id = 0;
course = "Not Assigned";
marks = 0.0;
[Link]("Default Constructor Executed");
}

MCA II SEM III CBCS P a g e | 13


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
Student(int i, String c, double m) {
id = i;
course = c;
marks = m;
[Link]("Parameterized Constructor Executed");
}
Student(Student s) {
id = [Link];
course = [Link];
marks = [Link];
[Link]("Copy Constructor Executed");
}
void display() {
[Link]("ID: " + id + ", Course: " + course + ", Marks: " + marks);
}
public static void main(String[] args) {
Student st1 = new Student();
[Link]();
Student st2 = new Student(105, "Computer Science", 89.5);
[Link]();
Student st3 = new Student(st2);
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 14


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:8


Q. Write a program to implement inheritance in Java. Show function overriding by
creating objects of base and derived classes.
Source Code:
package mca;
class Vehicle {
String brand = "Generic Vehicle";
void displayInfo() {
[Link]("Brand: " + brand);
[Link]("This is a vehicle.");
}
}
class Car extends Vehicle {
int wheels = 4;
@Override
void displayInfo() {
[Link]("Brand: " + brand);
[Link]("This is a car.");
[Link]("Number of wheels: " + wheels);
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Vehicle v = new Vehicle();
[Link]("=== Vehicle Object ===");
[Link]();
[Link]();
Car c = new Car();
[Link] = "Toyota";
[Link]("=== Car Object ===");
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 15


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:9


Q. Write a program in Java that creates a class called Student having three members
name, age and enrolment_no :
i)Ensure that age instance variable of the class is never accessed directly and its value is
never less than 4 and greater than 40 for any object of the class.
ii)Ensure constructor always assigns a unique value to enrolment_no.
iii)Maintain a static variable for counting the number of student objects created.
iv)Write a remove method – if this method is invoked with a enrolment_no : the
corresponding object is removed, and the object counter is automatically decremented -
use finalize()
v)Use static methods to access the counter variable.
Source Code:
package mca;
class Student1 {
private String name;
private int age;
private final int enrolment_no;
private static int counter = 0;
private static int enrolmentGenerator = 1000;
public Student1(String name, int age) {
[Link] = name;
setAge(age);
enrolment_no = ++enrolmentGenerator;
counter++;
[Link]("Student Created: " + name + " | Enrolment No: " + enrolment_no);
}
public void setAge(int age) {
if (age >= 4 && age <= 40) {
[Link] = age;
} else {
[Link]("Invalid Age! Setting default age value: 4");
[Link] = 4;
}
}
public String getName() { return name; }
public int getAge() { return age; }
public int getEnrolmentNo() { return enrolment_no; }
public static int getStudentCount() {
return counter;
}
public void remove() {
[Link]("Removing Student: " + name + " | Enrolment No: " + enrolment_no);
try {

MCA II SEM III CBCS P a g e | 16


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
finalize();
} catch (Throwable e) {
[Link]();
}
}
@Override
protected void finalize() throws Throwable {
counter--;
[Link]("Student Object Finalized (Deleted): " + enrolment_no);
[Link]();
}
}
public class StudentTest {
public static void main(String[] args) {
Student1 s1 = new Student1("Amit", 20);
Student1 s2 = new Student1("Riya", 2); // Invalid age → auto corrected
Student1 s3 = new Student1("Karan", 25);
[Link]("\nTotal Students: " + [Link]());
[Link]();
s2 = null;
[Link]();
[Link]("\nFinal Student Count: " + [Link]());
}
}
Output:

MCA II SEM III CBCS P a g e | 17


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:10


Q. Write a Java program that reads a line of integers and then displays each integer and
the sum of all integers. (use StringTokenizer class).
Source Code:
package mca;
import [Link];
import [Link];
public class IntegerSum {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a line of integers (separated by spaces):");
String inputLine = [Link]();
StringTokenizer st = new StringTokenizer(inputLine);
int sum = 0;
[Link]("The integers are:");
while ([Link]()) {
int num = [Link]([Link]());
[Link](num);
sum += num;
}
[Link]("Sum of all integers: " + sum);
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 18


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:11

Q. Write a Java Program to test any five standard exceptions and User Defined Custom
Exceptions using throw keyword.

Source Code:
package mca;
import [Link];
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class ExceptionDemo {
static void validateAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above for registration!");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("**** Testing Standard Exceptions ****");
// 1. ArithmeticException
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Caught: " + e);
}
// 2. ArrayIndexOutOfBoundsException
try {
int arr[] = {1, 2, 3};
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught: " + e);
}
// 3. NullPointerException
try {
String str = null;
[Link]([Link]());
} catch (NullPointerException e) {
[Link]("Caught: " + e);
}
// 4. NumberFormatException
try {

MCA II SEM III CBCS P a g e | 19


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
int num = [Link]("ABC");
} catch (NumberFormatException e) {
[Link]("Caught: " + e);
}
// 5. StringIndexOutOfBoundsException
try {
String s = "Java";
[Link]([Link](10));
} catch (StringIndexOutOfBoundsException e) {
[Link]("Caught: " + e);
}
[Link]("\n**** Testing User-Defined Custom Exception ****");
try {
[Link]("Enter Age: ");
int age = [Link]();
validateAge(age);
[Link]("Registration Successful!");
} catch (InvalidAgeException e) {
[Link]("Custom Exception Caught: " + [Link]());
}
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 20


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:12


Q. Design java application using Collection in java using Array List Collection and
perform operations on ArrayList – You can implement ArrayList Library holding objects
of Class Book.; Add multiple books while creating object of library using constructor ,
also add methods like add a book, issue, return.
Source Code:
package mca;
import [Link];
import [Link];
class Book {
private int id;
private String title;
private boolean isIssued;
public Book(int id, String title) {
[Link] = id;
[Link] = title;
[Link] = false;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public boolean isIssued() {
return isIssued;
}
public void issue() {
isIssued = true;
}
public void returnBook() {
isIssued = false;
}
@Override
public String toString() {
return "Book ID: " + id + ", Title: \"" + title + "\", Issued: " + (isIssued ? "Yes" : "No");
}
}
class Library {
private ArrayList<Book> books;
public Library() {
books = new ArrayList<>();

MCA II SEM III CBCS P a g e | 21


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
[Link](new Book(101, "Java Programming"));
[Link](new Book(102, "Python Basics"));
[Link](new Book(103, "Data Structures"));
}
public void addBook(Book b) {
[Link](b);
[Link]("Book added successfully!");
}
public void issueBook(int id) {
for (Book b : books) {
if ([Link]() == id) {
if (![Link]()) {
[Link]();
[Link]("Book issued successfully!");
} else {
[Link]("Book is already issued.");
}
return;
}
}
[Link]("Book not found!");
}
public void returnBook(int id) {
for (Book b : books) {
if ([Link]() == id) {
if ([Link]()) {
[Link]();
[Link]("Book returned successfully!");
} else {
[Link]("Book was not issued.");
}
return;
}
}
[Link]("Book not found!");
}
public void displayBooks() {
[Link]("\n------ Library Books ------");
for (Book b : books) {
[Link](b);
}
}
}
public class LibraryManagement {

MCA II SEM III CBCS P a g e | 22


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
Library library = new Library();
int choice;
do {
[Link]("\n===== Library Menu =====");
[Link]("1. Display Books");
[Link]("2. Add Book");
[Link]("3. Issue Book");
[Link]("4. Return Book");
[Link]("5. Exit");
[Link]("Enter choice: ");
choice = [Link]();
switch (choice) {
case 1:
[Link]();
break;
case 2:
[Link]("Enter Book ID: ");
int id = [Link]();
[Link](); // clear buffer
[Link]("Enter Book Title: ");
String title = [Link]();
[Link](new Book(id, title));
break;
case 3:
[Link]("Enter Book ID to Issue: ");
[Link]([Link]());
break;
case 4:
[Link]("Enter Book ID to Return: ");
[Link]([Link]());
break;
case 5:
[Link]("Exiting program...");
break;
default:
[Link]("Invalid choice!");
}
} while (choice != 5);
[Link]();
}
}

MCA II SEM III CBCS P a g e | 23


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
Output:

MCA II SEM III CBCS P a g e | 24


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:13


Q. Design java application using Collection in java using Linked List Collection and
perform operations on Linked List.
Source Code:
package mca;
import [Link];
import [Link];
public class LinkedListDemo {
private LinkedList<String> items;
public LinkedListDemo() {
items = new LinkedList<>();
}
public void addItem(String item) {
[Link](item);
[Link](item + " added successfully!");
}
public void removeItem(String item) {
if ([Link](item)) {
[Link](item + " removed successfully!");
} else {
[Link](item + " not found in the list.");
}
}
public void searchItem(String item) {
if ([Link](item)) {
[Link](item + " is present in the list.");
} else {
[Link](item + " not found.");
}
}
public void updateItem(String oldItem, String newItem) {
int index = [Link](oldItem);
if (index != -1) {
[Link](index, newItem);
[Link](oldItem + " updated to " + newItem);
} else {
[Link](oldItem + " not found to update.");
}
}
public void displayItems() {
if ([Link]()) {
[Link]("List is empty!");

MCA II SEM III CBCS P a g e | 25


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
} else {
[Link]("Current Linked List: " + items);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
LinkedListDemo demo = new LinkedListDemo();
int choice;
do {
[Link]("\n--- LinkedList Operations Menu ---");
[Link]("1. Add Item");
[Link]("2. Remove Item");
[Link]("3. Search Item");
[Link]("4. Update Item");
[Link]("5. Display List");
[Link]("6. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link]();
switch (choice) {
case 1:
[Link]("Enter item to add: ");
[Link]([Link]());
break;
case 2:
[Link]("Enter item to remove: ");
[Link]([Link]());
break;
case 3:
[Link]("Enter item to search: ");
[Link]([Link]());
break;
case 4:
[Link]("Enter existing item to update: ");
String oldItem = [Link]();
[Link]("Enter new item: ");
String newItem = [Link]();
[Link](oldItem, newItem);
break;
case 5:
[Link]();
break;
case 6:
[Link]("Exiting... Thank you!");

MCA II SEM III CBCS P a g e | 26


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
break;
default:
[Link]("Invalid choice! Try again.");
}
} while (choice != 6);
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 27


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

MCA II SEM III CBCS P a g e | 28


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:14


Q. Write a java program that loads names and phone numbers from a text file into a hash
table where the data is organized as one line per record and each field in a record is
separated by a tab (\t). The program takes a name or phone number as input and prints
the corresponding other value from the hash table.
Source Code:
[Link](Text File):
Vaishnavi 9595376413
Siddhi 9960093964
Sarvesh 8788153857
Sunita 7840908312
Balaji 8421548384
Main Code:
package mca;
import [Link].*;
import [Link].*;
public class PhoneDirectory {
public static void main(String[] args) {
HashMap<String, String> nameToPhone = new HashMap<>();
HashMap<String, String> phoneToName = new HashMap<>();
try {
BufferedReader br = new BufferedReader(new FileReader("C:/Users/hp/eclipse-
workspace/MCA2nd/src/mca/[Link]"));
String line;
while ((line = [Link]()) != null) {
String[] parts = [Link]("\t");
if ([Link] == 2) {
String name = parts[0].trim();
String phone = parts[1].trim();
[Link](name, phone);
[Link](phone, name);
}
}
[Link]();
[Link]("Phone directory loaded successfully!");
} catch (Exception e) {
[Link]("Error reading file: " + [Link]());
return;
}
Scanner sc = new Scanner([Link]);
[Link]("\nEnter a name or phone number to search:");

MCA II SEM III CBCS P a g e | 29


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
String input = [Link]().trim();
if ([Link](input)) {
[Link]("Phone Number for " + input + " is: " + [Link](input));
} else if ([Link](input)) {
[Link]("Name for phone number " + input + " is: " + [Link](input));
} else {
[Link]("No match found in the directory.");
}
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 30


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:15


Q. Design and implement Networking application - Write a Java program (client) that
sends a text message to another Java program (server), which receives and displays it.
Use socket programming.
Source Code:
package mca;
import [Link].*;
import [Link].*;
class ServerThread extends Thread {
public void run() {
try {
[Link]("Server started...");
ServerSocket serverSocket = new ServerSocket(9999);
[Link]("Waiting for client...");
Socket socket = [Link]();
[Link]("Client connected!");
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()));
String message = [Link]();
[Link]("Client Message: " + message);
[Link]();
[Link]();
} catch (Exception e) {
[Link]("Server Error: " + e);
}
}
}
class ClientThread extends Thread {
public void run() {
try {
[Link](2000);
Socket socket = new Socket("localhost", 9999);
PrintWriter out = new PrintWriter([Link](), true);
String message = "Hello Server";
[Link](message);
[Link]("Message sent to server: " + message);
[Link]();
} catch (Exception e) {
[Link]("Client Error: " + e);
}
}
}

MCA II SEM III CBCS P a g e | 31


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
public class CombinedSocketProgram {
public static void main(String[] args) {
ServerThread server = new ServerThread();
ClientThread client = new ClientThread();
[Link]();
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 32


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:16


A)Write a program to retrieve web page using URL class.
Source Code:
package mca;
import [Link].*;
import [Link].*;
public class RetrieveWebPage {
public static void main(String[] args) {
try {
URL url = new URL("[Link]
URLConnection connection = [Link]();
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()));
String line;
[Link]("----- Web Page Content -----");
while ((line = [Link]()) != null) {
[Link](line);
}
[Link]();
} catch (Exception e) {
[Link]("Error: " + e);
}
}
}
Output:

MCA II SEM III CBCS P a g e | 33


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
B)Write a java program to obtain and display IP address from a given host
Source Code:
import [Link].*;
public class HostToIP {
public static void main(String[] args) {
try {
InetAddress addr = [Link]("[Link]");
[Link]("IP Address: " + [Link]());
} catch (Exception e) {
[Link]("Error: " + e);
}
}
}
Output:

C)Write a java program to display host name from ip address.


Source Code:
package mca;
import [Link].*;
public class IPToHost {
public static void main(String[] args) {
try {
InetAddress addr = [Link]("[Link]");
[Link]("Host Name: " + [Link]());
} catch (Exception e) {
[Link]("Error: " + e);
}
}
}
Output:

MCA II SEM III CBCS P a g e | 34


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:17


Q. Write a program to create Threads using both the methods: Extending the Thread
class and by Implementing the Runnable Interface and design an application showcasing
basic methods on thread like sleep(), join (). Give and display name to each thread ,also
set priorities.
Source Code:
package mca;
class MyThread1 extends Thread {
public MyThread1(String name) {
[Link](name);
}
public void run() {
try {
for (int i = 1; i <= 5; i++) {
[Link](getName() + " : " + i);
[Link](500);
}
} catch (Exception e) {
}
}
}
class MyThread2 implements Runnable {
Thread t;
public MyThread2(String name) {
t = new Thread(this, name);
}
public void run() {
try {
for (int i = 1; i <= 5; i++) {
[Link]([Link]() + " : " + i);
[Link](500);
}
} catch (Exception e) {
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
MyThread1 t1 = new MyThread1("Thread-1 (Extends)");
[Link](Thread.MAX_PRIORITY);
MyThread2 obj = new MyThread2("Thread-2 (Runnable)");
[Link](Thread.MIN_PRIORITY);

MCA II SEM III CBCS P a g e | 35


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
[Link]();
[Link]();
try {
[Link]();
[Link]();
} catch (Exception e) {
}
[Link]("Main thread finished.");
}
}
Output:

MCA II SEM III CBCS P a g e | 36


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:18


Q. Program on Multi-Threading: Write a java program that implements a multi-thread
application that has three threads. First thread generates random integer every 1 second
and if the value is even, second thread computes the square of the number and prints. If
the value is odd, the third thread will print the value of cube of the number.
Source Code:
package mca;
import [Link];
class NumberGenerator extends Thread {
public void run() {
Random r = new Random();
for (int i = 1; i <= 5; i++) {
int num = [Link](100);
[Link]("Generated Number: " + num);
if (num % 2 == 0) {
SquareThread st = new SquareThread(num);
[Link]();
} else {
CubeThread ct = new CubeThread(num);
[Link]();
}
try {
[Link](1000);
} catch (Exception e) {
}
}
}
}
class SquareThread extends Thread {
int num;
SquareThread(int num) {
[Link] = num;
}
public void run() {
int sq = num * num;
[Link]("Square of " + num + " = " + sq);
}
}
class CubeThread extends Thread {
int num;
CubeThread(int num) {
[Link] = num;

MCA II SEM III CBCS P a g e | 37


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
}
public void run() {
int cube = num * num * num;
[Link]("Cube of " + num + " = " + cube);
}
}
public class MultiThreadApp {
public static void main(String[] args) {
NumberGenerator ng = new NumberGenerator();
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 38


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:19


Q. Write a program to show synchronization in multiple threads - Main thread creates
two threads and passes a single object of type Pyramid to both the threads. Both threads
try to access draw_pyramid () method of the Pyramid object. One thread creates pyramid
of * and other pyramid of # - Show synchronized output i.e. two separate pyramids – one
of * and other of # should be displayed.
Source Code:
package mca;
class Pyramid {
synchronized void draw_pyramid(char ch) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
[Link](ch + " ");
}
[Link]();
}
[Link]();
}
}
class StarThread extends Thread {
Pyramid p;
StarThread(Pyramid p) {
this.p = p;
}
public void run() {
p.draw_pyramid('*');
}
}
class HashThread extends Thread {
Pyramid p;
HashThread(Pyramid p) {
this.p = p;
}
public void run() {
p.draw_pyramid('#');
}
}
public class SyncPyramid {
public static void main(String[] args) {
Pyramid p = new Pyramid();
StarThread t1 = new StarThread(p);
HashThread t2 = new HashThread(p);

MCA II SEM III CBCS P a g e | 39


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
[Link]();
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 40


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:20


[Link] on File Handling:
a)Write a Java program that reads on file name from the user, then displays information
about whether the file exists, whether the file is readable, whether the file is writable, the
type of file and the length of the file in bytes.
Source Code:
package mca;
import [Link];
import [Link];
public class FileInfo1 {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter file name: ");
String fname = [Link]();
File f = new File(fname);
[Link]("Exists: " + [Link]());
[Link]("Readable: " + [Link]());
[Link]("Writable: " + [Link]());
if ([Link](".")) {
String ext = [Link]([Link]('.') + 1);
[Link]("File Type: " + ext);
} else {
[Link]("File Type: Unknown");
}
[Link]("File Size (bytes): " + ([Link]() ? [Link]() : 0));
[Link]();
}
}
Output:

MCA II SEM III CBCS P a g e | 41


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
b)Also, write a program to write multiplication table of 4 in the file.
Source Code:
package mca;
import [Link];
public class WriteTable {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("C:/Users/hp/eclipse-
workspace/MCA2nd/src/mca/[Link]");
for (int i = 1; i <= 10; i++) {
[Link]("4 x " + i + " = " + (4 * i) + "\n");
}
[Link]();
[Link]("Multiplication table of 4 written to [Link]");
} catch (Exception e) {
[Link]("Error: " + e);
}
}
}
Output:

MCA II SEM III CBCS P a g e | 42


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:21


Q. Design GUI Based application using AWT, Swing and Event Handling: Write a java
program that simulates a traffic light. The program lets the user select one of three lights:
red, yellow, or green with radio buttons. On selecting a button, an appropriate message
with “stop” or “ready” or “go” should appear above the buttons in a selected color.
Initially there is no message shown.
Source Code:
package mca;
import [Link].*;
import [Link].*;
import [Link].*;
public class TrafficLight extends JFrame implements ActionListener {
JRadioButton red, yellow, green;
JLabel msg;
ButtonGroup group;
public TrafficLight() {
setTitle("Traffic Light");
setSize(300, 250);
setLayout(new FlowLayout());
msg = new JLabel("");
[Link](new Font("Arial", [Link], 22));
add(msg);
red = new JRadioButton("Red");
yellow = new JRadioButton("Yellow");
green = new JRadioButton("Green");
group = new ButtonGroup();
[Link](red);
[Link](yellow);
[Link](green);
add(red);
add(yellow);
add(green);
[Link](this);
[Link](this);
[Link](this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if ([Link]()) {
[Link]("STOP");
[Link]([Link]);

MCA II SEM III CBCS P a g e | 43


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
}
else if ([Link]()) {
[Link]("READY");
[Link]([Link]);
}
else if ([Link]()) {
[Link]("GO");
[Link]([Link]);
}
}
public static void main(String[] args) {
new TrafficLight();
}
}
Output:

MCA II SEM III CBCS P a g e | 44


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

MCA II SEM III CBCS P a g e | 45


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:22


Q. Event Handling: Write a Java program that handles all mouse events and shows the
event name at the center of the window when a mouse event is fired. (Use adapter classes).
Source Code:
package mca;
import [Link].*;
import [Link].*;
public class MouseEventsDemo extends Frame {
String msg = "";
public MouseEventsDemo() {
setSize(400, 300);
setTitle("Mouse Events Demo");
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) { msg = "Mouse Clicked"; repaint(); }
public void mousePressed(MouseEvent e) { msg = "Mouse Pressed"; repaint(); }
public void mouseReleased(MouseEvent e) { msg = "Mouse Released"; repaint(); }
public void mouseEntered(MouseEvent e) { msg = "Mouse Entered"; repaint(); }
public void mouseExited(MouseEvent e) { msg = "Mouse Exited"; repaint(); }
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) { msg = "Mouse Moved"; repaint(); }
public void mouseDragged(MouseEvent e) { msg = "Mouse Dragged"; repaint(); }
});
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) { [Link](0); }
});
setVisible(true);
}
public void paint(Graphics g) {
[Link](new Font("Arial", [Link], 22));
[Link](msg, 120, 150);
}
public static void main(String[] args) {
new MouseEventsDemo();
}
}

MCA II SEM III CBCS P a g e | 46


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
Output:

MCA II SEM III CBCS P a g e | 47


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:23


Q. Write a program that creates a user interface to perform integer divisions. The user
enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2
is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were
not an integer, the program would throw a NumberFormatException. If Num2 were
Zero, the program would throw an Arithmetic Exception Display the exception in a
message dialog box.
Source Code:
package mca;
import [Link].*;
import [Link].*;
import [Link].*;
public class DivisionGUI extends JFrame implements ActionListener {
JTextField num1, num2, result;
JButton divide;
public DivisionGUI() {
setTitle("Integer Division");
setSize(300, 200);
setLayout(new GridLayout(4, 2));
add(new JLabel("Num 1:"));
num1 = new JTextField();
add(num1);
add(new JLabel("Num 2:"));
num2 = new JTextField();
add(num2);
add(new JLabel("Result:"));
result = new JTextField();
[Link](false);
add(result);
divide = new JButton("Divide");
add(divide);
[Link](this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int n1 = [Link]([Link]());
int n2 = [Link]([Link]());
int res = n1 / n2;
[Link]([Link](res));
}

MCA II SEM III CBCS P a g e | 48


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
catch (NumberFormatException ex) {
[Link](this, "Please enter valid integers");
}
catch (ArithmeticException ex) {
[Link](this, "Cannot divide by zero");
}
}
public static void main(String[] args) {
new DivisionGUI();
}
}
Output:

MCA II SEM III CBCS P a g e | 49


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

Practical Lab Exercise:24


Q. Write a java program to implement basic calculator using grid layout.
Source Code:
package mca;
import [Link].*;
import [Link].*;
import [Link].*;
public class DigitalCalculator extends JFrame implements ActionListener {
JTextField display;
double num1 = 0, num2 = 0, result = 0;
char operator;
public DigitalCalculator() {
setTitle("Digital Calculator");
setSize(250, 330); // Smaller window
setLayout(new BorderLayout());
// Display Field
display = new JTextField();
[Link](false);
[Link](new Font("Arial", [Link], 22)); // Smaller font
[Link]([Link]);
add(display, [Link]);
// Buttons Panel
JPanel panel = new JPanel();
[Link](new GridLayout(5, 4, 2, 2)); // Small grid boxes
String buttons[] = {
"CE", "C", "+/-", "/",
"7", "8", "9", "*",
"4", "5", "6", "-",
"1", "2", "3", "+",
"%", "0", ".", "="
};
for (String b : buttons) {
JButton btn = new JButton(b);
[Link](new Font("Arial", [Link], 14)); // Smaller button font
[Link](this);
[Link](btn);
}
add(panel, [Link]);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {

MCA II SEM III CBCS P a g e | 50


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
String cmd = [Link]();
// DIGITS & DECIMAL
if ([Link]("[0-9]") || [Link](".")) {
[Link]([Link]() + cmd);
}
// CLEAR BUTTONS
else if ([Link]("CE") || [Link]("C")) {
[Link]("");
num1 = num2 = result = 0;
}
// PLUS-MINUS
else if ([Link]("+/-")) {
if (![Link]().equals("")) {
double val = [Link]([Link]());
[Link]([Link](val * -1));
}
}
// OPERATORS (+, -, *, /, %)
else if ("+-*/%".contains(cmd)) {
num1 = [Link]([Link]());
operator = [Link](0);
[Link]("");
}
// EQUAL BUTTON (=)
else if ([Link]("=")) {
if ([Link]().equals("")) return;
num2 = [Link]([Link]());
switch (operator) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/':
if (num2 == 0) {
[Link](this, "Cannot divide by zero!");
return;
}
result = num1 / num2;
break;
case '%': result = num1 % num2; break;
}
// Show full expression
[Link](num1 + " " + operator + " " + num2 + " = " + result);
}
}

MCA II SEM III CBCS P a g e | 51


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26
public static void main(String[] args) {
new DigitalCalculator();
}
}
Output:

MCA II SEM III CBCS P a g e | 52


Vaishnavi Balaji Pujari Lab Based on CC301|Java Programming|2025-26

MCA II SEM III CBCS P a g e | 53

You might also like