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

Java File Harshit

The document outlines a series of Java programming experiments, each with specific aims, theories, source codes, and expected outputs. Topics covered include command-line arguments, ASCII values, arithmetic operations, bitwise operations, data structures, method overloading, constructors, and inheritance. Each experiment is designed to teach fundamental programming concepts and demonstrate practical applications of Java.

Uploaded by

Harshit XII A 03
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 views58 pages

Java File Harshit

The document outlines a series of Java programming experiments, each with specific aims, theories, source codes, and expected outputs. Topics covered include command-line arguments, ASCII values, arithmetic operations, bitwise operations, data structures, method overloading, constructors, and inheritance. Each experiment is designed to teach fundamental programming concepts and demonstrate practical applications of Java.

Uploaded by

Harshit XII A 03
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

EXPERIMENT - 01

•​Aim : Write a Program to accept a String as a command line argument and print a
Welcome message as given below:-“Welcome your name”.

•​ Theory :

In Java, command-line arguments are inputs passed while running a program. These are
stored in the String[] args array of the main() method.

•​ args[0] → first argument


•​ Useful for taking input without using Scanner
•​ If no argument is passed → program should handle it

•​ Source Code :

class WelcomeMessage {
public static void main(String[] args) {
args = new String[]{"Yeshika"}; // preset input

if ([Link] > 0) {
[Link]("Welcome " + args[0]);
} else {
[Link]("Yeshika");
}
}
}

•​ Output:

Harshit 37714802724
EXPERIMENT - 02

•​ Aim : Program to find ASCII code of a character

•​ Theory:

This experiment demonstrates how to find the ASCII value of a character in Java. Each
character is internally represented by a numeric value based on the ASCII standard. In this
program, a character is taken and typecast into an integer using (int), which returns its
corresponding ASCII value. This helps in understanding typecasting, character
representation, and how data is stored and processed in Java.

•​ Source Code:

import [Link];

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

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


char ch = [Link]().charAt(0);

int ascii = (int) ch;

[Link]("ASCII value of " + ch + " is: " + ascii);


}
}

•​ Output:

Harshit 37714802724
EXPERIMENT - 03

•​ Aim: Write a Program to accept two integers as inputs and print their sum

•​ Theory:

The experiment demonstrates the basic use of variables, data types, and arithmetic operators
in Java by calculating the sum of two integers. Two integer variables are declared and
initialised, and the addition operator (+) is used to compute their sum, which is then stored
in another variable. The result is displayed using [Link](). This
program helps in understanding fundamental programming concepts such as variable
declaration, expression evaluation, and output display, which are essential for building more
complex Java applications.

•​ Source Code:
import [Link];
class SumOfNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

[Link]("Enter first number:


"); int num1 = [Link]();

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


int num2 = [Link]();

int sum = num1 + num2;

[Link]("Sum = " + sum);


}
}

•​ Output:

Harshit 37714802724
EXPERIMENT - 04

•​ Aim: Swapping two numbers using bitwise operator

•​ Theory:

This experiment demonstrates how to swap two integer variables without using a temporary
variable by applying the bitwise XOR (^) operator. The XOR operation has the property
that a number XORed twice with another number returns the original value, which makes it
useful for swapping. By performing a sequence of XOR operations on the two variables,
their values are exchanged efficiently. This helps in understanding bitwise operations and
memory-efficient programming techniques in Java.

•​ Source Code:

class SwapNumbers {

public static void main(String[] args) {

int a = 5;

int b = 10;

[Link]("Before swapping:");

[Link]("a = " + a + ", b = " + b);

a = a ^ b;

b = a ^ b;

a = a ^ b;

[Link]("After swapping:");

[Link]("a = " + a + ", b = " + b);

•​ Output:

Harshit 37714802724
EXPERIMENT - 05

•​ Aim: Initialize an integer array with ASCII values and print the
corresponding character values in a single row

•​ Theory:

This experiment demonstrates the use of arrays and typecasting in Java by storing ASCII
values in an integer array and converting them into corresponding characters. Each integer
value is typecast into a char, allowing us to understand how characters are internally
represented in Java. It also helps in learning array traversal and output formatting.

•​ Source Code:

class ASCIIArray {
public static void main(String[] args) {
int[] ascii = {65, 66, 67, 68, 69};

[Link]("Characters: ");
for (int i = 0; i < [Link]; i++) {
[Link]((char) ascii[i] + " ");
}
}
}

•​ Output:

Harshit 37714802724
EXPERIMENT - 06

•​ Aim: Write a program to reverse the elements of a given 2*2 [Link] integer
numbers need to be passed as Command-Line arguments

•​ Theory:

This experiment demonstrates array manipulation by reversing the elements of a 2×2 matrix.
Normally, values are passed using command-line arguments, but here they are directly initialized
for simplicity. The program shows how to store elements in a 2D array and reverse their order using
loops, helping in understanding indexing and array traversal.

•​ Source Code:

class ReverseArray {
public static void main(String[] args) {
int[][] arr = {
{1, 2},
{3, 4}
};
[Link]("Reversed array:");
for (int i = 1; i >= 0; i--) {
for (int j = 1; j >= 0; j--) {
[Link](arr[i][j] + " ");
}
[Link]();
}
}
}

•​ Output:

Harshit 37714802724
EXPERIMENT - 07

•​ Aim: Create a java program to implement stack and queue concept.

•​ Theory:

This experiment demonstrates the implementation of stack and queue data structures in
Java. A stack follows the LIFO (Last In First Out) principle, while a queue follows FIFO
(First In First Out). Java provides built-in classes like Stack and Queue to perform
operations such as push, pop, add, and remove, helping in understanding real-world data
handling.

•​ Source Code:

import [Link].*;

class StackQueueDemo {

public static void main(String[] args) {

// Stack

Stack<Integer> stack = new Stack<>();

[Link](10);

[Link](20);

[Link](30);

[Link]("Stack: " + stack);

[Link]();

[Link]("After pop: " + stack);

// Queue

Queue<Integer> queue = new LinkedList<>();

[Link](1);

[Link](2);

[Link](3);
Harshit 37714802724
[Link]("Queue: " + queue);

[Link]();

[Link]("After remove: " + queue);

•​ Output:

Harshit 37714802724
EXPERIMENT - 08

•​ Aim: Write a java program to produce the tokens from given long string

•​ Theory :

This experiment demonstrates how to break a long string into smaller parts called tokens
using delimiters such as spaces. In Java, methods like split() are used for tokenization.
This helps in understanding string manipulation, which is widely used in text processing,
parsing, and data handling applications.

•​ Source Code:

class StringTokens {

public static void main(String[] args) {

String str = "Java is a powerful programming language";

String[] tokens = [Link](" ");

[Link]("Tokens:");

for (String t : tokens) {

[Link](t);

•​ Output:

Harshit 37714802724
EXPERIMENT - 09

•​ Aim: Using the concept of method overloading , write method for calculating the area
of triangle, circle and rectangle

•​ Theory :

This experiment demonstrates the concept of method overloading in Java, which is a


feature of compile-time polymorphism where multiple methods can have the same name but
differ in the number, type, or order of parameters. It improves code readability and
reusability by allowing a single method name to perform different tasks based on the input
provided. In this program, the method area() is overloaded to calculate the area of
different shapes such as a rectangle, circle, and triangle using different parameter lists. The
appropriate method is automatically called by the compiler depending on the arguments
passed. This experiment helps in understanding function reusability, parameter passing, and
how Java handles method calls internally, which is useful in designing efficient and modular
programs.

•​ Source Code:

class AreaCalculator {

// Rectangle

static int area(int l, int b) {

return l * b;

// Circle

static double area(double r) {

return 3.14 * r * r;

// Triangle

static double area(double base, double height) {

Harshit 37714802724
return 0.5 * base * height;

public static void main(String[] args) {

[Link]("Rectangle Area: " + area(5, 4));

[Link]("Circle Area: " + area(3.0));

[Link]("Triangle Area: " + area(6.0, 2.0));

•​ Output:

Harshit 37714802724
EXPERIMENT - 10

•​ Aim: Create a class Box that uses a parametezised constructor to initialize the
dimensions of a [Link] dimensions of the Box are width, height, depth. The class
should have a method that can return the volume of the box. Create an object of the Box
class and test the functionalities

•​ Theory:

This experiment demonstrates the use of classes, objects, and parameterized constructors in Java. A
class named Box is created with attributes like width, height, and depth. A constructor is used to
initialize these values at the time of object creation. A method is defined to calculate and return the
volume of the box. This helps in understanding object-oriented concepts like encapsulation,
constructors, and method usage.

•​ Source Code:
import [Link];
class Box {
double width, height, depth;

// Parameterized constructor
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

double volume() {
return width * height * depth;
}
}

public class Main {


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

[Link]("Enter width: ");


double w = [Link]();

[Link]("Enter height: ");


double h = [Link]();

[Link]("Enter depth: ");


double d = [Link]();

Harshit 37714802724
Box b = new Box(w, h, d);

[Link]("Volume of box = " + [Link]());


}
}

•​ Output :

Harshit 37714802724
EXPERIMENT - 11

•​ Aim : Write a program to display the use of this keyword

•​ Theory:

This experiment demonstrates the use of the this keyword in Java, which refers to the
current object of a class. It is commonly used to differentiate between instance variables and
parameters with the same name. It also helps in improving code clarity and avoiding
ambiguity. This experiment shows how this is used to assign values to instance variables inside
a constructor.

•​ Source Code:
import [Link];
class Student {
int id;
String name;

Student(int id, String name) {


[Link] = id;
[Link] = name;
}

void display() {
[Link]("ID: " + id + ", Name: " + name);
}
}

public class Main {


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

[Link]("Enter ID: ");


int id = [Link]();
[Link](); // consume newline

[Link]("Enter Name: ");


String name = [Link]();

Student s = new Student(id, name);


[Link]();
}
}

Harshit 37714802724
•​ Output :

Harshit 37714802724
EXPERIMENT - 12

•​ Aim : Write a program that can count the number of instances created for the class

•​ Theory:

This experiment demonstrates how to count the number of objects created for a class using a
static variable. A static variable is shared among all objects of the class and is used to keep track
of the count. Each time an object is created, the constructor increments the counter. This helps in
understanding static members and object tracking in Java.

•​ Source Code:

class Counter {
static int count = 0;

Counter() {
count++;
[Link]("Object created. Current count: " + count);
}

static void displayCount() {


[Link]("Total objects created: " + count);
}
}

public class Main {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

[Link]();
}
}

•​ Output:

Harshit 37714802724
EXPERIMENT - 13

•​ Aim : Java program to get the cube of a given number using the static method

•​ Theory :

This experiment demonstrates the use of static methods in Java. A static method belongs to the class
rather than an object, and it can be called directly using the class name. In this program, a static
method is used to calculate the cube of a number. This helps in understanding method sharing,
memory efficiency, and class-level operations.

•​ Source Code :

class Cube {
static int cube(int n) {
return n * n * n;
}

public static void main(String[] args) {


int result = [Link](5);

[Link]("Cube of 5 = " + result);


}
}

•​ Output:

Harshit 37714802724
EXPERIMENT - 14

•​ Aim : Write a program that implements method overriding

•​ Theory:

Method overriding is a feature of runtime polymorphism in Java where a subclass provides a


specific implementation of a method that is already defined in its superclass.

When a method in the subclass has the same name, same parameters, and same return type as in
the parent class, it is said to override that method.

Key Points:

•​ It occurs between parent and child classes (inheritance required).


•​ The method must have the same signature.
•​ It is resolved at runtime (dynamic binding).
•​ It allows achieving polymorphism in Java.
•​ The @Override annotation is optional but recommended.

•​ Source Code :
•​
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
[Link]("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Animal obj = new Dog(); // Method overriding
[Link]();
}
}

•​ Output :

Harshit 37714802724
EXPERIMENT - 15

•​ Aim : Write a program to illustrate simple inheritance

•​ Theory:

Simple inheritance is a mechanism in Java where one child class inherits properties and
methods from a single parent class using the extends keyword. It promotes code
reusability and reduces duplication. The child class can use existing features of the parent
class and also add its own functionality.

•​ Source Code :

class Animal {

void eat() {

[Link]("Animal eats food");

class Dog extends Animal {

void bark() {

[Link]("Dog barks");

public class Main {

public static void main(String[] args) {

Dog d = new Dog();

[Link]();

[Link]();

}
Harshit 37714802724
•​ Output :

Harshit 37714802724
EXPERIMENT - 16

•​ Aim : Write a program to illustrate multilevel inheritance

•​ Theory :

Multilevel inheritance is a type of inheritance where a class is derived from another derived
class, forming a chain of inheritance. This means a class acts as both a parent and a child.
It allows code reuse across multiple levels and helps in creating a hierarchical relationship
between classes.

•​ Source Code :

class Animal {
void eat() {
[Link]("Animal eats");
}
}

class Dog extends Animal {


void bark() {
[Link]("Dog barks");
}
}

class Puppy extends Dog {


void weep() {
[Link]("Puppy weeps");
}
}

public class Main {


public static void main(String[] args) {
Puppy p = new Puppy();
[Link]();
[Link]();
[Link]();
}
}

Output :

Harshit 37714802724
EXPERIMENT - 17

•​ Aim : Write a program illustrating all uses of super keywords

•​ Theory :

The super keyword is used to refer to the immediate parent class. It is used to:

•​ Call parent class constructor


•​ Access parent class methods
•​ Access parent class variables

•​ Source Code :

class Animal {
String name = "Animal";

Animal() {
[Link]("Animal constructor");
}

void display() {
[Link]("This is Animal class");
}
}

class Dog extends Animal {


String name = "Dog";

Dog() {
super(); // calling parent constructor
[Link]("Dog constructor");
}

void show() {
[Link]("Child name: " + name);
[Link]("Parent name: " + [Link]); // accessing parent variable
[Link](); // calling parent method
}
}

public class Main {


public static void main(String[] args) {
Dog d = new Dog();
[Link]();
}

Harshit 37714802724
}

•​ Output :

Harshit 37714802724
EXPERIMENT - 18

•​ Aim : Write a program to show dynamic polymorphism and interface

•​ Theory :

Dynamic polymorphism is a concept where the method call is resolved at runtime, usually
achieved through method overriding. It allows one interface to be used for different types
of actions.

An interface in Java is a collection of abstract methods that a class must implement. It helps
achieve abstraction and supports multiple inheritance. Using interfaces along with dynamic
polymorphism makes programs more flexible, modular, and easy to maintain.

•​ Source Code :

interface Animal {

void sound();

class Dog implements Animal {

public void sound() {

[Link]("Dog barks");

class Cat implements Animal {

public void sound() {

[Link]("Cat meows");

public class Main {

public static void main(String[] args) {


Harshit 37714802724
Animal a;

a = new Dog();

[Link]();

a = new Cat();

[Link]();

•​ Output :

Harshit 37714802724
EXPERIMENT - 19

•​ Aim : Create an abstract class shape . Let rectangle and triangle inherit this shape class.
Add necessary functions

•​ Theory :

An abstract class is a class that cannot be instantiated and may contain abstract methods
(methods without a body). Subclasses must implement these methods. It helps achieve
abstraction and code reusability.

•​ Source Code :

abstract class Shape {


abstract void area();
}

class Rectangle extends Shape {


int length = 10;
int breadth = 5;

void area() {
[Link]("Area of Rectangle: " + (length * breadth));
}
}

class Triangle extends Shape {


int base = 6;
int height = 4;

void area() {
[Link]("Area of Triangle: " + (0.5 * base * height));
}
}

public class Main {


public static void main(String[] args) {
Shape s;

s = new Rectangle();
[Link]();

s = new Triangle();
[Link]();
}
}
Harshit 37714802724
•​ Output :

Harshit 37714802724
EXPERIMENT - 20

•​ Aim : Write a java package to show dynamic polymorphism and interfaces

•​ Theory :

A package in Java is used to organize related classes into a namespace, making the
program more structured and manageable.

Dynamic polymorphism is achieved through method overriding, where the method call is
resolved at runtime, allowing one reference to refer to different objects.

An interface is a collection of abstract methods that a class must implement. It helps in


achieving abstraction and makes the program more flexible and reusable.

•​ Source Code :

interface Animal {

void sound();

class Dog implements Animal {

public void sound() {

[Link]("Dog barks");

class Cat implements Animal {

public void sound() {

[Link]("Cat meows");

public class Main {

Harshit 37714802724
public static void main(String[] args) {

Animal a;

a = new Dog();

[Link]();

a = new Cat();

[Link]();

•​ Output :

Harshit 37714802724
EXPERIMENT - 21

•​ Aim : Write an application that creates an ‘interface’ and implements it

•​ Theory :

An interface is a collection of abstract methods. A class implements an interface using the


implements keyword and must define all its methods. It helps achieve abstraction and
multiple inheritance.

•​ Source Code :

interface Vehicle {
void start();
}

class Car implements Vehicle {


public void start() {
[Link]("Car starts with key");
}
}

public class Main {


public static void main(String[] args) {
Vehicle v = new Car();
[Link]();
}
}

•​ Output :

Harshit 37714802724
EXPERIMENT - 22

•​ Aim : Write an interface called Playable, with a method void play(); Let this
interface be placed in a package called music. Write a class called Veena which
implements Playable interface. Let this class be placed in a package [Link]. Write a
class called Saxophone which implements Playable interface. Let this class be placed in a
package [Link]. Write another class Test in a package called live. Then,

(a)​Create an instance of Veena and call play() method


(b)​Create an instance of Saxophone and call play() method
(c)​Place the above instances in a variable of type Playable and then call play()

•​ Theory :

An interface in Java is a collection of abstract methods that a class must implement. It helps
achieve abstraction and supports multiple inheritance.

Packages are used to organize classes into namespaces, making the program structured and
manageable. Sub-packages allow further categorization.

In this experiment, an interface Playable is created in the music package. Classes


Veena and Saxophone implement this interface in different sub-packages. A Test
class demonstrates dynamic polymorphism by calling the play() method using both
objects and interface references.

•​ Source Code :

interface Playable {

void play();

class Veena implements Playable {

public void play() {

[Link]("Playing Veena");

class Saxophone implements Playable {

Harshit 37714802724
public void play() {

[Link]("Playing Saxophone");

public class Main {

public static void main(String[] args) {

// (a) Veena object

Veena v = new Veena();

[Link]();

// (b) Saxophone object

Saxophone s = new Saxophone();

[Link]();

// (c) Using interface reference (dynamic polymorphism)

Playable p;

p = new Veena();

[Link]();

p = new Saxophone();

[Link]();

Harshit 37714802724
•​ Output :

Harshit 37714802724
EXPERIMENT - 23

•​ Aim : Write a program to accept name and age of a person from the command prompt
(passed as arguments when you execute the class) and ensure that the age entered is
>=15 and < 60. Display proper error messages. The program must exit gracefully after
displaying the error message in case the arguments passed are not proper. (Hint: Create a
user defined exception class for handling errors.)

•​ Theory :

Command line arguments allow passing inputs during program execution. A user-defined
exception is created to handle invalid inputs like incorrect age. Exception handling ensures
the program terminates gracefully with proper messages.

•​ Source Code :

import [Link];

class InvalidAgeException extends Exception {

InvalidAgeException(String msg) {

super(msg);

public class Main {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

try {

[Link]("Enter name: ");

String name = [Link]();

[Link]("Enter age: ");


int age = [Link]();

Harshit 37714802724
if (age < 15 || age >= 60) {

throw new InvalidAgeException("Age must be between 15 and 59");

[Link]("Name: " + name);

[Link]("Age: " + age);

} catch (InvalidAgeException e) {

[Link]("Error: " + [Link]());

} catch (Exception e) {

[Link]("Error: Invalid input");

[Link]();

Output :

Harshit 37714802724
EXPERIMENT - 24

•​ Aim : Create a customized exception and also make use of all the 5 exception keywords.

•​ Theory :

Java provides five keywords for exception handling: try, catch, throw, throws, and
finally. A custom exception is created by extending the Exception class to handle
specific errors.

•​ Source Code :

class MyException extends Exception {

MyException(String msg) {

super(msg);

public class Main {

static void check(int num) throws MyException {

if (num < 0) {

throw new MyException("Number cannot be negative");

} else {

[Link]("Valid number");

public static void main(String[] args) {

try {

check(-5);

} catch (MyException e)

Harshit 37714802724
Harshit 37714802724
[Link]("Caught Exception: " + [Link]());

} finally {

[Link]("Finally block executed");

•​ Output :

Harshit 37714802724
EXPERIMENT - 25

•​ Aim : Write an Applet that displays “Hello World “(Background color black, text
color- blue and your name in the status window.)

•​ Theory :

An applet is a Java program that runs in a browser or applet viewer. It is used to create GUI-
based applications. Methods like setBackground(), setForeground(), and
showStatus() are used to control appearance and display messages.

•​ Source Code :

import [Link];

import [Link].*;

public class HelloApplet extends Applet {

public void init() {

// Set background color to black


setBackground([Link]);
}

public void paint(Graphics g) {

// Set text color to blue

[Link]([Link]);

// Display Hello World

[Link]("Hello World", 100, 100);

Harshit 37714802724
}

•​ Output :

Harshit 37714802724
EXPERIMENT - 26

•​ Aim : Develop an analog clock using applet. Again give the exact aim theory and
java code

•​ Theory :

An analog clock applet uses Java graphics to draw clock components like circle and hands.
The current time is fetched using system time, and graphical methods are used to display
hour, minute, and second hands dynamically.

•​ Source Code :

import [Link];

import [Link].*;

import [Link].*;

public class AnalogClock extends Applet implements Runnable {

Thread t;

public void init() {

setBackground([Link]);

public void start() {

t = new Thread(this);

[Link]();

public void run() {

while (true) {

repaint(); // refresh every second

Harshit 37714802724
try {

[Link](1000);

} catch (InterruptedException e) {}

public void paint(Graphics g) {

int x = 150, y = 150, r = 100;

// Draw clock circle

[Link](x - r, y - r, 2 * r, 2 * r);

// Draw numbers

for (int i = 1; i <= 12; i++) {

double angle = [Link](i * 30 - 90);

int numX = (int)(x + [Link](angle) * (r -

20)); int numY = (int)(y + [Link](angle) * (r -

20)); [Link]([Link](i), numX,

numY);

// Get current time

Calendar cal = [Link]();

int hour = [Link]([Link]);

int minute = [Link]([Link]);

Harshit 37714802724
int second = [Link]([Link])
// Calculate angles

double secAngle = [Link](second * 6 - 90);

double minAngle = [Link](minute * 6 - 90);

double hrAngle = [Link]((hour * 30 + minute / 2) - 90);

// Draw hands

drawHand(g, x, y, secAngle, r - 10); // second

drawHand(g, x, y, minAngle, r - 20); // minute

drawHand(g, x, y, hrAngle, r - 40); // hour

// Method to draw hands

public void drawHand(Graphics g, int x, int y, double angle, int length) {

int xEnd = (int)(x + [Link](angle) * length);

int yEnd = (int)(y + [Link](angle) * length);

[Link](x, y, xEnd, yEnd);

}
// Calculate angles

double secAngle = [Link](second * 6 - 90);

double minAngle = [Link](minute * 6 - 90);

double hrAngle = [Link]((hour * 30 + minute / 2) - 90);

// Draw hands

drawHand(g, x, y, secAngle, r - 10); // second

Harshit 37714802724
drawHand(g, x, y, minAngle, r - 20); // minute

drawHand(g, x, y, hrAngle, r - 40); // hour

// Method to draw hands

public void drawHand(Graphics g, int x, int y, double angle, int length) {

int xEnd = (int)(x + [Link](angle) * length);

int yEnd = (int)(y + [Link](angle) * length);

[Link](x, y, xEnd, yEnd);

Output:

Harshit 37714802724
Harshit 37714802724
EXPERIMENT - 27

•​ Aim : Write a java program to show multithreaded producer and consumer application.

•​ Theory :

Producer-consumer is a classic multithreading problem where one thread (producer)


produces data and another thread (consumer) consumes it. Synchronization ensures proper
communication between threads using methods like wait() and notify().

•​ Source Code :

class Buffer {

int data;

boolean available = false;

synchronized void produce(int value) {

try {

while (available)

wait();

data = value;

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

available = true;

notify();

} catch (Exception e) {}

synchronized void consume() {

try {

while (!available)

wait();

Harshit 37714802724
[Link]("Consumed: " + data);

available = false;

notify();

} catch (Exception e) {}

class Producer extends Thread {

Buffer b;

Producer(Buffer b) {

this.b = b;

public void run() {

for (int i = 1; i <= 5; i++) {

[Link](i);

class Consumer extends Thread {

Buffer b;

Consumer(Buffer b) {

Harshit 37714802724
this.b = b;

public void run() {

for (int i = 1; i <= 5; i++) {

[Link]();

public class Main {

public static void main(String[] args) {

Buffer b = new Buffer();

Producer p = new Producer(b);

Consumer c = new Consumer(b);

[Link]();

[Link]();

Harshit 37714802724
•​ Output :

Harshit 37714802724
EXPERIMENT - 28

•​ Aim :Write an application that executes two threads. One thread every 1000
milliseconds and another every 3000 milliseconds. Create the threads by extending the
Thread class.

•​ Theory :

Multithreading allows concurrent execution. Threads can be controlled using sleep()


method to pause execution for a specific time interval.

•​ Source Code :

class Thread1 extends Thread {

public void run() {

try {

for (int i = 1; i <= 5; i++) {

[Link]("Thread 1 running");

[Link](1000);

} catch (Exception e) {}

class Thread2 extends Thread {

public void run() {

try {

for (int i = 1; i <= 5; i++) {

[Link]("Thread 2 running");

[Link](3000);

} catch (Exception e) {}

Harshit 37714802724
}

public class Main {

public static void main(String[] args) {

Thread1 t1 = new Thread1();

Thread2 t2 = new Thread2();

[Link]();

[Link]();

•​ Output :

Harshit 37714802724
EXPERIMENT - 29

•​ Aim : Create class of SalesPersons as a thread that will display five sales persons
name. Create a class as Days as other Thread that has array of seven days. Call the
instance of SalesPersons in Days and start both the threads, suspend SalesPersons on
Sunday and resume on Wednesday.
Note: use suspend, resume methods from thread

•​ Theory :

Threads can be controlled using methods like suspend() and resume() (though
deprecated). These methods pause and restart thread execution. This experiment
demonstrates thread coordination.

•​ Source Code :

class SalesPersons extends Thread {

String[] names = {"Amit", "Ravi", "Sita", "Neha", "Rahul"};

public void run() {

try {

for (String name : names) {

[Link]("Sales Person: " + name);

[Link](1000);

} catch (Exception e) {}

class Days extends Thread {

SalesPersons sp;

Days(SalesPersons sp) {
[Link] = sp;

Harshit 37714802724
}

public void run() {

String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",


"Saturday", "Sunday"};

try {

for (String day : days) {

[Link]("Day: " + day);

if ([Link]("Sunday")) {

[Link]("Suspending SalesPersons...");

[Link]();

if ([Link]("Wednesday")) {

[Link]("Resuming SalesPersons...");

[Link]();

[Link](1000);

} catch (Exception e) {}

Harshit 37714802724
public class Main {

public static void main(String[] args) {

SalesPersons sp = new SalesPersons();

Days d = new Days(sp);

[Link]();

[Link]();

•​ Output :

Harshit 37714802724
EXPERIMENT - 30

•​ Aim : WAP that illustrates how to process mouse click, enter, exit, press and
release events. The background color changes when the mouse is entered, clicked,
pressed, released or exited.

•​ Theory :

Mouse events in Java are handled using the MouseListener interface. It provides
methods like mouseClicked(), mouseEntered(), mouseExited(),
mousePressed(), and mouseReleased(). These methods help respond to user
interactions such as clicking or moving the mouse.

•​ Source Code :

import [Link].*;

import [Link].*;

public class MouseEventDemo extends Frame implements MouseListener {

MouseEventDemo() {

setTitle("Mouse Event Demo”);

setSize(400, 300);

setVisible(true);

addMouseListener(this);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

[Link](0);

});

}
public void mouseEntered(MouseEvent e) {
setBackground([Link]);

Harshit 37714802724
}

public void mouseExited(MouseEvent e) {

setBackground([Link]);

public void mouseClicked(MouseEvent e) {

setBackground([Link]);

public void mousePressed(MouseEvent e) {

setBackground([Link]);

public void mouseReleased(MouseEvent e) {

setBackground([Link]);

public static void main(String[] args) {

new MouseEventDemo();

•​ Output :

Harshit 37714802724
EXPERIMENT - 31

•​ Aim : WAP that displays your name whenever the mouse is clicked.

•​ Theory :

Mouse click events are handled using mouseClicked() method of MouseListener.


When the user clicks the mouse, the program responds by displaying text on the [Link]

•​ Source Code :

import [Link].*;

import [Link].*;

public class MouseNameDisplay extends Frame implements MouseListener {

String message = “";

MouseNameDisplay() {

setTitle("Mouse Click Name Display”);

setSize(400, 300);

setVisible(true);

addMouseListener(this);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent we) {

[Link](0);

});

public void paint(Graphics g) {

Harshit 37714802724
[Link](new Font("Arial", [Link], 20));

[Link](message, 100, 150);

// Mouse clicked event

public void mouseClicked(MouseEvent e) {

message = “Yeshika”;

repaint();

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mousePressed(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public static void main(String[] args) {

new MouseNameDisplay();

•​ Output :

Harshit 37714802724

You might also like