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

java Lab. Experiments and Manual

The document is a lab manual for Java programming for MCA III Semester at Mewar University, detailing a series of experiments covering various Java concepts such as variable scope, classes, constructors, methods, inheritance, polymorphism, interfaces, exception handling, and multithreading. Each experiment includes objectives, class definitions, and example code to illustrate the concepts. The manual serves as a practical guide for students to learn and implement Java programming techniques.

Uploaded by

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

java Lab. Experiments and Manual

The document is a lab manual for Java programming for MCA III Semester at Mewar University, detailing a series of experiments covering various Java concepts such as variable scope, classes, constructors, methods, inheritance, polymorphism, interfaces, exception handling, and multithreading. Each experiment includes objectives, class definitions, and example code to illustrate the concepts. The manual serves as a practical guide for students to learn and implement Java programming techniques.

Uploaded by

mudita.sf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Lab Manual

Java Programming
MCA III Semester

Department of Computer Applications


Faculty of Computer Science and System Studies
Mewar University
Chittorgarh, Rajasthan 312901
Lab Manual: Java Programming

List of Experiments

S.no Experiments. Page


no.
1. Scope of variables and its types. 3
2. Concept of CLASS and understanding object creation. 4-5
3. Concept of Constructors and Construct Overloading. 6-7
4. Concept of Methods and Method Overloading. 8-9
5. Concept of Inheritance and use of SUPER keyword. 10-11
6. Concept of polymorphism and method overriding 12-13
7. Concept of interfaces and achieving multiple inheritance. 14-15
8. Implementation of exception handling and showcase the use 16
of the finally block.
9. Illustrate the concept of multithreading, showcasing the 17-18
concurrent execution of multiple threads.
10. Demonstrate the use of String and various string 19-20
manipulation techniques.
11. Concept of packages, 21
12. Explore Input/output (I/O) operations, including the basics 22-23
of streams and illustrate fundamental concepts related to
handling input and output in Java.
13. Demonstrate inter-thread communication using the wait(), 24-26
notify(), and notifyAll() methods.
14. Demonstrate the Delegation Event Model, focusing on 27
event classes and how they are used for handling user
interactions.
15. Create a basic Task Management System where users can 28-30
add tasks, view tasks, and mark tasks as completed.

2|Page
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-1
Objective: Write a program to demonstrate the scope of variables, emphasizing
the three types: local variable, instance variable, and static variable.

// Step 1: Create a class ScopeDemo


class ScopeDemo {

// Step 2: Declare instance variable and initialize it


int instanceVariable = 10;

// Step 3: Declare static variable and initialize it


static int staticVariable = 20;

// Step 4: Declare a local variable within a method


void demonstrateScope() {
int localVariable = 30;

// Step 5: Print all the variables' values


System.out.println("Instance Variable: " + instanceVariable);
System.out.println("Static Variable: " + staticVariable);
System.out.println("Local Variable: " + localVariable);
}

// Step 6: Create the main method


public static void main(String[] args) {
// Create an instance of class ScopeDemo
ScopeDemo scopeDemoObject = new ScopeDemo();

// Call the method to demonstrate scope


scopeDemoObject.demonstrateScope();
}
}

Output:
Instance Variable: 10
Static Variable: 20
Local Variable: 30

3|Page
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-2
Objective: Write a program to Demonstrate the Concept of CLASS in JAVA and
how can we create an object of the class.

// Step 1: Create a class named Student


class Student {
// Step 2: Declare class attributes
String name;
int rollNumber;
double marks;

// Step 3: Create a method to display student details


void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
}
}

// Step 4: Create the main class to demonstrate class and object creation
public class Main {
public static void main(String[] args) {
// Step 5: Create an object of the Student class
Student student1 = new Student();

// Step 6: Set values for the attributes of student1


student1.name = "John Doe";
student1.rollNumber = 101;
student1.marks = 95.5;

// Step 7: Display details of student1


System.out.println("Details of Student 1:");
student1.displayDetails();

// Step 8: Create another object of the Student class


Student student2 = new Student();

// Step 9: Set values for the attributes of student2


student2.name = "Jane Doe";
student2.rollNumber = 102;
student2.marks = 89.0;
4|Page
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

// Step 10: Display details of student2


System.out.println("\nDetails of Student 2:");
student2.displayDetails();
}
}

Output:

Details of Student 1:
Name: John Doe
Roll Number: 101
Marks: 95.5

Details of Student 2:
Name: Jane Doe
Roll Number: 102
Marks: 89.0

5|Page
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-3
Objective: Write a Java program to demonstrate the concept of constructors and
constructor overloading.
// Step 1: Create a class named Book
class Book {
// Step 2: Declare class attributes
String title;
String author;
int pageCount;

// Step 3: Create a default constructor


Book() {
title = "Default Title";
author = "Default Author";
pageCount = 0;
}

// Step 4: Create a parameterized constructor


Book(String title, String author, int pageCount) {
this.title = title;
this.author = author;
this.pageCount = pageCount;
}

// Step 5: Create a method to display book details


void displayDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Page Count: " + pageCount);
}
}

// Step 6: Create the main class to demonstrate constructors and overloading


public class Main {
public static void main(String[] args) {
// Step 7: Create objects using different constructors
Book defaultBook = new Book(); // Default constructor
Book parameterizedBook = new Book("Java Programming", "John Smith", 300); //
Parameterized constructor

// Step 8: Display details of books


6|Page
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

System.out.println("Details of Default Book:");


defaultBook.displayDetails();

System.out.println("\nDetails of Parameterized Book:");


parameterizedBook.displayDetails();
}
}

Output:

Details of Default Book:


Title: Default Title
Author: Default Author
Page Count: 0

Details of Parameterized Book:


Title: Java Programming
Author: John Smith
Page Count: 300

7|Page
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-4
Objective: Write a Java program to demonstrate the concept of methods and
method overloading.

// Step 1: Create a class named Calculator


class Calculator {
// Step 2: Create a method to add two integers
int add(int num1, int num2) {
return num1 + num2;
}

// Step 3: Overload the add method to handle doubles


double add(double num1, double num2) {
return num1 + num2;
}

// Step 4: Overload the add method to handle three integers


int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
}

// Step 5: Create a method to multiply two integers


int multiply(int num1, int num2) {
return num1 * num2;
}

// Step 6: Overload the multiply method to handle doubles


double multiply(double num1, double num2) {
return num1 * num2;
}
}

// Step 7: Create the main class to demonstrate methods and overloading


public class Main {
public static void main(String[] args) {
// Step 8: Create an object of the Calculator class
Calculator calculator = new Calculator();

// Step 9: Call methods with different parameter types


System.out.println("Addition of two integers: " + calculator.add(5, 10));
System.out.println("Addition of two doubles: " + calculator.add(3.5, 2.5));
8|Page
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

System.out.println("Addition of three integers: " + calculator.add(2, 4, 6));


System.out.println("Multiplication of two integers: " + calculator.multiply(4, 7));
System.out.println("Multiplication of two doubles: " + calculator.multiply(2.5, 3.5));
}
}

Output:

Addition of two integers: 15


Addition of two doubles: 6.0
Addition of three integers: 12
Multiplication of two integers: 28
Multiplication of two doubles: 8.75

9|Page
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment No. 5
Objective: Write a Java program to demonstrate the concept of inheritance and
the use of the super keyword.
// Step 1: Create a superclass named Vehicle
class Vehicle {
// Step 2: Declare superclass attributes
String brand;
int year;

// Step 3: Create a superclass constructor


Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
}

// Step 4: Create a method in the superclass


void displayDetails() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}

// Step 5: Create a subclass named Car that extends Vehicle


class Car extends Vehicle {
// Step 6: Declare subclass attributes
String model;

// Step 7: Create a subclass constructor using the super keyword


Car(String brand, int year, String model) {
super(brand, year); // Call the constructor of the superclass
this.model = model;
}

// Step 8: Override the displayDetails method in the subclass


@Override
void displayDetails() {
super.displayDetails(); // Call the displayDetails method of the superclass
System.out.println("Model: " + model);
}
}

10 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

// Step 9: Create the main class to demonstrate inheritance and super keyword
public class Main {
public static void main(String[] args) {
// Step 10: Create an object of the Car class
Car myCar = new Car("Toyota", 2022, "Camry");

// Step 11: Call the displayDetails method of the Car class


myCar.displayDetails();
}
}
Output:
Brand: Toyota
Year: 2022
Model: Camry

11 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-6
Objective: Write a Java program to demonstrate the concept of polymorphism
and method overriding.

// Step 1: Create a superclass named Shape


class Shape {
// Step 2: Create a method in the superclass
void draw() {
System.out.println("Drawing a generic shape");
}
}

// Step 3: Create a subclass named Circle that extends Shape


class Circle extends Shape {
// Step 4: Override the draw method in the subclass
@Override
void draw() {
System.out.println("Drawing a circle");
}
}

// Step 5: Create another subclass named Square that extends Shape


class Square extends Shape {
// Step 6: Override the draw method in the subclass
@Override
void draw() {
System.out.println("Drawing a square");
}
}

// Step 7: Create the main class to demonstrate polymorphism and method overriding
public class Main {
public static void main(String[] args) {
// Step 8: Create an array of Shape objects
Shape[] shapes = new Shape[3];
shapes[0] = new Circle();
shapes[1] = new Square();
shapes[2] = new Shape(); // Creating an object of the superclass

// Step 9: Call the draw method on each object in the array


for (Shape shape : shapes) {
12 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

shape.draw(); // Polymorphic method invocation


}
}
}

Output:
Drawing a circle
Drawing a square
Drawing a generic shape
.

13 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-7
Objective: Write a Java program to demonstrate the concept of interfaces and
achieving multiple inheritance.
// Step 1: Create a Drawable interface
interface Drawable {
// Step 2: Declare an abstract draw method
void draw();
}

// Step 3: Create a Resizable interface


interface Resizable {
// Step 4: Declare an abstract resize method
void resize(int percentage);
}

// Step 5: Create a class named Shape implementing Drawable and Resizable


class Shape implements Drawable, Resizable {
// Step 6: Implement the draw method from the Drawable interface
@Override
public void draw() {
System.out.println("Drawing a shape");
}

// Step 7: Implement the resize method from the Resizable interface


@Override
public void resize(int percentage) {
System.out.println("Resizing the shape by " + percentage + "%");
}
}

// Step 8: Create the main class to demonstrate multiple inheritance through interfaces
public class Main {
public static void main(String[] args) {
// Step 9: Create an object of the Shape class
Shape myShape = new Shape();

// Step 10: Call methods from both interfaces


myShape.draw();
myShape.resize(50);
}
}
14 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Output:
Drawing a shape
Resizing the shape by 50%

15 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-8
Objective: Write a Java program to demonstrate the implementation of
exception handling and showcase the use of the finally block.

import java.util.Scanner;
public class ExceptionHandlingDemo {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();

System.out.print("Enter the denominator: ");


int denominator = scanner.nextInt();

int result = performDivision(numerator, denominator);


System.out.println("Result of division: " + result);

} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
System.out.println("Finally block executed - closing resources.");
scanner.close();
}
}
private static int performDivision(int numerator, int denominator) {
if (denominator == 0) {
throw new ArithmeticException("Denominator cannot be zero.");
}
return numerator / denominator;
}
}
Sample Output:
Enter the numerator: 10
Enter the denominator: 0
Error: Cannot divide by zero.
Finally block executed - closing resources.
16 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-9
Objective: Develop a Java program to illustrate the concept of multithreading,
showcasing the concurrent execution of multiple threads.

class Task implements Runnable {


private String taskName;

public Task(String name) {


this.taskName = name;
}

@Override
public void run() {
synchronized (this) {
for (int i = 1; i <= 5; i++) {
System.out.println("Executing Task " + taskName + ": Step " + i);
try {
Thread.sleep(500); // Simulate some work being done
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

public class MultithreadingDemo {


public static void main(String[] args) {
// Create two threads representing distinct tasks
Thread thread1 = new Thread(new Task("A"));
Thread thread2 = new Thread(new Task("B"));

// Start the threads concurrently


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

try {
// Use join to ensure sequential execution after both threads complete
thread1.join();
thread2.join();
} catch (InterruptedException e) {
17 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

e.printStackTrace();
}

// Print a message indicating the end of program execution


System.out.println("Multithreading Demo completed.");
}
Output:
Executing Task A: Step 1
Executing Task B: Step 1
Executing Task A: Step 2
Executing Task B: Step 2
Executing Task A: Step 3
Executing Task B: Step 3
Executing Task A: Step 4
Executing Task B: Step 4
Executing Task A: Step 5
Executing Task B: Step 5
Multithreading Demo completed.

18 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-10
Objective: Create a Java program to demonstrate the use of String and various
string manipulation techniques. The objective is to illustrate common operations
on strings, including concatenation, substring extraction, length determination,
and the use of string methods for manipulation and analysis.

public class StringManipulationDemo {


public static void main(String[] args) {
// String Creation
String str1 = "Hello, ";
String str2 = new String("World!");

// Concatenation
String resultConcatenation = str1 + str2;
String resultConcatMethod = str1.concat(str2);

System.out.println("Concatenation using + operator: " + resultConcatenation);


System.out.println("Concatenation using concat method: " + resultConcatMethod);

// Substring Extraction
String substring = resultConcatenation.substring(7, 12);
System.out.println("Substring Extraction: " + substring);

// String Length
int length = resultConcatenation.length();
System.out.println("String Length: " + length);

// String Methods
System.out.println("Uppercase: " + resultConcatenation.toUpperCase());
System.out.println("Lowercase: " + resultConcatenation.toLowerCase());
System.out.println("Character at index 4: " + resultConcatenation.charAt(4));
System.out.println("Index of 'o': " + resultConcatenation.indexOf('o'));
System.out.println("Replace 'Hello' with 'Greetings': " + resultConcatenation.replace("Hello",
"Greetings"));
System.out.println("Trim leading and trailing spaces: " + " Trim ".trim());
}
}
Output:
Concatenation using + operator: Hello, World!
Concatenation using concat method: Hello, World!
Substring Extraction: World
19 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

String Length: 13
Uppercase: HELLO, WORLD!
Lowercase: hello, world!
Character at index 4: o
Index of 'o': 4
Replace 'Hello' with 'Greetings': Greetings, World!
Trim leading and trailing spaces: Trim

20 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-11
Objective: Create a Java program to demonstrate the concept of packages,
showcasing how to organize and manage classes within a package structure. The
objective is to illustrate the benefits of using packages for modularizing code,
preventing naming conflicts, and enhancing code maintainability.

// File: MathOperations.java
package com.example;

public class MathOperations {


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

public static int subtract(int a, int b) {


return a - b;
}
}
// File: MainApp.java
import com.example.MathOperations;

public class MainApp {


public static void main(String[] args) {
// Using classes from the com.example package
int resultAdd = MathOperations.add(10, 5);
int resultSubtract = MathOperations.subtract(15, 7);

System.out.println("Addition result: " + resultAdd);


System.out.println("Subtraction result: " + resultSubtract);
}
}
Output:
Addition result: 15
Subtraction result: 8

21 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-12
Objective: Develop a Java program to explore Input/Output (I/O) operations,
including the basics of streams, byte and character streams, and the usage of
predefined streams. The objective is to illustrate fundamental concepts related to
handling input and output in Java.

import java.io.*;
public class IOOperationsDemo {
public static void main(String[] args) {
// Standard Input using System.in
System.out.print("Enter a line of text: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

try {
String userInput = reader.readLine();
System.out.println("You entered: " + userInput);
} catch (IOException e) {
e.printStackTrace();
}

// Byte Streams - Reading and Writing Binary Data


try {
FileInputStream inputFile = new FileInputStream("input.txt");
FileOutputStream outputFile = new FileOutputStream("output.txt");

int data;
while ((data = inputFile.read()) != -1) {
outputFile.write(data);
}

inputFile.close();
outputFile.close();
} catch (IOException e) {
e.printStackTrace();
}

// Character Streams - Reading and Writing Text Data


try {
FileReader fileReader = new FileReader("input.txt");
FileWriter fileWriter = new FileWriter("output.txt");

22 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

int charData;
while ((charData = fileReader.read()) != -1) {
fileWriter.write(charData);
}

fileReader.close();
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Enter a line of text: Hello, I/O Operations!
You entered: Hello, I/O Operations!

23 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-13
Objective: Create a Java program to demonstrate inter-thread communication
using the wait(), notify(), and notifyAll() methods..
class Message {
private String content;

public Message(String content) {


this.content = content;
}

public String getContent() {


return content;
}

public void setContent(String content) {


this.content = content;
}
}

class Producer implements Runnable {


private final Message message;

public Producer(Message message) {


this.message = message;
}

@Override
public void run() {
synchronized (message) {
for (int i = 1; i <= 5; i++) {
String newContent = "Message " + i;
message.setContent(newContent);
System.out.println("Produced: " + newContent);

try {
Thread.sleep(1000); // Simulate some work being done
message.notify(); // Notify the consumer thread
message.wait(); // Release the lock and wait for the consumer to consume
} catch (InterruptedException e) {
e.printStackTrace();
}
24 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

}
}
}
}

class Consumer implements Runnable {


private final Message message;

public Consumer(Message message) {


this.message = message;
}

@Override
public void run() {
synchronized (message) {
for (int i = 1; i <= 5; i++) {
try {
message.wait(); // Wait for the producer to produce
System.out.println("Consumed: " + message.getContent());
Thread.sleep(1000); // Simulate some work being done
message.notify(); // Notify the producer thread
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

public class InterThreadCommunicationDemo {


public static void main(String[] args) {
Message sharedMessage = new Message("");

Thread producerThread = new Thread(new Producer(sharedMessage));


Thread consumerThread = new Thread(new Consumer(sharedMessage));

producerThread.start();
consumerThread.start();
}
}
Output:
Produced: Message 1
25 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Consumed: Message 1
Produced: Message 2
Consumed: Message 2
Produced: Message 3
Consumed: Message 3
Produced: Message 4
Consumed: Message 4
Produced: Message 5
Consumed: Message 5

26 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-14
Objective: Develop a Java program to demonstrate the Delegation Event Model,
focusing on event classes and how they are used for handling user interactions.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DelegationEventModelDemo {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("Delegation Event Model Demo");

// Create a JButton
JButton button = new JButton("Click Me");

// Create an ActionListener to handle button click events


ActionListener buttonClickListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "Button Clicked!");
}
};

// Register the ActionListener with the JButton


button.addActionListener(buttonClickListener);

// Set up the JFrame


frame.setLayout(new FlowLayout());
frame.add(button);
frame.setSize(300, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center the frame on the screen
frame.setVisible(true);
}
}
Output:
A JFrame with a button labeled "Click Me" is displayed. When the button is clicked, a JOptionPane
dialog appears with the message "Button Clicked!"

27 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

Experiment-15
Objective: Create a basic Task Management System where users can add tasks,
view tasks, and mark tasks as completed.
public class Task {
private String description;
private boolean completed;

public Task(String description) {


this.description = description;
this.completed = false;
}

public String getDescription() {


return description;
}

public boolean isCompleted() {


return completed;
}

public void markAsCompleted() {


this.completed = true;
}

@Override
public String toString() {
return "Task: " + description + " | Completed: " + completed;
}
}

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class TaskManager {


private List<Task> tasks;

public TaskManager() {
this.tasks = new ArrayList<>();
}
28 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

public void addTask(String description) {


Task newTask = new Task(description);
tasks.add(newTask);
System.out.println("Task added successfully: " + newTask.getDescription());
}

public void viewTasks() {


if (tasks.isEmpty()) {
System.out.println("No tasks available.");
} else {
System.out.println("Tasks:");
for (Task task : tasks) {
System.out.println(task);
}
}
}

public void markTaskAsCompleted(int index) {


if (index >= 0 && index < tasks.size()) {
Task task = tasks.get(index);
task.markAsCompleted();
System.out.println("Task marked as completed: " + task.getDescription());
} else {
System.out.println("Invalid task index.");
}
}

public static void main(String[] args) {


TaskManager taskManager = new TaskManager();
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("\nTask Management System");
System.out.println("1. Add Task");
System.out.println("2. View Tasks");
System.out.println("3. Mark Task as Completed");
System.out.println("4. Exit");
System.out.print("Choose an option (1-4): ");

int choice = scanner.nextInt();

29 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901
Lab Manual: Java Programming

switch (choice) {
case 1:
System.out.print("Enter task description: ");
scanner.nextLine(); // Consume the newline character
String description = scanner.nextLine();
taskManager.addTask(description);
break;
case 2:
taskManager.viewTasks();
break;
case 3:
System.out.print("Enter the index of the task to mark as completed: ");
int index = scanner.nextInt();
taskManager.markTaskAsCompleted(index);
break;
case 4:
System.out.println("Exiting Task Management System. Goodbye!");
scanner.close();
System.exit(0);
default:
System.out.println("Invalid choice. Please choose a valid option.");
}
}
}
}

30 | P a g e
Department of Computer Applications,
Mewar University, NH-48, Gangrar, Chittorgarh (Rajasthan) 312901

You might also like