0% found this document useful (0 votes)
2 views47 pages

Java Programming Lab Manual

The document is a Java Programming Lab Manual that outlines various experiments and exercises related to Java programming concepts, including control statements, string manipulation, class creation, constructors, command line arguments, method overloading, inheritance, exception handling, multithreading, and applet programming. Each experiment includes an aim, description, and example program code. The manual serves as a comprehensive guide for students to practice and understand fundamental Java programming techniques.

Uploaded by

naveenroyals71
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)
2 views47 pages

Java Programming Lab Manual

The document is a Java Programming Lab Manual that outlines various experiments and exercises related to Java programming concepts, including control statements, string manipulation, class creation, constructors, command line arguments, method overloading, inheritance, exception handling, multithreading, and applet programming. Each experiment includes an aim, description, and example program code. The manual serves as a comprehensive guide for students to practice and understand fundamental Java programming techniques.

Uploaded by

naveenroyals71
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

JAVA PROGRAMMING LAB MANUAL

INDEX PAGE

[Link] List of experiments Page no


(a) write a program using IF and Switch statements.
1
(b) write a program using WHILE, DO-WHILE, FOR looping statements.
(a) write a program to manipulate strings.
2
(b) write a program to arrange array of strings in ascending order.
(a) write a program to create a class & objects.
3
(b) write a program to create class adding methods and access the class members.
(a) write a program using default constructor.
4
(b) write a program using parameterised constructor.
(a) write a program to illustrate usage of command line arguments.
5
(b) write a program using to read data as command line arguments and update into files.
(a) write a program to illustrate method overloading.
6
(b) write a program to illustrate method overloading using constructors.
(a) write a program to illustrate single inheritance.
7
(b) write a program to illustrate multiple inheritance.
8 write a program using the concept of method overriding.
9 write a program to create and importing packages.
10 write a program illustrate multiple inheritance using interfaces.
(a) write a program to give values to variables interactively through keyboard.
11 (b) write a program to read and write the primitive data types.
(c) write a program to handle files.
(a) write a program to search a student mark percentage based on pin number using array
list.
12
(b) write a program to create a linked list to perform using delete, insert, & update in
linked list with any application.
(a) write a program to illustrate exception handling.
13 (b) write a program to illustrate exception handling using multiple catch statements.
(c) write a program to illustrate exception handling using nested try.
(a) write a program to create single thread extending the thread class.
(b) write a program to create single thread using by implementing the runnable interface.
14
(c) write a program to create multiple threads.
(d) write a program to illustrate thread priorities.
(a) write a program to create simple applet to display different shapes with colours.
15
(b) write a applet program to design simple animation.
(a) write an applet program to handle key events.
(b) write an applet program to handle mouse events.
16 (c) write an applet program to handle text field and button control.
(d) write an applet program to handle check box & list control.
(e) write an applet program to handle multiple controls.
EXPTNO 1(a):
AIM: To check whether a number is positive, negative, or zero using if, else if, and else.

Description:

Program:
import [Link];

public class Number Check {


public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter a number: ");
int num = input. nextInt();

if (num > 0) {
[Link]("The number is positive.");
} else if (num < 0) {
[Link]("The number is negative.");
} else {
[Link]("The number is zero.");
}
}
}

Output:
EXPTNO 1(b):
AIM: To display the day of the week based on user input (1 to 7) using switch.
Description:

Program:
import [Link];
public class DayOfWeek {
public static void main(String[] args) {
Scanner input = new Scanner([Link]);
[Link]("Enter day number (1-7): ");
int day = [Link]();
switch (day) {
case 1: [Link]("Sunday"); break;
case 2: [Link]("Monday"); break;
case 3: [Link]("Tuesday"); break;
case 4: [Link]("Wednesday"); break;
case 5: [Link]("Thursday"); break;
case 6: [Link]("Friday"); break;
case 7: [Link]("Saturday"); break;
default: [Link]("Invalid day number!");
}
}
}

Output:
EXPT 2(a):
Aim: To perform basic string operations such as length, uppercase conversion, concatenation, and character
access.
Description:

Program:
public class StringManipulation {
public static void main(String[] args) {
String text = "Hello World” ;// Create a string
[Link]("Length: " + [Link]()); // 1. Length of the string
[Link]("Uppercase: " + [Link]() ;// 2. Convert to uppercase
[Link]("Lowercase: " + [Link]()) ;// 3. Convert to lowercase
[Link]("Substring (0-5): " + [Link](0, 5));
// 4. Substring (extract part of the string)
[Link]("Replace 'World' with 'Java': " + [Link]("World", "Java"));
// 5. Replace characters
// 6. Check if string contains a word
[Link]("Contains 'Hello'? " + [Link]("Hello"));
// 7. Concatenate strings
String newText = text + " - Welcome!";
[Link]("Concatenated: " + newText);
// 8. Trim spaces
String spaced = " Java Programming ";
[Link]("Trimmed: '" + [Link]() + "'");
}
}
Output:
EXPTNO2(b):
AIM: To sort an array of strings in ascending alphabetical order using Java.
Description:

Program:
import [Link];

public class SortStrings {


public static void main(String[] args) {
// Create an array of strings
String[] names = {"Naveen", "Ravi", "Anita", "Kiran", "Bala"};
// Print original array
[Link]("Original array:");
for (String name : names) {
[Link](name);
}
// Sort the array in ascending order
[Link](names);
// Print sorted array
[Link]("\nSorted array (Ascending):");
for (String name : names) {
[Link](name);
}
}
}
Output:
EXPTNO3(a):
AIM: To create a class named Car and create objects to access its properties and methods.
Description:

Program:
// Define the class
class Car {
// Properties (fields)
String brand;
int year;
// Method
void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Year: " + year);
}
}
// Main class to create objects
public class CarDemo {
public static void main(String[] args) {
// Create first object
Car car1 = new Car();
[Link] = "Toyota";
[Link] = 2020;
// Create second object
Car car2 = new Car();
[Link] = "Honda";
[Link] = 2022;
// Display info
[Link]("Car 1 Details:");
[Link]();
[Link]("\nCar 2 Details:");
[Link]();
}}
Output:
EXPTNO3(b):
AIM: To create a class Student with data members and methods, and access them using objects.
Description:

Program:
// Define the class
class Student {
// Data members (fields)
String name;
int age;
// Method to set student details
void setDetails(String studentName, int studentAge) {
name = studentName;
age = studentAge;
}
// Method to display student details
void displayDetails() {
[Link]("Student Name: " + name);
[Link]("Student Age: " + age);
}
}
// Main class to access members
public class StudentDemo {
public static void main(String[] args) {
// Create object of Student class
Student s1 = new Student();
// Call method to set details
[Link]("Name", 21);
// Call method to display details
[Link]();
}
}
Output:
EXPTNO 4(a):
AIM: To create a class with a default constructor and use it to initialize object values.
Description:

Program:
// Define the class
class Book {
String title;
String author;
// Default constructor
Book() {
title = "Unknown Title";
author = "Unknown Author";
}
// Method to display book details
void display() {
[Link]("Book Title: " + title);
[Link]("Book Author: " + author);
}
}
// Main class to test the default constructor
public class BookDemo {
public static void main(String[] args) {
// Create object using default constructor
Book b1 = new Book();
// Display default values
[Link]();
}
}
Output:
EXPTNO 4(b):
AIM: To create a class with a parameterized constructor and use it to initialize object values at the time of
object creation.
Description:

Program:
// Define the class
class Employee {
String name;
int id;
// Parameterized constructor
Employee(String empName, int empId) {
name = empName;
id = empId;
}
// Method to display employee details
void display() {
[Link]("Employee Name: " + name);
[Link]("Employee ID: " + id);
}
}
// Main class to test the constructor
public class EmployeeDemo {
public static void main(String[] args) {
// Create objects using parameterized constructor
Employee e1 = new Employee("Naveen", 101);
Employee e2 = new Employee("Priya", 102);
// Display employee details
[Link]();
[Link](); // line break
[Link]();
}
}
Output:
EXPTNO 5(a):
AIM: To illustrate the usage of command line arguments by accepting and displaying user input passed
during program execution.

Description:

Program:
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello world, my name is " + args[0] + "!");
}
}

Note:
Compile and run from command line:
javac [Link] compilingcode
java CommandLineDemo Nav

Output:
EXPTNO 5(b):
AIM: To read data from command line arguments and update (write) it into a file using Java.
Description:

Program:
import [Link];
import [Link];
public class WriteToFile {
public static void main(String[] args) {
// Check if arguments are provided
if ([Link] == 0) {
[Link]("No command line arguments provided.");
return;
}
try {
// Create or open file for writing
FileWriter writer = new FileWriter("[Link]");

// Write each argument to the file


for (String arg : args) {
[Link](arg + "\n");
}
[Link]();
[Link]("Data written to [Link] successfully.");
} catch (IOException e) {
[Link]("An error occurred while writing to the file.");
[Link]();
}
}
}
Output:
EXPTNO 6(a):
AIM: To write a Java program that demonstrates method overloading, where multiple methods share the
same name but differ in the number or type of parameters
Description:

Program:
public class OverloadExample {
// Method to display a message
void display() {
[Link]("No parameters");
}
// Overloaded method with one integer parameter
void display(int a) {
[Link]("Integer parameter: " + a);
}
// Overloaded method with two parameters
void display(String name, int age) {
[Link]("Name: " + name + ", Age: " + age);
}
// Overloaded method with different parameter types
void display(double value) {
[Link]("Double parameter: " + value);
}
public static void main(String[] args) {
OverloadExample obj = new OverloadExample();
[Link]();
[Link](10);
[Link]("Naveen", 25);
[Link](3.14);
}
}
Output:
EXPTNO 6(b):
AIM: To write a Java program that demonstrates constructor overloading, where multiple constructors are
defined with different parameter lists to initialize objects in various ways.
Description:

Program:
public class Student {
String name;
int age;
// Default constructor
Student() {
name = "Unknown";
age = 0;
}
// Constructor with one parameter
Student(String n) {
name = n;
age = 18; // default age
}
// Constructor with two parameters
Student(String n, int a) {
name = n;
age = a;
}
void display() {
[Link]("Name: " + name + ", Age: " + age);
}
public static void main(String[] args) {
Student s1 = new Student(); // uses default constructor
Student s2 = new Student("Naveen"); // uses constructor with one parameter
Student s3 = new Student("Rahul", 22); // uses constructor with two parameters

[Link]();
[Link]();
[Link]();
}
}

Output:
EXPTNO 7(a):
AIM: To write a Java program that demonstrates single inheritance, where a subclass inherits properties
and methods from a single superclass.
Description:

Program;
// Superclass
class Person {
String name;
int age;
void setDetails(String n, int a) {
name = n;
age = a;
}
void showDetails() {
[Link]("Name: " + name);
[Link]("Age: " + age);
}
}
// Subclass
class Employee extends Person {
int employeeId;
void setEmployeeId(int id) {
employeeId = id;
}
void showEmployeeInfo() {
showDetails(); // inherited method
[Link]("Employee ID: " + employeeId);
}
public static void main(String[] args) {
Employee emp = new Employee();
[Link]("Naveen", 25); // inherited from Person
[Link](101); // defined in Employee
[Link](); // displays all info
}
}

Output:
EXPTNO 7(b):
AIM: To write a Java program that demonstrates multiple inheritance using interfaces, where a class
inherits behaviour from more than one interface.
Description:

Program:
// First interface
interface Printable {
void print();
}
// Second interface
interface Showable {
void show();
}
// Class implementing both interfaces
class Document implements Printable, Showable {
public void print() {
[Link]("Printing document...");
}
public void show() {
[Link]("Showing document...");
}
public static void main(String[] args) {
Document doc = new Document();
[Link]();
[Link]();
}
}

Output:
EXPTNO 8:
AIM: To write a Java program that demonstrates method overriding, where a subclass provides a specific
implementation of a method already defined in its superclass
Description:

Program:
// Superclass
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
// Subclass
class Dog extends Animal {
// Overriding the sound() method
@Override
void sound() {
[Link]("Dog barks");
}
}
public class MethodOverrideDemo {
public static void main(String[] args) {
Animal a = new Animal(); // reference to Animal
Dog d = new Dog(); // reference to Dog
Animal ref = new Dog(); // upcasting
[Link](); // calls Animal's sound()
[Link](); // calls Dog's sound()
[Link](); // calls Dog's sound() due to dynamic dispatch
}
}

Output:
EXPTNO 9:
AIM: To write a Java program that demonstrates how to create a package and import it into another class
for use.
Description:

Program:
Creating packages with class message .java
// File: mypack/[Link]
package mypack;
public class Message {
public void show() {
[Link]("Hello from the package!");
}
}
Create another class [Link] to import and use the package
// File: [Link]
import [Link];
public class TestPackage {
public static void main(String[] args) {
Message msg = new Message();
[Link]();
}
}

Output:
EXPTNO 10:
AIM: To write a Java program that demonstrates multiple inheritance using interfaces, where a class
inherits behavior from more than one interface.
Description:

Program:
// First interface
interface Flyable {
void fly();
}
// Second interface
interface Swimmable {
void swim();
}
// Class implementing both interfaces
class Duck implements Flyable, Swimmable {
public void fly() {
[Link]("Duck flies in the sky.");
}
public void swim() {
[Link]("Duck swims in the pond.");
}
public static void main(String[] args) {
Duck d = new Duck();
[Link]();
[Link]();
}
}

Output:
11 a)
AIM: To write a program to give values to variables interactively through keyboard.

Description:

Program:
import [Link];

public class InteractiveInput {


public static void main(String[] args) {
// Create Scanner object to read input from keyboard
Scanner sc = new Scanner([Link]);
// Read an integer
[Link]("Enter an integer: ");
int number = [Link]();
// Read a double
[Link]("Enter a decimal number: ");
double decimal = [Link]();
// Read a string (single word)
[Link]("Enter a word: ");
String word = [Link]();
// Read a full line of text
[Link](); // consume leftover newline
[Link]("Enter a sentence: ");
String sentence = [Link]();
// Display the values entered
[Link]("\nYou entered:");
[Link]("Integer: " + number);
[Link]("Decimal: " + decimal);
[Link]("Word: " + word);
[Link]("Sentence: " + sentence);
[Link]();
}
}
OUTPUT:

Result:

11b)
Aim: To write a write an program to read and write the primitive data types.
Description:

Program:
import [Link];

public class PrimitiveDataTypes {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Read different primitive types


[Link]("Enter an integer: ");
int intVal = [Link]();

[Link]("Enter a float: ");


float floatVal = [Link]();

[Link]("Enter a double: ");


double doubleVal = [Link]();

[Link]("Enter a long: ");


long longVal = [Link]();
[Link]("Enter a short: ");
short shortVal = [Link]();

[Link]("Enter a byte: ");


byte byteVal = [Link]();

[Link]("Enter a boolean (true/false): ");


boolean boolVal = [Link]();

[Link](); // consume newline


[Link]("Enter a character: ");
char charVal = [Link]().charAt(0);

// Display values back


[Link]("\nYou entered:");
[Link]("Integer: " + intVal);
[Link]("Float: " + floatVal);
[Link]("Double: " + doubleVal);
[Link]("Long: " + longVal);
[Link]("Short: " + shortVal);
[Link]("Byte: " + byteVal);
[Link]("Boolean: " + boolVal);
[Link]("Character: " + charVal);

[Link]();
}
}

Output:
11c)
Aim: to write a java write a program to handle files.
Description;

Program;
import [Link];
import [Link];
import [Link];
import [Link];

public class FileHandling {


public static void main(String[] args) {
try {
// 1. Create a file
File file = new File("[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}

// 2. Write to the file


FileWriter writer = new FileWriter("[Link]");
[Link]("Hello Naveen!\nThis is a simple file handling example.");
[Link]();
[Link]("Successfully wrote to the file.");

// 3. Read from the file


FileReader reader = new FileReader("[Link]");
int ch;
[Link]("\nFile contents:");
while ((ch = [Link]()) != -1) {
[Link]((char) ch);
}
[Link]();

} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}
}

Output:

Result:

12a)
Aim: To write a program to search a student mark percentage based on pin number using array list.
Description:

Program:
import [Link];
import [Link];

class Student {
int pin;
double percentage;

Student(int pin, double percentage) {


[Link] = pin;
[Link] = percentage;
}
}

public class StudentSearch {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Create an ArrayList to store students


ArrayList<Student> students = new ArrayList<>();

// Add some sample students


[Link](new Student(101, 85.5));
[Link](new Student(102, 90.0));
[Link](new Student(103, 76.2));
[Link](new Student(104, 88.8));

// Ask user for pin number to search


[Link]("Enter student pin number to search: ");
int searchPin = [Link]();

// Search in ArrayList
boolean found = false;
for (Student s : students) {
if ([Link] == searchPin) {
[Link]("Student with pin " + searchPin +
" has percentage: " + [Link] + "%");
found = true;
break;
}
}

if (!found) {
[Link]("Student with pin " + searchPin + " not found.");
}

[Link]();
}
}

Output:

Result:

12b)
Aim: write a program to create a linked list to perform using delete, insert, & update in linked list with any
application.
Description:

Program:
import [Link];
import [Link];

public class LinkedListExample {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Create a LinkedList of student names


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

// Insert some students


[Link]("Naveen");
[Link]("Ravi");
[Link]("Anita");
[Link]("Kiran");

[Link]("Initial list: " + students);

// Insert a new student at a specific position


[Link]("Enter a new student name to insert: ");
String newStudent = [Link]();
[Link](2, newStudent); // insert at index 2
[Link]("After insertion: " + students);

// Update a student name


[Link]("Enter index to update (0-based): ");
int updateIndex = [Link]();
[Link](); // consume newline
[Link]("Enter new name: ");
String updatedName = [Link]();
[Link](updateIndex, updatedName);
[Link]("After update: " + students);

// Delete a student
[Link]("Enter index to delete (0-based): ");
int deleteIndex = [Link]();
[Link](deleteIndex);
[Link]("After deletion: " + students);

[Link]();
}
}

Output:
Initial list: [Naveen, Ravi, Anita, Kiran]
Enter a new student name to insert: Bala
After insertion: [Naveen, Ravi, Bala, Anita, Kiran]
Enter index to update (0-based): 1
Enter new name: Ramesh
After update: [Naveen, Ramesh, Bala, Anita, Kiran]

Enter index to delete (0-based): 3


After deletion: [Naveen, Ramesh, Bala, Kiran]

13a)
Aim: To write a java program to illustrate Exception Handling.
Description:
This program demonstrates how Java manages runtime errors through exception handling. The code
attempts to divide two integers, where one of them is zero. Since division by zero is not allowed, Java
throws an ArithmeticException. The try block contains the risky code, the catch block handles the specific
exception, and the finally block executes regardless of whether an exception occurs. This ensures the
program does not crash and provides meaningful feedback to the user.
Program:
// Program to illustrate Exception Handling in Java
public class ExceptionHandlingDemo {
public static void main(String[] args) {
try {
int a = 10;
int b = 0; // This will cause division by zero
int result = a / b;
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
catch (Exception e) {
[Link]("Unexpected error occurred: " + e);
}
finally {
[Link]("Execution completed.");
}
}
}

Output: Error: Division by zero is not allowed.


Execution completed.

13b)
Aim: To java a program to illustrate exception handling using multiple catch statements.
Description:

1. This program demonstrates the use of multiple catch blocks in Java.


2. When risky code is placed inside a try block, different exceptions may occur depending on the
type of error.
3. By using multiple catch statements, each specific exception can be handled individually,
providing meaningful feedback to the user.

Program:
// Program to illustrate Exception Handling using Multiple Catch Statements
public class MultipleCatchDemo {
public static void main(String[] args) {
try {
// Example 1: Division by zero
int a = 10;
int b = 0;
int result = a / b; // ArithmeticException

// Example 2: Invalid array index


int[] arr = {1, 2, 3};
[Link](arr[5]); // ArrayIndexOutOfBoundsException

// Example 3: Invalid number format


String str = "abc";
int num = [Link](str); // NumberFormatException

}
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index is out of bounds.");
}
catch (NumberFormatException e) {
[Link]("Error: Invalid number format.");
}
catch (Exception e) {
[Link]("Unexpected error occurred: " + e);
}
finally {
[Link]("Execution completed.");
}
}
}

Output:
Error: Division by zero is not allowed.
Execution completed.

Result:
13c)
Aim: To write a program to illustrate exception handling using nested try.
Description:
1. write a program to illustrate exception handling using nested try
2. A try block can contain another try block inside it.
3. This is useful when different parts of code may throw different exceptions, and you want to handle
them separately
4. The inner try block handles exceptions specific to its code segment.
5. Multiple catch blocks can be used to handle different types of exceptions.
6. The finally block ensures that cleanup or final statements are always executed.

Program:
// Program to illustrate Exception Handling using Nested Try Blocks
public class NestedTryDemo {
public static void main(String[] args) {
try {
// Outer try block
int[] arr = {10, 20, 30};

try {
// Inner try block
int result = arr[2] / 0; // Division by zero
[Link]("Result: " + result);
}
catch (ArithmeticException e) {
[Link]("Error: Division by zero is not allowed.");
}

// Accessing invalid index (handled by outer try)


[Link](arr[5]); // ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Array index is out of bounds.");
}
finally {
[Link]("Execution completed.");
}
}
}

Output:
Error: Division by zero is not allowed.
Error: Array index is out of bounds.
Execution completed.

Result:

14a)
Aim: To illustrate how to create and run a single thread in Java by extending the Thread class.
Description:
1. In Java, threads allow programs to perform multiple tasks concurrently
2. One way to create a thread is by extending the Thread class and overriding its run() method.
3. The run() method contains the code that will execute in the new thread.
4. The start() method is used to begin execution of the thread, which internally calls run().
5. This program demonstrates how a single thread can be created and executed

Program:
// Program to create a single thread by extending Thread class
class MyThread extends Thread {
// Override the run() method
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread is running... Count: " + i);
try {
[Link](500); // pause for 500ms
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
}
public static void main(String[] args) {
// Create an object of MyThread
MyThread t1 = new MyThread();
// Start the thread
[Link]();
[Link]("Main method execution completed.");
}
}

Output:
Main method execution completed.
Thread is running... Count: 1
Thread is running... Count: 2
Thread is running... Count: 3
Thread is running... Count: 4
Thread is running... Count: 5

Result:

14b)
Aim: To demonstrate how to create and run a single thread in Java by implementing the Runnable
interface.
Description:
When using Runnable, we define the thread’s task inside the run() method. Then, we pass the Runnable
object to a Thread object and call start() to begin execution. This approach is preferred when a class already
extends another class, since Java does not support multiple inheritance.

Program:
// Program to create a single thread by implementing Runnable interface
class MyRunnable implements Runnable {
// Override the run() method
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]("Thread is running... Count: " + i);
try {
[Link](500); // pause for 500ms
} catch (InterruptedException e) {
[Link]("Thread interrupted.");
}
}
}
}
public class SingleThreadRunnableDemo {
public static void main(String[] args) {
// Create a Runnable object
MyRunnable myTask = new MyRunnable();

// Pass Runnable to Thread object


Thread t1 = new Thread(myTask);
// Start the thread
[Link]();
[Link]("Main method execution completed.");
}
}

Output:
Main method execution completed.
Thread is running... Count: 1
Thread is running... Count: 2
Thread is running... Count: 3
Thread is running... Count: 4
Thread is running... Count: 5

Result:

14c)
Aim: To illustrate how to create and execute multiple threads in Java, showing concurrent execution of
tasks.
Description:
In Java, multiple threads can run simultaneously, allowing programs to perform tasks concurrently.
Each thread executes its own run() method independently.
• Threads can be created by extending the Thread class or implementing the Runnable interface.
• The start() method begins execution of each thread.
• The JVM scheduler decides the order of execution, so outputs may vary each time the program
runs.

Program:
// Program to create multiple threads by extending Thread class
class MyThread extends Thread {
private String threadName;

MyThread(String name) {
[Link] = name;
}
// Override run() method
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](threadName + " is running... Count: " + i);
try {
[Link](500); // pause for 500ms
} catch (InterruptedException e) {
[Link](threadName + " interrupted.");
}
}
[Link](threadName + " finished execution.");
}
}
public class MultipleThreadsDemo {
public static void main(String[] args) {
// Create multiple thread objects
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
MyThread t3 = new MyThread("Thread-3");

// Start threads
[Link]();
[Link]();
[Link]();

[Link]("Main method execution completed.");


}
}

Output:

Main method execution completed.


Thread-1 is running... Count: 1
Thread-2 is running... Count: 1
Thread-3 is running... Count: 1
Thread-1 is running... Count: 2
Thread-2 is running... Count: 2
Thread-3 is running... Count: 2
...
Thread-1 finished execution.
Thread-2 finished execution.
Thread-3 finished execution.

Result:

14d)
Aim: To illustrate how thread priorities in Java affect the execution order of multiple threads
Description:
In Java, each thread has a priority (an integer value between 1 and 10).
• The default priority is 5 (Thread.NORM_PRIORITY).
• Higher priority threads are given preference by the thread scheduler, but execution order is not
guaranteed (depends on JVM and OS).
• Priorities are set using setPriority(int value) method.
Program:
// Program to illustrate Thread Priorities in Java
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
public void run() {
for (int i = 1; i <= 3; i++) {
[Link](getName() + " is running... Count: " + i);
}
}
}
public class ThreadPriorityDemo {
public static void main(String[] args) {
// Create threads
MyThread t1 = new MyThread("Low Priority Thread");
MyThread t2 = new MyThread("Normal Priority Thread");
MyThread t3 = new MyThread("High Priority Thread");

// Set priorities
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5
[Link](Thread.MAX_PRIORITY); // 10

// Start threads
[Link]();
[Link]();
[Link]();

[Link]("Main method execution completed.");


}
}

Output:
Main method execution completed.
High Priority Thread is running... Count: 1
High Priority Thread is running... Count: 2
High Priority Thread is running... Count: 3
Normal Priority Thread is running... Count: 1
Normal Priority Thread is running... Count: 2
Normal Priority Thread is running... Count: 3
Low Priority Thread is running... Count: 1
Low Priority Thread is running... Count: 2
Low Priority Thread is running... Count: 3

Result:

15a)
Aim: To create a simple Java applet that displays different geometric shapes in various color.
Program:
public class ShapesSApplet extends Applet {

/* <applet code="ShapesApplet" width=400 height=400></applet> */

public void paint(Graphics g) {

// Draw a line

[Link](20, 20, 100, 20);

[Link]([Link]);

// Draw rectangle

[Link](50, 50, 100, 60);

[Link]([Link]);

[Link](50, 50, 100, 60);

// Draw oval

[Link](20, 100, 80, 40);

[Link]([Link]);

[Link](20, 100, 80, 40);

// Draw string

[Link]("Hello Applet!", 50, 180);


[Link]([Link]);

Output :

ShapesApplet

Hello Applet

Result:

15b)
Aim:
To design a simple animation using Java Applet.
Description:
This program demonstrates animation by moving a red ball horizontally across the applet window.
The ball changes direction when it reaches the boundary, creating a bouncing effect.

Program:
import [Link];
import [Link];
import [Link];
/* <applet code="SimpleAnimation" width=400 height=300></applet> */

public class SimpleAnimation extends Applet implements Runnable {


int x = 10; // x-coordinate of the ball
int y = 100; // y-coordinate of the ball
int dx = 5; // change in x (speed)
Thread t;
public void init() {
setBackground([Link]);
t = new Thread(this);
[Link]();
}
public void run() {
while (true) {
x += dx;
if (x > getWidth() - 50 || x < 0) {
dx = -dx; // reverse direction when hitting boundary
}
repaint();
try {
[Link](50); // delay for smooth animation
} catch (InterruptedException e) {
[Link]();
}
}
}
public void paint(Graphics g) {
[Link]([Link]);
[Link](x, y, 50, 50); // draw the ball
}
}
Output:

Result:

16a)
Aim: write an applet program to handle key events.
Description;
Key events are generated when the user interacts with the keyboard. These are handled using the
KeyListener interface from the [Link] package.

Program:
import [Link].*;
import [Link].*;
import [Link].*;
/* */
public class KeyEventApplet extends Applet implements KeyListener {
String msg = "";
int x = 20, y = 40; // coordinates for displaying text
public void init() {
addKeyListener(this);
setBackground([Link]);
}
// KeyListener methods
public void keyPressed(KeyEvent e) {
msg = "Key Pressed: " + [Link]([Link]());
repaint();
}
public void keyReleased(KeyEvent e) {
msg = "Key Released: " + [Link]([Link]());
repaint();
}
public void keyTyped(KeyEvent e) {
msg = "Key Typed: " + [Link]();
repaint();
}
// Display message
public void paint(Graphics g) {
[Link](msg, x, y);
}
}
Output:

Result:

16b)
Aim: write an applet program to handle mouse events
Description:
Mouse events are actions performed by using the mouse, such as clicking, pressing, releasing,
entering, dragging & moving. These events handled by using event listener & available in “[Link]. Event
package”.
Applets can handle the events by implementing following interfaces.
1. Mouse listener: -Handles click, press, release, enter, exit.
2. MouseMotionListener → Handles drag and move.

Program:
import [Link].*;
import [Link].*;
import [Link].*;
/* */
public class MouseApplet extends Applet implements MouseListener, MouseMotionListener {
String msg = "";
int mouseX = 0, mouseY = 0;
public void init() {
addMouseListener(this);
addMouseMotionListener(this);
setBackground([Link]);
}
// MouseListener methods
public void mouseClicked(MouseEvent e) {
msg = "Mouse Clicked";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mousePressed(MouseEvent e) {
msg = "Mouse Pressed";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mouseReleased(MouseEvent e) {
msg = "Mouse Released";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mouseEntered(MouseEvent e) {
msg = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e) {
msg = "Mouse Exited";
repaint();
}
// MouseMotionListener methods
public void mouseDragged(MouseEvent e)
{ msg = "Mouse Dragged";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
public void mouseMoved(MouseEvent e) {
msg = "Mouse Moved";
mouseX = [Link]();
mouseY = [Link]();
repaint();
}
// Display message
public void paint(Graphics g) {
[Link](msg + " at (" + mouseX + ", " + mouseY + ")", mouseX, mouseY);
}
}

Output:

Result:

You might also like