0% found this document useful (0 votes)
18 views45 pages

Java Programming Projects and Tutorials

This document outlines a Java Programming course project from Govt. P.G. Nehru College, covering various topics such as JDK installation, arithmetic operations, string manipulation, constructor chaining, aggregation, method overriding, and exception handling. Each section includes example code and explanations for implementing these concepts in Java. The project aims to provide practical experience in Java programming for Master of Science (Computer Science) students during the academic session 2025-2026.

Uploaded by

8607055993md
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)
18 views45 pages

Java Programming Projects and Tutorials

This document outlines a Java Programming course project from Govt. P.G. Nehru College, covering various topics such as JDK installation, arithmetic operations, string manipulation, constructor chaining, aggregation, method overriding, and exception handling. Each section includes example code and explanations for implementing these concepts in Java. The project aims to provide practical experience in Java programming for Master of Science (Computer Science) students during the academic session 2025-2026.

Uploaded by

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

Govt. P.G.

Nehru College, Jhajjar


(Haryana)

Subject: Java Programming

Submitted By: Name:

Course: Master of Science (Computer Science)

Roll No.: 22417250

Submitted To: Name:

Academic Session: 2025-2026


Index
1. Install and configure JDK, then compile & run a basic Java program.

2. Implement arithmetic operations using user-defined functions.

3. Write a program demonstrating String comparison and mutable/immutable strings.

4. Create a constructor-based Java program showcasing constructor chaining.

5. Develop an application showcasing aggregation and composition in Java classes.

6. Implement and explain the difference between method overriding and hiding.

7. Write a program implementing abstract classes and interfaces together.

8. Develop an application demonstrating exception handling and logging.

9. Implement a program that performs file handling using byte and character streams.

10. Create a Java program with multiple threads executing concurrently.

11. Implement the producer-consumer problem using thread synchronization.

12. Write a program using GUI components with different layout managers.

13. Develop a basic GUI-based expense tracker application.

14. Implement collection framework operations using HashMap, TreeMap, and


LinkedList.

15. Create a simple library management system using OOP.

16. Implement networking in Java using sockets to send and receive data.

Teacher sign -…………………


PROGRAM
🧰 Step 1: Install and Configure JDK
1. Download JDK
o Visit Oracle JDK Downloads.
o Download the latest version (e.g., JDK 21 or later) for Windows.
2. Install JDK
o Run the installer and follow the prompts (default settings are fine).
3. Set Environment Variables
o Open System Properties → Advanced → Environment Variables.
o Add a new variable:
▪ Variable name: JAVA_HOME
▪ Variable value: Path to your JDK (e.g., C:\Program Files\Java\jdk-21)
o Add %JAVA_HOME%\bin to the Path variable.
4. Verify Installation
5. java -version

6. javac -version

You should see output like:

java version "21"

javac 21

For Linux / macOS

Run these commands in the terminal:

sudo apt update

sudo apt install openjdk-21-jdk -y

Verify:

java -version

javac -version
Step 2: Write a Simple Java Program
Create a new file called [Link].

// [Link]

public class HelloWorld {

public static void main(String[] args) {

[Link]("Hello, Java is successfully


installed!");

Step 3: Compile the Java Program


Open your terminal (or Command Prompt) and navigate to the folder containing
[Link].

javac [Link]

This will create a file named [Link] (the compiled bytecode).

▶️ Step 4: Run the Program


java HelloWorld

Output:

Hello, Java is successfully installed!

Optional: Automate with a Script


Windows (Batch Script): [Link]
@echo off
REM Check Java installation

java -version >nul 2>&1

IF %ERRORLEVEL% NEQ 0 (

echo Java is not installed. Please install JDK from Oracle or


OpenJDK.

exit /b

REM Compile and run [Link]

javac [Link]

java HelloWorld

pause

Linux/macOS (Shell Script): [Link]


#!/bin/bash

# Check if Java is installed

if ! command -v java &> /dev/null; then

echo "Java not found. Installing OpenJDK..."

sudo apt update

sudo apt install -y openjdk-21-jdk

# Compile and run the program

javac [Link]

java HelloWorld
PROGRAM
Program: Implement Arithmetic Operations Using User-Defined Functions
// File: [Link]

import [Link];

public class ArithmeticOperations {

// User-defined function for addition


public static double add(double a, double b) {
return a + b;
}

// User-defined function for subtraction


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

// User-defined function for multiplication


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

// User-defined function for division


public static double divide(double a, double b) {
if (b == 0) {
[Link]("Error: Division by zero is not allowed.");
return 0;
}
return a / b;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Input from user


[Link]("Enter first number: ");
double num1 = [Link]();

[Link]("Enter second number: ");


double num2 = [Link]();

// Performing operations using user-defined functions


[Link]("\n=== Arithmetic Operations ===");
[Link]("Addition: " + add(num1, num2));
[Link]("Subtraction: " + subtract(num1, num2));
[Link]("Multiplication: " + multiply(num1, num2));
[Link]("Division: " + divide(num1, num2));

[Link]();
}
}

Sample Output
Enter first number: 10
Enter second number: 5

=== Arithmetic Operations ===


Addition: 15.0
Subtraction: 5.0
Multiplication: 50.0
Division: 2.0
PROGRAM

Write a program demonstrating String


comparison and mutable/immutable strings .

// File: [Link]
public class StringDemo {
public static void main(String[] args) {
// === String Comparison ===
[Link]("=== String Comparison ===");
String str1 = "Hello";
String str2 = "Hello";
String str3 = new String("Hello");
// Using '==' compares references (memory addresses)

[Link]("str1 == str2 : " + (str1 == str2)); // true, both refer to


same string pool object

[Link]("str1 == str3 : " + (str1 == str3)); // false, str3 is a new object


// Using equals() compares actual contents
[Link]("[Link](str3) : " + [Link](str3)); // true
// === Immutable Strings ===
[Link]("\n=== Immutable Strings ===");
String s = "Java";
[Link]("Original String: " + s);
[Link](" Programming"); // creates a new string but doesn't change 's'
[Link]("After concat (without assignment): " + s);
s = [Link](" Programming"); // reassign to new string
[Link]("After concat (with assignment)
// === Mutable Strings (StringBuilder and StringBuffer) ===
[Link]("\n=== Mutable Strings ===");
// Using StringBuilder (not thread-safe, faster)
StringBuilder sb = new StringBuilder("Hello");
[Link](" World");
[Link]("StringBuilder result: " + sb);
// Using StringBuffer (thread-safe, slower)
StringBuffer sbf = new StringBuffer("Good");
[Link](" Morning");
[Link]("StringBuffer result: " + sbf);
}
}

OUTOUT:
=== String Comparison ===
str1 == str2 : true
str1 == str3 : false
[Link](str3) : true

=== Immutable Strings ===


Original String: Java
After concat (without assignment): Java
After concat (with assignment): Java Programming

=== Mutable Strings ===


StringBuilder result: Hello World
StringBuffer result: Good Morning
PROGRAM
Program: Constructor Chaining in Java
// File: [Link]

class Person {
String name;
int age;

// Default constructor
Person() {
this("Unknown", 0); // Calls parameterized constructor in the same
class
[Link]("Default constructor of Person called");
}

// Parameterized constructor
Person(String name, int age) {
[Link] = name;
[Link] = age;
[Link]("Parameterized constructor of Person called");
}
}

class Employee extends Person {


String department;
double salary;

// Default constructor
Employee() {
this("Not Assigned", 0.0); // Calls another constructor in Employee
class
[Link]("Default constructor of Employee called");
}

// Parameterized constructor
Employee(String department, double salary) {
super("John Doe", 30); // Calls parent (Person) class constructor
[Link] = department;
[Link] = salary;
[Link]("Parameterized constructor of Employee called");
}

// Display method
void displayDetails() {
[Link]("\n--- Employee Details ---");
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Department: " + department);
[Link]("Salary: " + salary);
}
}

OUTPUT:
Sample Output
Creating Employee object using default constructor...
Parameterized constructor of Person called
Parameterized constructor of Employee called
Default constructor of Employee called
--- Employee Details ---
Name: John Doe
Age: 30
Department: Not Assigned
Salary: 0.0

Creating Employee object using parameterized constructor...


Parameterized constructor of Person called
Parameterized constructor of Employee called
--- Employee Details ---
Name: John Doe
Age: 30
Department: IT
Salary: 50000.0

PROGRAM
Program: Aggregation and Composition in Java
// File: [Link]

// --- Composition Example ---


// Engine is part of a Car (strong relationship)
// If Car is destroyed, Engine is also destroyed.
class Engine {
private String type;

public Engine(String type) {


[Link] = type;
}

public void start() {


[Link]("Engine of type " + type + " started.");
}

public String getType() {


return type;
}
}

class Car {
private String model;
private Engine engine; // Composition relationship

public Car(String model, String engineType) {


[Link] = model;
[Link] = new Engine(engineType); // Engine created inside Car
(composition)
}

public void startCar() {


[Link]("Starting car: " + model);
[Link]();
}

public void showDetails() {


[Link]("Car model: " + model + ", Engine type: " +
[Link]());
}
}

// --- Aggregation Example ---


// Department has Employees (weak relationship)
// Employees can exist even if Department is deleted.
class Employee {
private String name;

public Employee(String name) {


[Link] = name;
}

public void showEmployee() {


[Link]("Employee: " + name);
}
}

class Department {
private String deptName;
private Employee[] employees; // Aggregation relationship

public Department(String deptName, Employee[] employees) {


[Link] = deptName;
[Link] = employees; // Employees passed from outside
(aggregation)
}

public void showDepartmentDetails() {


[Link]("\nDepartment: " + deptName);
[Link]("Employees in department:");
for (Employee e : employees) {
[Link]();
}
}
}

// --- Main Class ---


public class AggregationCompositionDemo {
public static void main(String[] args) {

[Link]("=== Composition Example ===");


Car car = new Car("Toyota Camry", "V6 Engine");
[Link]();
[Link]();

[Link]("\n=== Aggregation Example ===");


Employee e1 = new Employee("Alice");
Employee e2 = new Employee("Bob");
Employee e3 = new Employee("Charlie");

Employee[] empArray = {e1, e2, e3};

Department dept = new Department("IT Department", empArray);


[Link]();
}
}

Sample Output
=== Composition Example ===
Starting car: Toyota Camry
Engine of type V6 Engine started.
Car model: Toyota Camry, Engine type: V6 Engine

=== Aggregation Example ===


Department: IT Department
Employees in department:
Employee: Alice
Employee: Bob
Employee: Charlie
PROGRAM
Program: Implement and Explain Method Overriding and Method
Hiding
// File: [Link]

class Parent {
// Instance method — can be overridden
public void instanceMethod() {
[Link]("Parent's instance method");
}

// Static method — can be hidden, not overridden


public static void staticMethod() {
[Link]("Parent's static method");
}
}

class Child extends Parent {


// Overriding the instance method
@Override
public void instanceMethod() {
[Link]("Child's overridden instance method");
}

// Hiding the static method (not overriding)


public static void staticMethod() {
[Link]("Child's hidden static method");
}
}

public class MethodOverridingAndHidingDemo {


public static void main(String[] args) {

[Link]("=== Method Overriding Example ===");


Parent parentObj = new Parent();
Parent childAsParent = new Child(); // Parent reference, Child object

[Link](); // Calls Parent's version


[Link](); // Calls Child's version (runtime
polymorphism)

[Link]("\n=== Method Hiding Example ===");


[Link](); // Calls Parent's version
[Link](); // Calls Parent's version (based on
reference type)

Child childObj = new Child();


[Link](); // Calls Child's version (based on
class)
}
}
Sample Output
=== Method Overriding Example ===
Parent's instance method
Child's overridden instance method

=== Method Hiding Example ===


Parent's static method
Parent's static method
Child's hidden static method

PROGRAM
Program: Implementing Abstract Classes and Interfaces Together
// File: [Link]

// --- Interface: Defines behavior (contract) ---


interface Payable {
double calculatePay(); // abstract method (implicitly public and
abstract)
}

// --- Abstract Class: Provides partial implementation ---


abstract class Employee implements Payable {
String name;
int empId;
double baseSalary;

// Constructor
public Employee(String name, int empId, double baseSalary) {
[Link] = name;
[Link] = empId;
[Link] = baseSalary;
}

// Abstract method (must be implemented by subclasses)


public abstract void displayDetails();

// Concrete (non-abstract) method


public void showBasicInfo() {
[Link]("Employee ID: " + empId);
[Link]("Employee Name: " + name);
}
}

// --- Concrete Class: Implements abstract methods and interface methods ---
class FullTimeEmployee extends Employee {
private double bonus;

public FullTimeEmployee(String name, int empId, double baseSalary, double


bonus) {
super(name, empId, baseSalary);
[Link] = bonus;
}

// Implement abstract method from Employee


@Override
public void displayDetails() {
showBasicInfo();
[Link]("Base Salary: " + baseSalary);
[Link]("Bonus: " + bonus);
[Link]("Total Pay: " + calculatePay());
}

// Implement method from Payable interface


@Override
public double calculatePay() {
return baseSalary + bonus;
}
}
Sample Output
=== Full-Time Employee ===
Employee ID: 101
Employee Name: Alice
Base Salary: 50000.0
Bonus: 5000.0
Total Pay: 55000.0
PROGRAM
Program: Exception Handling and Logging in Java
// File: [Link]

import [Link];
import [Link].*;

public class ExceptionHandlingAndLoggingDemo {

// Create a Logger instance


private static final Logger logger =
[Link]([Link]());

public static void main(String[] args) {


// Configure logger
[Link]().reset(); // reset default settings
[Link]([Link]);

// Add a ConsoleHandler to display logs in console


ConsoleHandler handler = new ConsoleHandler();
[Link]([Link]);
[Link](handler);

Scanner sc = new Scanner([Link]);

try {
[Link]("=== Division Calculator ===");
[Link]("Enter numerator: ");
int num = [Link]();

[Link]("Enter denominator: ");


int den = [Link]();

[Link]("User entered numerator: " + num + " and denominator:


" + den);

int result = divide(num, den);


[Link]("Result: " + result);
[Link]("Division successful: " + result);

} catch (ArithmeticException e) {
[Link]([Link], "Division by zero attempted", e);
[Link]("Error: Division by zero is not allowed.");

} catch (Exception e) {
[Link]([Link], "Unexpected error occurred", e);
[Link]("An unexpected error occurred: " +
[Link]());

} finally {
[Link]("Program execution completed.");
[Link]();
}
}
// User-defined method that may throw an exception
public static int divide(int a, int b) throws ArithmeticException {
[Link]("Performing division operation...");
return a / b; // may throw ArithmeticException
}
}

Sample Output

✅Case 1: Normal Input


=== Division Calculator ===
Enter numerator: 20
Enter denominator: 5
Result: 4

Logs:

INFO: User entered numerator: 20 and denominator: 5


FINE: Performing division operation...
INFO: Division successful: 4
INFO: Program execution completed.

❌Case 2: Division by Zero


=== Division Calculator ===
Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed.

Logs:

INFO: User entered numerator: 10 and denominator: 0


SEVERE: Division by zero attempted
[Link]: / by zero
INFO: Program execution completed.

INFO: User entered numerator: 10 and denominator: 0


SEVERE: Division by zero attempted
[Link]: / by zero
INFO: Program execution completed.
PROGRAM
Program: Multiple Threads Example in Java
// File: [Link]
class Task1 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Task 1 - Count: " + i);
try {
[Link](500); // pause for half a second
} catch (InterruptedException e) {
[Link]("Task 1 interrupted");
}
}
[Link]("Task 1 completed!");
}
}

class Task2 extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Task 2 - Count: " + i);
try {
[Link](700); // pause for 0.7 seconds
} catch (InterruptedException e) {
[Link]("Task 2 interrupted");
}
}
[Link]("Task 2 completed!");
}
}

class Task3 implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Task 3 (Runnable) - Count: " + i);
try {
[Link](600);
} catch (InterruptedException e) {
[Link]("Task 3 interrupted");
}
}
[Link]("Task 3 completed!");
}
}

public class MultiThreadExample {


public static void main(String[] args) {
// Create thread objects
Task1 t1 = new Task1();
Task2 t2 = new Task2();
Thread t3 = new Thread(new Task3());
// Start all threads
[Link]();
[Link]();
[Link]();

// Wait for all threads to finish


try {
[Link]();
[Link]();
[Link]();
} catch (InterruptedException e) {
[Link]("Main thread interrupted");
}

[Link]("All tasks completed. Main thread exiting.");


}
}

Sample Output (will vary due to thread scheduling)


Task 1 - Count: 1
Task 2 - Count: 1
Task 3 (Runnable) - Count: 1
Task 1 - Count: 2
Task 3 (Runnable) - Count: 2
Task 2 - Count: 2
...
Task 1 completed!
Task 3 completed!
Task 2 completed!
All tasks completed. Main thread exiting.
PROGRAM
Program: Producer-Consumer Problem in Java
// File: [Link]

import [Link];

class SharedBuffer {
private LinkedList<Integer> buffer = new LinkedList<>();
private int capacity = 5; // Maximum buffer size

// Method for producer to add items


public synchronized void produce(int value) throws InterruptedException {
while ([Link]() == capacity) {
[Link]("Buffer full. Producer waiting...");
wait(); // wait for consumer to consume
}

[Link](value);
[Link]("Produced: " + value);

notify(); // notify consumer that new data is available


}

// Method for consumer to remove items


public synchronized int consume() throws InterruptedException {
while ([Link]()) {
[Link]("Buffer empty. Consumer waiting...");
wait(); // wait for producer to produce
}

int value = [Link]();


[Link]("Consumed: " + value);

notify(); // notify producer that space is available


return value;
}
}

class Producer extends Thread {


private SharedBuffer buffer;

public Producer(SharedBuffer buffer) {


[Link] = buffer;
}

public void run() {


int value = 0;
try {
while (true) {
[Link](value++);
[Link](1000); // simulate production time
}
} catch (InterruptedException e) {
[Link]("Producer interrupted");
}
}
}

class Consumer extends Thread {


private SharedBuffer buffer;

public Consumer(SharedBuffer buffer) {


[Link] = buffer;
}

public void run() {


try {
while (true) {
[Link]();
[Link](1500); // simulate consumption time
}
} catch (InterruptedException e) {
[Link]("Consumer interrupted");
}
}
}

Sample Output
Produced: 0
Consumed: 0
Produced: 1
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
...
PROGRAM
Example: Java GUI Program with Multiple Layout Managers

import [Link].*;
import [Link].*;

public class LayoutManagerExample {


public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("Layout Manager Example");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](500, 400);
[Link](new BorderLayout(10, 10)); // Main layout for the
frame

// --------- NORTH PANEL (FlowLayout) ----------


JPanel northPanel = new JPanel();
[Link](new FlowLayout([Link], 10, 10));
[Link](Color.LIGHT_GRAY);
[Link](new JButton("Home"));
[Link](new JButton("About"));
[Link](new JButton("Contact"));
[Link](northPanel, [Link]);

// --------- CENTER PANEL (GridLayout) ----------


JPanel centerPanel = new JPanel();
[Link](new GridLayout(2, 2, 10, 10));
[Link]([Link]);
[Link](new JButton("Button 1"));
[Link](new JButton("Button 2"));
[Link](new JButton("Button 3"));
[Link](new JButton("Button 4"));
[Link](centerPanel, [Link]);

// --------- SOUTH PANEL (FlowLayout) ----------


JPanel southPanel = new JPanel(new FlowLayout([Link]));
[Link]([Link]);
[Link](new JButton("OK"));
[Link](new JButton("Cancel"));
[Link](southPanel, [Link]);

// --------- WEST PANEL (BoxLayout) ----------


JPanel westPanel = new JPanel();
[Link](new BoxLayout(westPanel, BoxLayout.Y_AXIS));
[Link](new JLabel("Options:"));
[Link](new JCheckBox("Option 1"));
[Link](new JCheckBox("Option 2"));
[Link](new JCheckBox("Option 3"));
[Link](westPanel, [Link]);

// Make frame visible


[Link](true);
}
}
. Output (Conceptually)
-------------------------------------------------
| Home | About | Contact |
-------------------------------------------------
| Options: | Button1 | Button2 |
| | Button3 | Button4 |
-------------------------------------------------
| OK Cancel |
-------------------------------------------------
PROGRAM
Program: Implement Arithmetic Operations Using User-Defined Functions
// File: [Link]

import [Link];

public class ArithmeticOperations {

// User-defined function for addition


public static double add(double a, double b) {
return a + b;
}

// User-defined function for subtraction


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

// User-defined function for multiplication


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

// User-defined function for division


public static double divide(double a, double b) {
if (b == 0) {
[Link]("Error: Division by zero is not allowed.");
return 0;
}
return a / b;
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

// Input from user


[Link]("Enter first number: ");
double num1 = [Link]();

[Link]("Enter second number: ");


double num2 = [Link]();

// Performing operations using user-defined functions


[Link]("\n=== Arithmetic Operations ===");
[Link]("Addition: " + add(num1, num2));
[Link]("Subtraction: " + subtract(num1, num2));
[Link]("Multiplication: " + multiply(num1, num2));
[Link]("Division: " + divide(num1, num2));

[Link]();
}
}

Sample Output
Enter first number: 10
Enter second number: 5

=== Arithmetic Operations ===


Addition: 15.0
Subtraction: 5.0
Multiplication: 50.0
Division: 2.0
Sample Output
Enter first number: 10
Enter second number: 5

=== Arithmetic Operations ===


Addition: 15.0
Subtraction: 5.0
Multiplication: 50.0
Division: 2.0
PROGRAM
Write a program Implement collection framework operations using HashMap, TreeMap, and
LinkedList

Java Program: Collection Framework Operations


import [Link].*;

public class CollectionFrameworkDemo {


public static void main(String[] args) {

// ======== 1 ⃣ HashMap Example ========


[Link]("---- HashMap Example ----");

// Create a HashMap
HashMap<Integer, String> hashMap = new HashMap<>();

// Add key-value pairs


[Link](3, "Apple");
[Link](1, "Banana");
[Link](2, "Cherry");

// Display HashMap (unordered)


[Link]("HashMap: " + hashMap);

// Get a value by key


[Link]("Value for key 2: " + [Link](2));

// Remove a key-value pair


[Link](1);
[Link]("After removing key 1: " + hashMap);

// Iterate over entries


[Link]("Iterating through HashMap:");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]([Link]() + " → " + [Link]());
}

// ======== 2 ⃣ TreeMap Example ========


[Link]("\n---- TreeMap Example ----");

// TreeMap automatically sorts by keys


TreeMap<Integer, String> treeMap = new TreeMap<>();

[Link](3, "Red");
[Link](1, "Green");
[Link](2, "Blue");

[Link]("TreeMap (Sorted by key): " + treeMap);

// First and Last keys


[Link]("First key: " + [Link]());
[Link]("Last key: " + [Link]());
// Search for a key
if ([Link](2)) {
[Link]("TreeMap contains key 2: " + [Link](2));
}

// Iterate using forEach


[Link]((key, value) -> [Link](key + " = " +
value));

// ======== 3 ⃣ LinkedList Example ========


[Link]("\n---- LinkedList Example ----");

LinkedList<String> linkedList = new LinkedList<>();

// Add elements
[Link]("Monday");
[Link]("Tuesday");
[Link]("Wednesday");

[Link]("LinkedList: " + linkedList);

// Add at first and last


[Link]("Sunday");
[Link]("Thursday");
[Link]("After addFirst & addLast: " + linkedList);

// Remove elements
[Link]("Tuesday");
[Link]();
[Link]();
[Link]("After removals: " + linkedList);

// Access element by index


[Link]("Element at index 1: " + [Link](1));

// Iterate using for-each


[Link]("Iterating through LinkedList:");
for (String day : linkedList) {
[Link](day);
}

// Sort LinkedList alphabetically


[Link](linkedList);
[Link]("Sorted LinkedList: " + linkedList);
}
}

Program Output Example


---- HashMap Example ----
HashMap: {1=Banana, 2=Cherry, 3=Apple}
Value for key 2: Cherry
After removing key 1: {2=Cherry, 3=Apple}
Iterating through HashMap:
2 → Cherry
3 → Apple

---- TreeMap Example ----


TreeMap (Sorted by key): {1=Green, 2=Blue, 3=Red}
First key: 1
Last key: 3
TreeMap contains key 2: Blue
1 = Green
2 = Blue
3 = Red
PROGRAM
Write a program Develop a basic GUI-based expense tracker application.

Expense Tracker (Basic GUI App)


import tkinter as tk
from tkinter import messagebox, ttk

class ExpenseTracker:
def __init__(self, root):
[Link] = root
[Link]("Expense Tracker")
[Link]("600x400")
[Link](False, False)

# Data storage
[Link] = []

# --- Title ---


title_label = [Link](root, text="Expense Tracker", font=("Arial",
18, "bold"))
title_label.pack(pady=10)

# --- Input Frame ---


input_frame = [Link](root)
input_frame.pack(pady=10)

# Description
[Link](input_frame, text="Description:").grid(row=0, column=0,
padx=5, pady=5)
self.desc_entry = [Link](input_frame, width=20)
self.desc_entry.grid(row=0, column=1, padx=5, pady=5)

# Amount
[Link](input_frame, text="Amount ($):").grid(row=0, column=2,
padx=5, pady=5)
self.amount_entry = [Link](input_frame, width=10)
self.amount_entry.grid(row=0, column=3, padx=5, pady=5)

# Category
[Link](input_frame, text="Category:").grid(row=0, column=4, padx=5,
pady=5)
self.category_entry = [Link](input_frame, width=15)
self.category_entry.grid(row=0, column=5, padx=5, pady=5)

# Add Button
add_btn = [Link](input_frame, text="Add Expense",
command=self.add_expense)
add_btn.grid(row=0, column=6, padx=10, pady=5)

# --- Expense List ---


columns = ("Description", "Amount", "Category")
[Link] = [Link](root, columns=columns, show="headings",
height=10)
[Link]("Description", text="Description")
[Link]("Amount", text="Amount ($)")
[Link]("Category", text="Category")
[Link](pady=10)

# --- Total Display ---


self.total_label = [Link](root, text="Total: $0.00", font=("Arial",
12, "bold"))
self.total_label.pack(pady=10)

# --- Buttons Frame ---


btn_frame = [Link](root)
btn_frame.pack()

clear_btn = [Link](btn_frame, text="Clear All",


command=self.clear_expenses, bg="red", fg="white")
clear_btn.grid(row=0, column=0, padx=10)

exit_btn = [Link](btn_frame, text="Exit", command=[Link],


bg="gray", fg="white")
exit_btn.grid(row=0, column=1, padx=10)

# --- Functions ---


def add_expense(self):
desc = self.desc_entry.get().strip()
amount = self.amount_entry.get().strip()
category = self.category_entry.get().strip()

if not desc or not amount or not category:


[Link]("Input Error", "Please fill all fields.")
return

try:
amount = float(amount)
except ValueError:
[Link]("Input Error", "Amount must be a number.")
return

[Link]((desc, amount, category))


[Link]("", [Link], values=(desc, f"{amount:.2f}",
category))
self.update_total()

# Clear fields
self.desc_entry.delete(0, [Link])
self.amount_entry.delete(0, [Link])
self.category_entry.delete(0, [Link])

def update_total(self):
total = sum(amount for _, amount, _ in [Link])
self.total_label.config(text=f"Total: ${total:.2f}")

def clear_expenses(self):
[Link]()
for item in [Link].get_children():
[Link](item)
self.update_total()
# --- Main Program ---
if __name__ == "__main__":
root = [Link]()
app = ExpenseTracker(root)
[Link]()

OUTPUT:
------------------------------------------------------------
| Expense Tracker |
|------------------------------------------------------------|
| Description: [__________] Amount ($): [____] Category: |
| [_________] [Add Expense] |
|------------------------------------------------------------|
| Description | Amount ($) | Category |
|------------------------------------------------------------|
| Lunch | 12.50 | Food |
| Uber Ride | 8.00 | Transport |
| Coffee | 3.50 | Food |
|------------------------------------------------------------|
| Total: $24.00 |
|------------------------------------------------------------|
| [Clear All] [Exit] |
------------------------------------------------------------
PROGRAM
Create a simple library management system using OOP.

Java Program: Simple Library Management System


import [Link];
import [Link];

// Class representing a single Book


class Book {
private int id;
private String title;
private String author;
private boolean isAvailable;

public Book(int id, String title, String author) {


[Link] = id;
[Link] = title;
[Link] = author;
[Link] = true;
}

// Getters
public int getId() {
return id;
}

public String getTitle() {


return title;
}

public String getAuthor() {


return author;
}

public boolean isAvailable() {


return isAvailable;
}

// Methods to borrow and return a book


public void borrowBook() {
if (isAvailable) {
isAvailable = false;
[Link](title + " has been borrowed successfully!");
} else {
[Link](title + " is currently not available.");
}
}
OUTPUT:
===== Library Management System =====
1. Add Book
2. Display All Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 1
Enter book ID: 101
Enter book title: Java Basics
Enter author name: John Doe
Book added successfully: Java Basics

===== Library Management System =====


1. Add Book
2. Display All Books
3. Borrow Book
4. Return Book
5. Exit
Enter your choice: 2

=== List of Books ===


Book ID: 101 | Title: Java Basics | Author: John Doe | Available: Yes

===== Library Management System =====


Enter your choice: 3
Enter book ID to borrow: 101
Java Basics has been borrowed successfully!

===== Library Management System =====


Enter your choice: 4
Enter book ID to return: 101
Java Basics has been returned successfully!
PROGRAM

Implement networking in Java using sockets to send and


receive data.

Java Networking Example (Client-Server using Sockets)

W e’ ll c re at e two Java files:

1. [Link] — Lis te n s fo r c o n n e c t io n s a n d re c e iv e s m e s s a g e s
2. [Link] — C o n n e c t s to th e s e rv e r a n d s e n d s m e s s a g e s

🖥 1. [Link]

import [Link].*;
import [Link].*;

public class Server {


public static void main(String[] args) {
final int PORT = 5000;

try (ServerSocket serverSocket = new ServerSocket(PORT)) {


[Link]("Server started. Waiting for client connection..
.");

Socket socket = [Link]();


[Link]("Client connected!");

// Input and Output streams


BufferedReader input = new BufferedReader(new
InputStreamReader([Link]()));
PrintWriter output = new PrintWriter([Link](),
true);

// Communication loop
String clientMessage;
while ((clientMessage = [Link]()) != null) {
[Link]("Client says: " + clientMessage);
[Link]("Server received: " + clientMessage);

if ([Link]("exit")) {
[Link]("Client disconnected.");
break;
}
}

// Close resources
[Link]();
[Link]();
[Link]();
[Link]("Server closed.");

} catch (IOException e) {
[Link]();
}
}
}

💻 2. [Link]

import [Link].*;
import [Link].*;
import [Link];

public class Client {


public static void main(String[] args) {
final String SERVER_ADDRESS = "localhost";
final int PORT = 5000;

try (Socket socket = new Socket(SERVER_ADDRESS, PORT)) {


[Link]("Connected to the server.");

BufferedReader input = new BufferedReader(new


InputStreamReader([Link]()));
PrintWriter output = new PrintWriter([Link](),
true);
Scanner scanner = new Scanner([Link]);

String message;
while (true) {
[Link]("Enter message (type 'exit' to quit): ");
message = [Link]();

[Link](message); // send message to server

if ([Link]("exit")) {
[Link]("Disconnected from server.");
break;
}

String response = [Link]();


[Link]("Server response: " + response);
}

[Link]();
[Link]();
[Link]();
[Link]();
} catch (IOException e) {
[Link]();
}
}
}

OUTPUT:
Server Terminal:

Server started. Waiting for client connection...


Client connected!
Client says: Hello Server
Client says: How are you?
Client says: exit
Client disconnected.
Server closed.

Client Terminal:

Connected to the server.


Enter message (type 'exit' to quit): Hello Server
Server response: Server received: Hello Server
Enter message (type 'exit' to quit): How are you?
Server response: Server received: How are you?
Enter message (type 'exit' to quit): exit
Disconnected from server.

Common questions

Powered by AI

Java's multithreading model allows concurrent execution of two or more threads for optimizing the use of CPU resources, facilitating the performance of complex applications by dividing operations into smaller segments that can run parallelly. Java supports multithreading via the Thread class, allowing programmers to either extend the Thread class or implement the Runnable interface. Each thread runs in its own call stack but can share resources with other threads within the same process, promoting synchronized resource access through mechanisms like wait(), notify(), and synchronized blocks. This ensures that only one thread accesses shared resources, maintaining consistency and preventing concurrency issues such as race conditions. Threads can independently pause (using sleep()) or respond to interrupts, helping in cooperative multitasking scenarios .

HashMaps and TreeMaps serve different purposes within Java's collection framework. HashMaps provide an unordered collection of key-value pairs, offering constant-time performance (O(1)) for insertions, deletions, and lookups when the load factor is maintained. They are ideal for scenarios where fast access time is prioritized and order is irrelevant. TreeMaps, on the other hand, maintain sorted order based on keys, automatically implementing the Comparable interface or comparator provided. This results in O(log n) performance for basic operations due to their tree structure. They are best suited for applications requiring iteration in sorted key order. Both structures enable efficient access and management of data, with TreeMaps being useful where natural ordering or explicit ordering of keys is required .

String immutability in Java means that once a String object is created, its content cannot be changed. This impacts performance and manipulation in several ways. Immutable strings increase security and simplicity, enabling string pooling—thereby saving memory by ensuring only a single instance of identical strings is stored. However, this can also introduce performance overhead when performing intensive string manipulations, as each change generates a new string rather than altering the existing memory content. This requirement for new allocations can be offset by using mutable alternatives like StringBuilder or StringBuffer for cases involving repeated or complex concatenations, which avoid the creation of unnecessary new objects and hence optimize performance .

Constructor chaining in Java is the process whereby a constructor calls another constructor in the same class or its superclass. In the provided example, the class 'Person' uses a default constructor to call its parameterized constructor with 'this("Unknown", 0);'. In the 'Employee' class, the default constructor calls another constructor in the same class using 'this("Not Assigned", 0.0);', which then calls the parent 'Person' class's constructor with 'super("John Doe", 30);'. This enables the reuse of code between constructors and ensures that the object is initialized consistently, adhering to inheritance principles .

Aggregation and composition are both forms of association used to depict relationships between classes. In aggregation, the relationship is loose, meaning that the lifetime of the dependent object (e.g., Employee in a Department) is independent of the lifecycle of the source object (Department). Hence, Employees can exist even if the Department is deleted. On the other hand, composition describes a strong relationship where the child object (e.g., Engine) cannot exist independently of the parent object (Car). If the Car object is destroyed, the associated Engine object is also destroyed, illustrating a whole-part relationship .

Polymorphism in Java is primarily driven through method overriding and interfaces. Method overriding permits subclasses to provide specific implementations of methods that are already defined in their superclasses, thus allowing objects to be treated as instances of their superclass with the flexibility of invoking subclass methods. This is integral to runtime polymorphism, where the decision about which method to invoke is made at runtime. Interfaces, by defining contracts that multiple classes can implement, further endorse polymorphism. Classes implementing an interface can be substituted for the interface type, allowing the same interface to perform different functionality based on the implementing class’s behavior. This approach leads to greater flexibility and scalability in code development and design .

Effective exception handling should involve catching exceptions at appropriate levels, using try-catch blocks to ensure the smooth continuation or graceful shutdown of applications in unexpected circumstances. Logging should be comprehensive, capturing enough context to debug efficiently while avoiding excessive verbosity. Loggers must be configured to capture different levels of information (e.g., INFO, SEVERE) and safely manage resources such as file handlers. Utilizing Java's Logging API, programmers can log the precise state and error details (e.g., 'Division by zero attempted') to assist in diagnosing failures. Consideration of both expected exceptions, such as divide by zero, and unexpected ones, ensures robustness, while the use of finally blocks to close resources like Scanners is critical for resource management .

In Java, method overriding occurs when a subclass provides a specific implementation for a method that is already defined by its superclass. This is evident in instance methods, where runtime polymorphism is achieved. For instance, in the provided example, 'Child's' overridden instance method is called instead of 'Parent's' when invoking through a Parent reference but instantiated as a Child object. Method hiding, however, pertains to static methods where the method in the subclass is hidden rather than overridden. The method that is called is determined by the reference type used, not by the actual object type. Therefore, when static methods are invoked, the method in the Parent class is called, not the one in the Child class, unless the type is explicitly stated as Child .

User-defined functions in Java allow developers to encapsulate behavior for reuse and clarity. In the 'ArithmeticOperations' program, functions such as 'add', 'subtract', 'multiply', and 'divide' are defined to perform basic arithmetic operations. These functions take parameters (two doubles) and return the result of the computation. For example, in the 'divide' function, logic is added to handle division by zero by checking if 'b' is zero and returning an error message instead. These predefined methods are then invoked in the 'main' method upon obtaining user input, facilitating structured and reusable code .

In Java, using abstract classes and interfaces together enhances design flexibility and scalability. Interfaces define methods that must be implemented by any class claiming the interface, providing a structure for interaction without implementation details. Abstract classes provide partial implementations, including methods with bodies and instance variables, which reduce redundancy across related classes. When combined, a class can extend an abstract class and implement interfaces to gain a mix of preset behavior and specialized methods as per application requirements. For instance, an abstract class 'Employee' providing base functionalities and an interface 'Payable' defining contract methods synergize to allow classes like 'FullTimeEmployee' to implement specific payment calculations while maintaining standard information interfaces across employee types .

You might also like