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

File Java 10-40

The documents discuss Java programs involving arrays, matrices, stacks, queues and other data structures. They include the aim, theory and code for programs that initialize arrays, reverse matrices, implement stacks and queues, tokenize strings, calculate areas using method overloading, create classes with parameterized constructors, demonstrate the use of 'this' keyword, count instances of a class using static variables, find cubes using static methods and more.

Uploaded by

balidhruv8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

File Java 10-40

The documents discuss Java programs involving arrays, matrices, stacks, queues and other data structures. They include the aim, theory and code for programs that initialize arrays, reverse matrices, implement stacks and queues, tokenize strings, calculate areas using method overloading, create classes with parameterized constructors, demonstrate the use of 'this' keyword, count instances of a class using static variables, find cubes using static methods and more.

Uploaded by

balidhruv8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

PROGRAM – 10

AIM : Write a Program to Initialize an integer array with ASCII values and print the
corresponding character values in a single row.

THEORY : ASCII assigns integer values to characters, facilitating their representation and
manipulation in computers.

CODE :

package LAB_CLG;

public class LAB_10 {


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

System.out.print("Corresponding characters: ");


for (int i = 0; i < asciiValues.length; i++) {
System.out.print((char)asciiValues[i] + " ");
}
System.out.println();
}

}
OUTPUT :
PROGRAM – 11

AIM : Write a program to reverse the elements of a given 2*2 array. Four integer numbers
need to be passed as Command-Line arguments

THEORY :
The program effectively demonstrates the concept of matrix transposition by swapping
rows with columns in a 2x2 matrix and printing both the original and transposed matrices.

CODE :

package LAB_CLG;

public class LAB_11 {


public static void main(String[] args) {
int[][] originalMatrix = {{1, 2}, {3, 4}};

System.out.println("Original Matrix:");
printMatrix(originalMatrix);

int[][] transposedMatrix = transpose(originalMatrix);

System.out.println("\nTransposed Matrix:");
printMatrix(transposedMatrix);
}

public static int[][] transpose(int[][] matrix) {


int[][] transposed = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
transposed[j][i] = matrix[i][j];
}
}
return transposed;
}

public static void printMatrix(int[][] matrix) {


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

OUTPUT :
PROGRAM – 12

AIM : Create a java program to implement stack and queue concept

THEORY : In Java, stacks and queues are implemented using the java.util.Stack and
java.util.Queue interfaces, respectively. These interfaces provide methods for common
stack and queue operations such as push/pop for stacks and enqueue/dequeue for queues.

CODE :

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class LAB_12 {


public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);

System.out.println("Stack:");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}

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


queue.offer(1);
queue.offer(2);
queue.offer(3);

System.out.println("\nQueue:");
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
}
}
OUTPUT:
PROGRAM – 13

AIM : Write a java program to produce the tokens from given long string.

THEORY : Tokens are the smallest units of a program, such as keywords, identifiers,
operators, and punctuation marks, which are recognized by the compiler or interpreter.

CODE :
package LAB_CLG;

import java.util.StringTokenizer;

public class LAB_13 {


public static void main(String[] args) {
String longString = "This is a long string with multiple words and spaces\nand\ttabs";

// Creating a StringTokenizer object with whitespace characters as delimiters


StringTokenizer tokenizer = new StringTokenizer(longString);

// Iterating through the tokens and printing them


System.out.println("Tokens from the long string:");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
}
}
}

OUTPUT :
PROGRAM – 14

AIM : Using the concept of method overloading Write method for calculating the area of
triangle, circle and rectangle.

THEORY :
Method overloading allows for more intuitive method names while providing flexibility in
handling different types of calculations within the same class.

CODE :
package LAB_CLG;

public class LAB_14 {


public static double calculateTriangleArea(double base, double height) {
return 0.5 * base * height;
}
public static double calculateCircleArea(double radius) {
return Math.PI * radius * radius;
}
public static double calculateRectangleArea(double length, double width) {
return length * width;
}

public static void main(String[] args) {


double triangleArea = calculateTriangleArea(5, 8);
System.out.println("Area of triangle: " + triangleArea);

double circleArea = calculateCircleArea(3);


System.out.println("Area of circle: " + circleArea);

double rectangleArea = calculateRectangleArea(4, 6);


System.out.println("Area of rectangle: " + rectangleArea);
}

}
OUTPUT :
PROGRAM – 15
AIM:
Create a class Box that uses a parameterized constructor to initialize the dimensions of a box. The 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:
Box class is created with attributes width, height, depth Parameterized constructor is used to initialize attributes
getVolume() method returns volume main() takes user input and passes to constructor to create Box object Volume
is calculated by accessing method to test the class.

SOURCE CODE:
package LAB_CLG;

import java.util.Scanner;

class Box {

double width;

double height;

double depth;

public Box(double width, double height, double depth) {

this.width = width;

this.height = height;

this.depth = depth;

double getVolume() {

return width * height * depth;

public class LAB_15 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter width, height and depth of box: ");


double width = sc.nextDouble();

double height = sc.nextDouble();

double depth = sc.nextDouble();

Box smallBox = new Box(width, height, depth);

double vol = smallBox.getVolume();

System.out.println("Volume of box is: " + vol);

sc.close(); // Close the scanner to prevent resource leak

OUTPUT:
PROGRAM – 16

AIM:
WAP to display the use of this keyword.

THEORY:
In the constructor: 'this' keyword is used to refer the instance variables rollNo and name, to avoid confusion with
local parameters. In display() method: Instance variables can be accessed directly but using 'this' makes code more
readable. So 'this' keyword allows referring current object which helps avoiding confusions and improves
readability.

SOURCE CODE:
package LAB_CLG;

import java.util.Scanner;

public class LAB_16 {

int rollNo;

String name;

public LAB_16(int rollNo, String name) {

this.rollNo = rollNo;

this.name = name;

void display() {

System.out.println(rollNo + " " + name);

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter roll number: ");

int rollNo = sc.nextInt();


System.out.print("Enter name: ");

String name = sc.next();

LAB_16 std = new LAB_16(rollNo, name);

std.display();

OUTPUT:
PROGRAM – 17

AIM:
Write a program that can count the number of instances created for the class.

THEORY:
Static variables are shared among all objects of a class. Here count is declared as static variable of Counter class.
Constructor is invoked every time new object is created. So we are incrementing static count variable in
constructor to keep track of number of objects created. Finally count gives total objects created for Counter class.
So key points are: Use static variable to store instance count Increment static count in constructor Print value of
static count This way we can get number of instances/objects created for a class by using static variable and
constructor.

SOURCE CODE:
package LAB_CLG;

import java.util.Scanner;

class Counter {

static int count=0;

Counter(){

count++;

public class LAB_17 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("How many objects you want to create: ");

int n = sc.nextInt();

for(int i=0; i<n; i++){

Counter obj = new Counter();

System.out.println(n + " instances created");

}
OUTPUT:
PROGRAM – 18

AIM:
Java Program to get the cube of a given number using the static method.

THEORY:
Static methods belong to the class rather than object. They are loaded in the memory only once when the class is
loaded. Can be called without needing to create an object of class. Static methods can only access static data
members and call other static methods. Cannot use non-static or instance variables inside them. Commonly used
for reusable logic that doesn't need object level data. Can be called directly by using ClassName.MethodName()
syntax.

In this program:

getCube() is declared static since it only depends on the passed parameter. It calculates cube in a reusable way
without needing any object data. It is called directly using Main.getCube() So static methods improve optimization
of memory usage and allows reusable logic. The core advantage is no need to create objects just to execute a piece
of code.

SOURCE CODE:
package LAB_CLG;

import java.util.Scanner;

public class LAB_18 {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter any number: ");

int num = sc.nextInt();

int cube = getCube(num);

System.out.println("Cube of " + num + " is: " + cube);

public static int getCube(int x) {

return x*x*x;

}
OUTPUT:
PROGRAM – 19

AIM:
WAP that implements method overriding

THEORY:
Method overriding allows a subclass to provide a specific implementation of a method already provided by its
parent class. When a method in a subclass has the same signature as a method in its parent class, it is said to
override the method. The overriding method must have the same method name, parameter list, and return type as
the parent class method. Overriding allows polymorphism, where a subclass can be substituted for its parent class.
The version of the method that gets executed depends on the actual object, not the declared type of the variable.
Overriding methods allows subclasses to give their own specific implementation for inherited behaviors.

SOURCE CODE:
package LAB_CLG;

import java.util.Scanner;

class Shape {

double width, height;

void input() {

Scanner sc = new Scanner(System.in);

System.out.print("Enter width: ");

width = sc.nextDouble();

System.out.print("Enter height: ");

height = sc.nextDouble();

double area() {

return 0;

class Triangle extends Shape {

@Override

double area() {

return 0.5 * width * height;

}
}

class Rectangle extends Shape {

@Override

double area() {

return width * height;

public class LAB_19 {

public static void main(String[] args) {

Shape s;

s = new Triangle();

s.input();

System.out.println("Area of Triangle: " + s.area());

s = new Rectangle();

s.input();

System.out.println("Area of Rectangle: " + s.area());

OUTPUT:
PROGRAM – 20
AIM:
WAP to illustrate simple inheritance.

THEORY:
Inheritance is a mechanism where a new class inherits properties and behavior from an existing class. The existing
class is called the superclass or parent class. The new class is called the subclass or child class. Using the extends
keyword, the subclass can inherit attributes and methods from the parent class. Inheritance supports code
reusability - common properties and behaviors can be defined in the parent class and reused in subclasses.
Subclasses can also add their own properties and methods to specialize the parent class.

SOURCE CODE:
package LAB_CLG;

class Animal {

void eat() {

System.out.println("Eating...");

class Dog extends Animal {

void bark() {

System.out.println("Barking...");

public class LAB_20 {

public static void main(String[] args) {

Dog d = new Dog();

d.bark();

d.eat();

}
OUTPUT:
PROGRAM – 21

AIM:
WAP to illustrate multilevel inheritance.

THEORY:
Multilevel inheritance occurs when a class inherits from another class, which in turn inherits from yet another
class. It forms a chain of parent-child relationships. Here’s how it works: A parent class (also known as the
grandparent class) has features. A child class inherits features from the parent class. An intermediate class (the
child of the parent and parent of another child) can also exist. In multilevel inheritance, the inheritance linkage is
linear, and at least three classes are involved.

SOURCE CODE:
package LAB_CLG;

class Person {

Person() {

System.out.println("Person constructor");

void nationality() {

System.out.println("Indian");

void place() {

System.out.println("Mumbai");

class Emp extends Person {

Emp() {

System.out.println("Emp constructor");

void organization() {

System.out.println("IBM");
}

void place() {

System.out.println("New York");

class Manager extends Emp {

Manager() {

System.out.println("Manager constructor");

void subordinates() {

System.out.println(12);

void place() {

System.out.println("London");

public class LAB_21 {

public static void main(String[] args) {

Manager m = new Manager();

m.nationality();

m.organization();

m.subordinates();

m.place();

}
OUTPUT:
PROGRAM – 22

AIM:
WAP illustrating all uses of super keywords.

THEORY:
The super keyword in Java is used to refer to the superclass (parent class) of the current object. It can be used in
several ways:

Accessing Superclass Members: You can use super to access methods or fields from the superclass that have been
overridden or hidden by the subclass.

Invoking Superclass Constructor: You can use super() to call the constructor of the superclass. This is useful when
the superclass constructor needs to be executed before the subclass constructor.

Accessing Superclass Constructor with Parameters: You can use super(...) to call a specific constructor of the
superclass with parameters.

SOURCE CODE:
package LAB_CLG;

class Animals {

String name;

Animals(String name) {

this.name = name;

void eat() {

System.out.println(name + " is eating.");

class Dogs extends Animals {

String breed;

Dogs(String name, String breed) {

super(name); // Calling superclass constructor


this.breed = breed;

void display() {

super.eat(); // Calling superclass method

System.out.println(name + " is a " + breed + " dog.");

public class LAB_22 {

public static void main(String[] args) {

Dogs dog = new Dogs("Buddy", "Labrador");

dog.display();

OUTPUT:
PROGRAM – 23

AIM:
WAP to show dynamic polymorphism and interface.

THEORY:
Dynamic polymorphism in Java is achieved through method overriding. When a subclass provides a specific
implementation of a method that is already provided by its superclass, it is known as method overriding. This
allows a subclass to provide its own implementation of a method that is already defined in its superclass. Interfaces
in Java define a contract for classes that implement them, specifying the methods that implementing classes must
provide.

SOURCE CODE:
package college_lab;

interface Animal {

void eat();

class Dog implements Animal {

public void eat() {

System.out.println("Dog is eating");

void bark() {

System.out.println("Dog is barking");

class Cat implements Animal {

public void eat() {

System.out.println("Cat is eating");

void meow() {

System.out.println("Cat is meowing");

}
public class LAB_23 {

public static void main(String[] args) {

Animal animal1 = new Dog();

Animal animal2 = new Cat();

animal1.eat();

((Dog) animal1).bark();

System.out.println();

animal2.eat();

((Cat) animal2).meow();

OUTPUT:
PROGRAM:-25
AIM:-Write a java package to show dynamic polymorphism and interfaces .
THEORY:-
The Shape interface defines the common methods getArea() and getPerimeter() that all shapes must
implement. The ClosedShape abstract class implements the Shape interface and provides a color property
common to closed shapes. The Rectangle and Circle classes are concrete implementa ons of ClosedShape,
providing their own implementa ons of getArea() and getPerimeter(). The ShapeDemo class contains a
printShapeInfo() method that demonstrates dynamic polymorphism. This method takes a Shape object as input
and calls its getArea() and getPerimeter() methods. If the Shape object is also an instance of ClosedShape, it
prints the color as well. In the main method, instances of Rectangle and Circle are created and passed to the
printShapeInfo() method, demonstra ng dynamic polymorphism.

SOURCE CODE :-
interface Shape {

double getArea();

double getPerimeter();

abstract class ClosedShape implements Shape {

protected String color;

public ClosedShape(String color) {

this.color = color;

public String getColor() {

return color;

class Rectangle extends ClosedShape {

private double length;

private double width;

public Rectangle(String color, double length, double width) {

super(color);

this.length = length;

this.width = width;

@Override
public double getArea() {

return length * width;

@Override

public double getPerimeter() {

return 2 * (length + width);

class Circle extends ClosedShape {

private double radius;

public Circle(String color, double radius) {

super(color);

this.radius = radius;

@Override

public double getArea() {

return Math.PI * radius * radius;

@Override

public double getPerimeter() {

return 2 * Math.PI * radius;

public class ShapeDemo {

public sta c void printShapeInfo(Shape shape) {

System.out.println("Shape area: " + shape.getArea());

System.out.println("Shape perimeter: " + shape.getPerimeter());

if (shape instanceof ClosedShape) {

ClosedShape closedShape = (ClosedShape) shape;

System.out.println("Shape color: " + closedShape.getColor());

public sta c void main(String[] args) {


Shape rect = new Rectangle("Red", 5.0, 3.0);

Shape circle = new Circle("Blue", 4.0);

printShapeInfo(rect);

System.out.println();

printShapeInfo(circle);

OUTPUT:-
PROGRAM:-26
AIM:- Write an applica on that creates an ‘interface’ and implements it.

THEORY:-
Interfaces in Java are used to define a contract or a set of methods that classes must implement.
They promote abstrac on, loose coupling, and code reusability. By crea ng classes that implement
an interface, you can write code that works with objects of those classes through the interface,
without needing to know the specific implementa on details of each class.

SOURCE CODE:-
interface Movable {

void move(int x, int y);

class Vehicle implements Movable {

private int x;

private int y;

public Vehicle(int x, int y) {

this.x = x;

this.y = y;

@Override

public void move(int x, int y) {

this.x += x;

this.y += y;

System.out.println("Vehicle moved to (" + this.x + ", " + this.y + ")");

public class MoveDemo {

public sta c void main(String[] args) {

Movable car = new Vehicle(0, 0);

car.move(10, 5);

car.move(-3, 2);

}
OUTPUT:-
PROGRAM:-27
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 music.string .Write a class called Saxophone which implements Playable
interface. Let this class be placed in a package music.wind .Write another class Test in a package
called live. Then, (a). Create an instance of Veena and call play() method (b). Create an 4 instance of
Saxophone and call play() method (c). Place the above instances in a variable of type Playable and
then call play()

THEORY:-
Interfaces in Java:

An interface is a reference type in Java that defines a contract for classes to follow. It specifies

a set of methods that any class implemen ng the interface must provide.In our case, we have

the Playable interface with a single method: void play(). Any class that implements Playable

must provide an implementa on for this method.

Packages:

Packages in Java are used to organize classes into namespaces. They help avoid naming

conflicts and provide a hierarchical structure. The music package contains the Playable

interface. The music.string package contains the Veena class. The music.wind package contains

the Saxophone class. The live package contains the Test class. Veena and Saxophone Classes:

Both Veena and Saxophone classes implement the Playable interface. They override the play()

method, providing their own specific implementa on. When an instance of either class calls

play(), the corresponding instrument’s sound is simulated.

Test Class:

The Test class demonstrates how to use the Veena and Saxophone classes. It creates instances

of both instruments and calls their play() methods. It also showcases polymorphism by

assigning instances to a variable of type Playable and invoking the play() method.

SOURCE CODE:-
package music;

public interface Playable {

void play();

package music.string;
import music.Playable;

public class Veena implements Playable {

@Override

public void play() {

System.out.println("Veena is playing...");

package music.wind;

import music.Playable;

public class Saxophone implements Playable {

@Override

public void play() {

System.out.println("Saxophone is playing...");

package live;

import music.Playable;

import music.string.Veena;

import music.wind.Saxophone;

public class Test {

public sta c void main(String[] args) {

Veena veenaInstance = new Veena();

veenaInstance.play();

Saxophone saxophoneInstance = new Saxophone();

saxophoneInstance.play();

Playable playableInstance = veenaInstance;

playableInstance.play();

playableInstance = saxophoneInstance;

playableInstance.play();

}
OUTPUT:-
PROGRAM:-28
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 a er displaying the error message in case the arguments passed are not
proper. (Hint : Create a user defined excep on class for handling errors.)

THEORY:-
In Java, excep ons are used to handle excep onal or error condi ons that may arise during the execu on of a
program. Java provides built-in excep on classes to handle various types of excep ons, such as
ArrayIndexOutOfBoundsExcep on, NullPointerExcep on, Arithme cExcep on, and more. However, in some
cases, you may need to define your own custom excep on classes to handle specific error condi ons in your
applica on. User-defined excep ons are created by extending the Excep on class or one of its subclasses. In
the given program, we define a custom excep on class called AgeExcep on that extends the Excep on class.
This excep on is thrown when the age entered by the user is not within the valid range (between 15 and 60).
The main method of the AgeValidator class first checks if the correct number of arguments (two, represen ng
name and age) is provided. If not, it throws an IllegalArgumentExcep on with an appropriate error message.
Next, it tries to parse the second argument (age) as an integer using Integer.parseInt. If the age is not in a valid
integer format, a NumberFormatExcep on is thrown.

SOURCE CODE:-
class AgeExcep on extends Excep on {

public AgeExcep on(String message) {

super(message);

public class AgeValidator {

public sta c void main(String[] args) {

try {

if (args.length != 2) {

throw new IllegalArgumentExcep on("Invalid number of arguments. Please provide

name and age.");

String name = args[0];

int age = Integer.parseInt(args[1]);

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

throw new AgeExcep on("Age should be between 15 and 60.");

System.out.println("Name: " + name);

System.out.println("Age: " + age);


} catch (NumberFormatExcep on e) {

System.err.println("Invalid age format. Please provide a valid integer.");

} catch (AgeExcep on e) {

System.err.println(e.getMessage());

} catch (IllegalArgumentExcep on e) {

System.err.println(e.getMessage());

OUTPUT:-
PROGRAM:-29
AIM:- Create a customized excep on and also make use of all the 5 excep on keywords.

THEORY:-
In Java, excep ons are used to handle excep onal or error condi ons that may arise during the execu on of a
program. Java provides built-in excep on classes for various types of excep ons, but you can also create your
own custom excep ons by extending the Excep on class or one of its subclassesHere's an explana on of the
five excep on keywords used in the program: try: The try block is used to enclose the code that might throw an
excep on. In this case, it wraps the calls to the validateAge method. catch: The catch block is used to handle
the excep ons that may be thrown within the try block. In this program, it catches the InvalidAgeExcep on and
prints the error message. throw: The throw keyword is used to manually throw an excep on. In the validateAge
method, we use throw new InvalidAgeExcep on("Invalid age: " + age); to throw a new instance of the
InvalidAgeExcep on when the age is invalid. throws: The throws keyword is used in a method signature to
declare the types of excep ons that the method may throw. In this program, the validateAge method uses
throws InvalidAgeExcep on to indicate that it can throw an InvalidAgeExcep on. finally: The finally block is
used to specify code that should be executed regardless of whether an excep on is thrown or not. In this
program, it prints a message indica ng that the finally block has been executed.

SOURCE CODE:-
class InvalidAgeExcep on extends Excep on {

InvalidAgeExcep on(String message) {

super(message);

public class AgeValidator {

sta c void validateAge(int age) throws InvalidAgeExcep on {

if (age < 0 || age > 120) {

throw new InvalidAgeExcep on("Invalid age: " + age);

} else {

System.out.println("Valid age: " + age);

public sta c void main(String[] args) {

try {

validateAge(25); // Valid age

validateAge(-5); // Invalid age

} catch (InvalidAgeExcep on e) {

System.out.println("Excep on caught: " + e.getMessage());


} finally {

System.out.println("Finally block executed.");

OUTPUT:-
PROGRAM:-30
AIM:- Write an Applet that displays “Hello World” (Background color -black, text color -blue and your name
in the status window.)

THEORY:-
This applet sets the background color to black in the init() method, then in the paint() method, it sets the text
color to blue and draws the "Hello World" message. In the start() method, it sets the status window to display
your name, and in the stop() method, it clears the status window .

SOURCE CODE:-
import java.applet.Applet;

import java.awt.Color;

import java.awt.Graphics;

public class HelloWorldApplet extends Applet {

public void init() {

setBackground(Color.BLACK);

setForeground(Color.BLUE);

setStatus("Applet developed by Coding Assistant");

public void paint(Graphics g) {

g.drawString("Hello World", 50, 25);

<applet code="HelloWorldApplet.class" width="200" height="50"></applet>

OUTPUT:-
PROGRAM:-31
AIM:- Create a customized excep on and also make use of all the 5 excep on keywords.

THEORY:-
Use Thread.sleep(int) to delay the execu on by entered me in milliseconds. Create a circle for the clock and
label the hours on it. Each hour on the clock is equivalent to 30 degrees. The angle of hours hand from the y=0
line, is ((30*hour)-90) degrees. Each minute on the clock is equivalent to 6 degrees. The angle of minutes hand
from the y=0 line, is ((6*minute)-90) degrees. Each second on the clock is equivalent to 6 degrees. The angle of
seconds hand from the y=0 line, is ((6*second)-90) degrees. To get the posi on of the hands of clock, it is
required to convert the angles to radians. To do this, use Math.toRadians func on. The x co-ordinate of any
point on a circle with center (a,b) and radius ‘r’ measuring an angle θ from the center is given as x = a + r * cosθ
. The y co-ordinate of any point on a circle with center (a,b) and radius ‘r’ measuring an angle θ from the center
is given as y = v + r * sinθ .

SOURCE CODE:-
/*Java Program to Display a Clock using Applet*/

import java.applet.*;

import java.awt.*;

import java.u l.*;

public class Clock extends Applet implements Runnable

Thread t;

//Ini alize the applet

public void init()

setBackground(Color.white);

//Func on to start the thread

public void start()

t = new Thread(this);

t.start();

//Func on to execute the thread

public void run()

while(true)
{

try

repaint();

//Delay by 1 sec

Thread.sleep(1000);

catch(Excep on e)

//Func on to draw the clock

public void paint(Graphics g)

Calendar me = Calendar.getInstance();

int hour = me.get(Calendar.HOUR_OF_DAY) % 12;

int minute = me.get(Calendar.MINUTE);

int second = me.get(Calendar.SECOND);

double angle;

int x,y;

//Draw a circle with center(250,250) & radius=150

g.drawOval(100,100,300,300);

//Label the clock

String s="12";

int i=0;

while(i<12)

angle = Math.toRadians(30*(i-3));

x = 250+(int)(Math.cos(angle)*135);

y = 250+(int)(Math.sin(angle)*135);

g.drawString(s,x,y);

i++;
s=String.valueOf(i);

//Draw the hours hand

g.setColor(Color.green);

angle = Math.toRadians((30*hour)-90);

x = 250+(int)(Math.cos(angle)*100);

y = 250+(int)(Math.sin(angle)*100);

g.drawLine(250,250,x,y);

//Draw the minutes hand

g.setColor(Color.red);

angle = Math.toRadians((6*minute)-90);

x = 250+(int)(Math.cos(angle)*115);

y = 250+(int)(Math.sin(angle)*115);

g.drawLine(250,250,x,y);

//Draw the seconds hand

g.setColor(Color.blue);

angle = Math.toRadians((6*second)-90);

x = 250+(int)(Math.cos(angle)*130);

y = 250+(int)(Math.sin(angle)*130);

g.drawLine(250,250,x,y);

/*

<applet code = Clock.class width=500 height=500>

</applet>

*/
OUTPUT:-
PROGRAM:-32
AIM:- Write a java program to show mul threaded producer and consumer applica on.

THEORY:-
The producer-consumer problem is a classic example of a mul -process synchroniza on

problem. It involves two types of processes: producers and consumers. Producers produce data

items and place them in a shared buffer, while consumers consume the data items from the

same buffer. In a mul threaded environment, the producer-consumer problem can be solved

using shared buffers, semaphores, or monitors. The shared buffer acts as a queue where

producers add data items and consumers remove data items. Semaphores or monitors are used

to ensure mutual exclusion and synchroniza on between producers and consumers, preven ng

race condi ons and ensuring data integrity. The producer-consumer problem can lead to two

poten al issues:

Buffer Underflow: This occurs when a consumer a empts to remove an item from an empty

buffer.

Buffer Overflow: This occurs when a producer a empts to add an item to a full buffer

SOURCE CODE:-
import java.u l.LinkedList;

public class ProducerConsumerExample {

private sta c final int MAX_BUFFER_SIZE = 5;

private sta c final LinkedList<Integer> buffer = new LinkedList<>();

private sta c final Object lock = new Object();

sta c class Producer extends Thread {

@Override

public void run() {

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

synchronized (lock) {

while (buffer.size() == MAX_BUFFER_SIZE) {

try {

System.out.println("Buffer is full. Producer is wai ng...");

lock.wait();

} catch (InterruptedExcep on e) {

e.printStackTrace();
}

buffer.add(i);

System.out.println("Producer produced: " + i);

lock.no fyAll();

sta c class Consumer extends Thread {

@Override

public void run() {

while (true) {

synchronized (lock) {

while (buffer.isEmpty()) {

try {

System.out.println("Buffer is empty. Consumer is wai ng...");

lock.wait();

} catch (InterruptedExcep on e) {

e.printStackTrace();

int value = buffer.removeFirst();

System.out.println("Consumer consumed: " + value);

lock.no fyAll();

public sta c void main(String[] args) {

Producer producer = new Producer();

Consumer consumer = new Consumer();

producer.start();
consumer.start();

OUTPUT:-
PROGRAM:-33
AIM:- Write an applica on that executes two threads. One thread displays “An” every 1000
milliseconds and other displays “B” every 3000 milliseconds. Create the threads by extending the
Thread class.

THEORY:-
In Java, threads can be created by extending the Thread class or implemen ng the Runnable
interface. Extending the Thread class is a straigh orward approach, but it has the limita on that a
class can extend only one class (due to Java's single inheritance nature). Therefore, the Runnable
interface is generally preferred for crea ng threads, as it allows for be er code reusability and
flexibility.In this example, we create two separate thread classes: ThreadA and ThreadB. Each class
extends the Thread class and overrides the run() method, which defines the behavior of the
thread.The sleep() method from the Thread class is used to pause the execu on of a thread for a
specified dura on. It is used here to introduce the desired me delays between the prin ng of "An"
and "B".

SOURCE CODE:-
public class ThreadExample {

public sta c void main(String[] args) {

ThreadA threadA = new ThreadA();

ThreadB threadB = new ThreadB();

threadA.start();

threadB.start();

class ThreadA extends Thread {

@Override

public void run() {

try {

while (true) {

System.out.print("An ");

Thread.sleep(1000); // Pause for 1 second

} catch (InterruptedExcep on e) {

e.printStackTrace();

}
}

class ThreadB extends Thread {

@Override

public void run() {

try {

while (true) {

System.out.print("B ");

Thread.sleep(3000); // Pause for 3 seconds

} catch (InterruptedExcep on e) {

e.printStackTrace();

OUTPUT:-
PROGRAM:-34
AIM:- Create class of SalesPersons as a thread that will display fives 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:-
In Java, the Thread class provides methods like suspend() and resume() to control the execu on of
threads. However, these methods are deprecated since Java 2, version 1.2, as they are inherently
unsafe and can lead to issues like deadlocks or thread starva on. Instead of using suspend() and
resume(), it is recommended to use alterna ve mechanisms like wait/no fy or semaphores for
thread synchroniza on and control. These mechanisms provide a safer and more robust way to
manage thread execu on. Despite being deprecated, this example uses suspend() and resume() for
demonstra on purposes and to fulfill the given requirements.

SOURCE CODE:-
public class ThreadExample {

public sta c void main(String[] args) {

SalesPersons salesPersons = new SalesPersons();

Days days = new Days(salesPersons);

salesPersons.start();

days.start();

class SalesPersons extends Thread {

String[] names = {"John", "Alice", "Bob", "Charlie", "Eve"};

@Override

public void run() {

for (String name : names) {

System.out.println("Salesperson: " + name);

try {

Thread.sleep(1000); // Delay for 1 second

} catch (InterruptedExcep on e) {

e.printStackTrace();

}
}

class Days extends Thread {

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

"Saturday", "Sunday"};

SalesPersons salesPersons;

Days(SalesPersons salesPersons) {

this.salesPersons = salesPersons;

@Override

public void run() {

for (String day : daysOfWeek) {

System.out.println("Day: " + day);

if (day.equals("Sunday")) {

System.out.println("Suspending SalesPersons thread...");

salesPersons.suspend();

} else if (day.equals("Wednesday")) {

System.out.println("Resuming SalesPersons thread...");

salesPersons.resume();

try {

Thread.sleep(2000); // Delay for 2 seconds

} catch (InterruptedExcep on e) {

e.printStackTrace();

}
OUTPUT:-
PROGRAM:-35
AIM:- : WAP in java that illustrates how to process mouse click, enter,exit, press and release
events.The background colorchanges when the mouse isentered, clicked, pressed,released or exited.

THEORY:-
MouseListener and MouseMo onListener is an interface in java.awt.event package. Mouse

events are of two types. MouseListener handles the events when the mouse is not in mo on.

While MouseMo onListener handles the events when mouse is in mo on. There are five

types of events that MouseListener can generate. There are five abstract func ons that

represent these five events. The abstract func ons are :

1. void mouseReleased(MouseEvent e) : Mouse key is released

2. void mouseClicked(MouseEvent e) : Mouse key is pressed/released

3. void mouseExited(MouseEvent e) : Mouse exited the component

4. void mouseEntered(MouseEvent e) : Mouse entered the component

5. void mousepressed(MouseEvent e) : Mouse key is pressed

SOURCE CODE:-
import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class MouseEventsDemo {

public sta c void main(String[] args) {

JFrame frame = new JFrame("Mouse Events Demo");

JPanel panel = new JPanel();

JLabel label = new JLabel("No event");

MouseListener mouseListener = new MouseListener() {

public void mousePressed(MouseEvent e) {

label.setText("Mouse pressed at point: " + e.getX() + ", " + e.getY());

public void mouseReleased(MouseEvent e) {

label.setText("Mouse released at point: " + e.getX() + ", " + e.getY());

public void mouseExited(MouseEvent e) {

label.setText("Mouse exited through point: " + e.getX() + ", " + e.getY());


}

public void mouseEntered(MouseEvent e) {

label.setText("Mouse entered at point: " + e.getX() + ", " + e.getY());

public void mouseClicked(MouseEvent e) {

label.setText("Mouse clicked at point: " + e.getX() + ", " + e.getY() +

" (click count: " + e.getClickCount() + ")");

};

frame.add(panel);

panel.add(label);

frame.addMouseListener(mouseListener);

frame.setSize(400, 300);

frame.setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

OUTPUT:-
PROGRAM:-37
AIM:- : Write a program that read from a file and write to file.
THEORY:-
Reading from and wri ng to files is a common task in programming, especially for handling

data persistence. In Java, file reading and wri ng can be accomplished using various classes

from the java.io package. Here's a brief overview of the main classes used in the program:

FileReader: This class is used to read characters from a file. It is typically wrapped in a

BufferedReader for efficient reading of text from a character-input stream.

BufferedReader: This class reads text from a character-input stream, buffering characters to

provide efficient reading of characters, arrays, and lines.

FileWriter: This class is used to write characters to a file. It is typically wrapped in a

BufferedWriter for efficient wri ng of text to a character-output stream.

BufferedWriter: This class writes text to a character-output stream, buffering characters to

provide efficient wri ng of characters, arrays, and lines.

SOURCE CODE:-
import java.io.*;

public class FileReadWrite {

public sta c void main(String[] args) {

String inputFile = "input.txt";

String outputFile = "output.txt";

try {

FileReader fileReader = new FileReader(inputFile);

BufferedReader bufferedReader = new BufferedReader(fileReader);

FileWriter fileWriter = new FileWriter(outputFile);

BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

String line;

while ((line = bufferedReader.readLine()) != null) {

bufferedWriter.write(line);

bufferedWriter.newLine();

bufferedReader.close();
bufferedWriter.close();

System.out.println("File reading and wri ng completed.");

} catch (FileNotFoundExcep on ex) {

System.out.println("Unable to open file '" + inputFile + "'");

} catch (IOExcep on ex) {

System.out.println("Error reading or wri ng file '" + inputFile + "'");

OUTPUT:-
PROGRAM:-38
AIM:- Convert the content of a given file into the uppercase content of the same file. JDBC
(Database connec vity with MS-Access).

THEORY:-
JDBC (Java Database Connec vity) is an API that provides Java programs the capability to interact
with databases. To connect to an MS-Access database using JDBC, you need to specify the database
URL (jdbc:ucanaccess://path/to/your/database.accdb), username, and password. Use
DriverManager.getConnec on() to establish a connec on. Use Prepared Statement to execute SQL
queries and update the content of the file in the database.

SOURCE CODE:-
import java.io.*;

public class FileToUpperAndUpdate {

public sta c void main(String[] args) {

String filePath = "test.txt";

try {

FileInputStream fis = new FileInputStream(filePath);

BufferedReader br = new BufferedReader(new InputStreamReader(fis));

StringBuilder contentBuilder = new StringBuilder();

String line;

while ((line = br.readLine()) != null) {

contentBuilder.append(line).append("\n");

String fileContent = contentBuilder.toString();

fis.close();

String upperCaseContent = fileContent.toUpperCase();

FileOutputStream fos = new FileOutputStream(filePath);

fos.write(upperCaseContent.getBytes());

fos.close();

System.out.println("File content converted to uppercase and updated successfully.");

} catch (IOExcep on e) {

System.out.println("Error: " + e.getMessage());

}
}

OUTPUT:-
PROGRAM:-39
AIM:- Create runnable jar file in java.
THEORY:-
A JAR (Java Archive) file is a package file format used to bundle mul ple Java class files, along with
associated metadata and resources (such as images, configura on files, etc.) into a single archive. JAR
files are essen al for distribu ng Java applica ons and libraries, as they allow you to package all the
necessary components into a single file.

To create a runnable JAR file, you need to specify the entry point (the main class with the main
method) and include all the required dependencies (other class files and libraries) within the JAR file.
This way, the JAR file can be executed directly without requiring addi onal setup or classpath
configura on.

SOURCE CODE:-
public class HelloWorld {

public sta c void main(String[] args) {

System.out.println("Hello, World!");

javac HelloWorld.java

Main-Class: HelloWorld

jar cvfm HelloWorld.jar MANIFEST.MF HelloWorld.class

OUTPUT:-
PROGRAM:-40
AIM:- Develop Scien fic Calculator using Swing.

THEORY:-
Swing: Swing is a GUI toolkit for Java. It provides a set of components for building graphical

user interfaces and is pla orm-independent.

JFrame: JFrame is a class in Swing that represents a window with decora ons such as borders,

tle, and bu ons for closing, minimizing, and maximizing the window.

JPanel: JPanel is a container that can hold other components. It is used to organize components

within a window.

JTextField: JTextField is a text component that allows the user to enter and edit a single line of

text.

JBu on: JBu on is a component that represents a clickable bu on. It is used to trigger ac ons

when clicked.

Ac onListener: Ac onListener is an interface that defines a single method

ac onPerformed(Ac onEvent e) which is called when an ac on occurs, such as clicking a

bu on.
SOURCE CODE:-
import javax.swing.*;

import java.awt.*;

import java.awt.event.Ac onEvent;

import java.awt.event.Ac onListener;

public class Scien ficCalculator extends JFrame implements Ac onListener {

private sta c final long serialVersionUID = 1L;

private JTextField textField;

private double firstNumber, secondNumber, result;

private String operator;

public Scien ficCalculator() {

setTitle("Scien fic Calculator");

setSize(400, 400);

setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

panel.setLayout(new GridLayout(5, 4));


textField = new JTextField();

textField.setEditable(false);

panel.add(textField);

String[] bu ons = {

"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+", "sin", "cos",

"tan", "sqrt"

};

for (String bu on : bu ons) {

JBu on btn = new JBu on(bu on);

btn.addAc onListener(this);

panel.add(btn);

add(panel);

setVisible(true);

public void ac onPerformed(Ac onEvent e) {

String ac on = e.getAc onCommand();

if (ac on.equals("sin") || ac on.equals("cos") || ac on.equals("tan") ||

ac on.equals("sqrt")) {

double value = Double.parseDouble(textField.getText());

switch (ac on) {

case "sin":

result = Math.sin(value);

break;

case "cos":

result = Math.cos(value);

break;

case "tan":

result = Math.tan(value);

break;

case "sqrt":

result = Math.sqrt(value);

break;
}

textField.setText(String.valueOf(result));

} else if (ac on.equals("=")) {

secondNumber = Double.parseDouble(textField.getText());

switch (operator) {

case "+":

result = firstNumber + secondNumber;

break;

case "-":

result = firstNumber - secondNumber;

break;

case "*":

result = firstNumber * secondNumber;

break;

case "/":

result = firstNumber / secondNumber;

break;

textField.setText(String.valueOf(result));

} else {

if (textField.getText().equals("")) {

firstNumber = 0;

} else {

firstNumber = Double.parseDouble(textField.getText());

operator = ac on;

textField.setText("");

public sta c void main(String[] args) {

new Scien ficCalculator();

}
OUTPUT:-

You might also like