Java File Harshit
Java File Harshit
•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.
• 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
• 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]);
• 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]);
• Output:
Harshit 37714802724
EXPERIMENT - 04
• 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 {
int a = 5;
int b = 10;
[Link]("Before swapping:");
a = a ^ b;
b = a ^ b;
a = a ^ b;
[Link]("After swapping:");
• 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
• 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 {
// Stack
[Link](10);
[Link](20);
[Link](30);
[Link]();
// Queue
[Link](1);
[Link](2);
[Link](3);
Harshit 37714802724
[Link]("Queue: " + queue);
[Link]();
• 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 {
[Link]("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 :
• Source Code:
class AreaCalculator {
// Rectangle
return l * b;
// Circle
return 3.14 * r * r;
// Triangle
Harshit 37714802724
return 0.5 * base * height;
• 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;
}
}
Harshit 37714802724
Box b = new Box(w, h, d);
• Output :
Harshit 37714802724
EXPERIMENT - 11
• 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;
void display() {
[Link]("ID: " + id + ", Name: " + name);
}
}
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);
}
[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;
}
• Output:
Harshit 37714802724
EXPERIMENT - 14
• Theory:
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:
• Source Code :
•
class Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
• Output :
Harshit 37714802724
EXPERIMENT - 15
• 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() {
void bark() {
[Link]("Dog barks");
[Link]();
[Link]();
}
Harshit 37714802724
• Output :
Harshit 37714802724
EXPERIMENT - 16
• 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");
}
}
Output :
Harshit 37714802724
EXPERIMENT - 17
• Theory :
The super keyword is used to refer to the immediate parent class. It is used to:
• Source Code :
class Animal {
String name = "Animal";
Animal() {
[Link]("Animal constructor");
}
void display() {
[Link]("This is Animal class");
}
}
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
}
}
Harshit 37714802724
}
• Output :
Harshit 37714802724
EXPERIMENT - 18
• 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();
[Link]("Dog barks");
[Link]("Cat meows");
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 :
void area() {
[Link]("Area of Rectangle: " + (length * breadth));
}
}
void area() {
[Link]("Area of Triangle: " + (0.5 * base * height));
}
}
s = new Rectangle();
[Link]();
s = new Triangle();
[Link]();
}
}
Harshit 37714802724
• Output :
Harshit 37714802724
EXPERIMENT - 20
• 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.
• Source Code :
interface Animal {
void sound();
[Link]("Dog barks");
[Link]("Cat meows");
Harshit 37714802724
public static void main(String[] args) {
Animal a;
a = new Dog();
[Link]();
a = new Cat();
[Link]();
• Output :
Harshit 37714802724
EXPERIMENT - 21
• Theory :
• Source Code :
interface Vehicle {
void start();
}
• 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,
• 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.
• Source Code :
interface Playable {
void play();
[Link]("Playing Veena");
Harshit 37714802724
public void play() {
[Link]("Playing Saxophone");
[Link]();
[Link]();
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];
InvalidAgeException(String msg) {
super(msg);
try {
Harshit 37714802724
if (age < 15 || age >= 60) {
} catch (InvalidAgeException e) {
} catch (Exception e) {
[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 :
MyException(String msg) {
super(msg);
if (num < 0) {
} else {
[Link]("Valid number");
try {
check(-5);
} catch (MyException e)
Harshit 37714802724
Harshit 37714802724
[Link]("Caught Exception: " + [Link]());
} finally {
• 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].*;
[Link]([Link]);
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].*;
Thread t;
setBackground([Link]);
t = new Thread(this);
[Link]();
while (true) {
Harshit 37714802724
try {
[Link](1000);
} catch (InterruptedException e) {}
[Link](x - r, y - r, 2 * r, 2 * r);
// Draw numbers
numY);
Harshit 37714802724
int second = [Link]([Link])
// Calculate angles
// Draw hands
}
// Calculate angles
// Draw hands
Harshit 37714802724
drawHand(g, x, y, minAngle, r - 20); // minute
Output:
Harshit 37714802724
Harshit 37714802724
EXPERIMENT - 27
• Aim : Write a java program to show multithreaded producer and consumer application.
• Theory :
• Source Code :
class Buffer {
int data;
try {
while (available)
wait();
data = value;
available = true;
notify();
} catch (Exception e) {}
try {
while (!available)
wait();
Harshit 37714802724
[Link]("Consumed: " + data);
available = false;
notify();
} catch (Exception e) {}
Buffer b;
Producer(Buffer b) {
this.b = b;
[Link](i);
Buffer b;
Consumer(Buffer b) {
Harshit 37714802724
this.b = b;
[Link]();
[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 :
• Source Code :
try {
[Link]("Thread 1 running");
[Link](1000);
} catch (Exception e) {}
try {
[Link]("Thread 2 running");
[Link](3000);
} catch (Exception e) {}
Harshit 37714802724
}
[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 :
try {
[Link](1000);
} catch (Exception e) {}
SalesPersons sp;
Days(SalesPersons sp) {
[Link] = sp;
Harshit 37714802724
}
try {
if ([Link]("Sunday")) {
[Link]("Suspending SalesPersons...");
[Link]();
if ([Link]("Wednesday")) {
[Link]("Resuming SalesPersons...");
[Link]();
[Link](1000);
} catch (Exception e) {}
Harshit 37714802724
public class Main {
[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].*;
MouseEventDemo() {
setSize(400, 300);
setVisible(true);
addMouseListener(this);
addWindowListener(new WindowAdapter() {
[Link](0);
});
}
public void mouseEntered(MouseEvent e) {
setBackground([Link]);
Harshit 37714802724
}
setBackground([Link]);
setBackground([Link]);
setBackground([Link]);
setBackground([Link]);
new MouseEventDemo();
• Output :
Harshit 37714802724
EXPERIMENT - 31
• Aim : WAP that displays your name whenever the mouse is clicked.
• Theory :
• Source Code :
import [Link].*;
import [Link].*;
MouseNameDisplay() {
setSize(400, 300);
setVisible(true);
addMouseListener(this);
addWindowListener(new WindowAdapter() {
[Link](0);
});
Harshit 37714802724
[Link](new Font("Arial", [Link], 20));
message = “Yeshika”;
repaint();
new MouseNameDisplay();
• Output :
Harshit 37714802724