[go: up one dir, main page]

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

Ankit Oops

The document is an index of Java programming exercises, detailing various tasks such as printing messages, understanding variables, implementing object-oriented concepts, and handling exceptions. Each program includes a brief objective and source code examples. The exercises cover fundamental programming concepts, including arrays, inheritance, polymorphism, and multithreading.
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 views84 pages

Ankit Oops

The document is an index of Java programming exercises, detailing various tasks such as printing messages, understanding variables, implementing object-oriented concepts, and handling exceptions. Each program includes a brief objective and source code examples. The exercises cover fundamental programming concepts, including arrays, inheritance, polymorphism, and multithreading.
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
You are on page 1/ 84

INDEX

S.N Name of the Program Page No Sign

1 Write a program in Java to print Hello

2 Write a program in java to understand the difference


between print () and println ()
3 Write a program in Java with two classes create a object of
first class and call into another class (having main method)
4 Write a program in java to product of two numbers

5 Write a program in java product of two numbers (Input by


the user)
6 Write a program in java to illustrate the concept of local,
instance and static variable
7 Write a program in java to implement implicit and explicit type
casting
8 Write a program in java to implement the various operators
in java
9 Write a program in Java for constructor overloading
10 Write a program in Java for method overloading
11 Write a program in Java for method overriding

12 Write a program in java to show run time polymorphism (up


casting)
13 Write a program in java for access specifiers (all four)

14 Write a program in java to implement the single dimension


array
15 Write a program in java to copy the elements from one array
to another array.
16 Write a program in java to perform the addition and
multiplication in 2-D array
17 Write a program in Java for simple inheritance
18 Write a program in java for Final keyword
19 Write a program in java for super keyword
20 Write a program in Java chaining constructor

21 Write a program in Java for abstract method and abstract class

22 Write a program in Java for interface


23 Write a program in Java multiple inheritance

24 Write a program in Java for Object Cloning (shallow and


deep copy)
25 Write a program in Java for Inner Classes (all types)

26 Write a program in java to create the package (user defined


package)

1
ANKIT KUMAR 240097140030
27 Write a program in Java for exception handling by using try,
catch and finally
28 Write a program in Java for throw and throws Exception

29 Write a program in Java to throw your own Exceptions

30 Write a program in Java to reading and writing in file using


byte stream

31 Write a program in Java to reading and writing in file using


character stream.

32 Write a program in Java to reading and writing through


console class.

33 Write a program in Java how to create thread using Thread Class.

34 Write a program in Java how to create thread using runnable


interface.

35 Write a program in Java to implement the multithreading.

36 Write a program in Java to achieve synchronization in threads.

37 Write a program in Java to implement the concept of


Priorities in threads.

38 Write a program in Java to illustrate the concept of Generic


Programming

39 Write a program in Java to illustrate the concept of event


handling (using various event handlers)

40 Create a simple student registration application using various


swing components (like: JFrame, JButton, JLabel,
text fields, text areas, check box and radio buttons).

2
ANKIT KUMAR 240097140030
Program No. 1

Objective: Write a program in Java to print Hello.


Source Code:
public class HelloWorld
{
public static void main(String[] args)
{
// Output statement
System.out.println("Hello");
}
}

Output:

3
ANKIT KUMAR 240097140030
Program No. 2

Objective: Write a program in Java to understand the difference between print () and
println ().
Source Code:
public class abc
{
public static void main(String[] args)
{
// using print method
System.out.print("Galgotias");
// using print method
System.out.print(" College");
// Moving to the next line
System.out.println();
// using println method
System.out.println("Galgotias");
// using println method
System.out.println(" College");
}
}

Output:

4
ANKIT KUMAR 240097140030
Program No. 3

Objective: Write a program in Java with two classes create a object of first class and
call into another class (having main method).
Source Code:
class Myclass {
// Method in the first class
public void displayMessage(String message)
{
System.out.println(message);
}
}
// Second class with the main method
public class MainClass {

public static void main(String[] args) {


// Create an object of the first class
MyClass obj = new MyClass();
// Call the method of the first class using the object

obj.displayMessage("How are you ?");

}
}

Output:

5
ANKIT KUMAR 240097140030
Program No. 4

Objective: Write a program in java to find product of two numbers


Source Code:
public class ProductOfTwoNumbers
{
public static void main(String[] args)
{
int num1 = 10;
int num2 = 20;
int product = num1 * num2;
System.out.println("The product of " + num1 + " and " + num2 + " is: " + product);
}
}

Output:

6
ANKIT KUMAR 240097140030
Program No. 5

Objective: Write a program in java to find product of two numbers(input by user).


Source Code:
import java.util.Scanner;
public class product

{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter the value of the first number ::");
int a = sc.nextInt();
System.out.println("Enter the value of the first number ::");
int b = sc.nextInt();
int result = a*b;
System.out.println("Product of the given two numbers is ::"+result);
}
}

Output:

7
ANKIT KUMAR 240097140030
Program No. 6

Objective: Write a program in java to illustrate the concept of local, instance and static
variable.
Source Code:
public class VariableExample
{
// Static variable (class variable)
static int staticVar = 150;
// Instance variable
int instanceVar = 100;
// Method to demonstrate local variable
public void myMethod() {
// Local variable
int localVar = 20;
System.out.println("Local Variable: " + localVar);
System.out.println("Instance Variable (inside method): " + instanceVar);
System.out.println("Static Variable (inside method): " + staticVar);

}
public static void main(String[] args) {
VariableExample obj1 = new VariableExample();
VariableExample obj2 = new VariableExample();
System.out.println("Object 1");
obj1.myMethod();
System.out.println("Instance Variable (obj1): " + obj1.instanceVar);
System.out.println("Static Variable: " + VariableExample.staticVar);
System.out.println("\n Object 2");

obj2.myMethod();
System.out.println("Instance Variable (obj2): " + obj2.instanceVar);

8
ANKIT KUMAR 240097140030
System.out.println("Static Variable: " + VariableExample.staticVar);
System.out.println("\n Modifying Variables");
obj1.instanceVar = 75;
VariableExample.staticVar = 200;
System.out.println("Instance Variable (obj1) after modification: " + obj1.instanceVar);
System.out.println("Instance Variable (obj2) after modification: " + obj2.instanceVar);
System.out.println("Static Variable after modification: " + VariableExample.staticVar);
}
}

Output:

9
ANKIT KUMAR 240097140030
Program No. 7

Objective: Write a program in java to implement implicit and explicit type casting.
Source Code:
public class TypeCastingExample {
public static void main(String[] args)
{
int intValue = 100;
long longValue = intValue; // int is automatically converted to long
float floatValue = longValue; // long is automatically converted to float
double doubleValue = floatValue; // float is automatically converted to double
System.out.println("Implicit Type Casting:");
System.out.println("int value: " + intValue);
System.out.println("long value: " + longValue);
System.out.println("float value: " + floatValue);
System.out.println("double value: " + doubleValue);

double anotherDoubleValue = 99.99;


int anotherIntValue = (int) anotherDoubleValue;
System.out.println("\nExplicit Type Casting:");
System.out.println("double value: " + anotherDoubleValue);
System.out.println("int value: " + anotherIntValue);
}
}

10
ANKIT KUMAR 240097140030
Program No. 8

Objective: Write a program in java to implement the various operators in Java.


Source Code:
public class Operators
{
public static void main(String[] args)
{
// Arithmetic Operators
int num1 = 20, num2 = 10;
System.out.println("Addition: " + (num1 + num2));
System.out.println("Subtraction: " + (num1 - num2));
System.out.println("Multiplication: " + (num1 * num2));
System.out.println("Division: " + (num1 / num2));
System.out.println("Modulus: " + (num1 % num2));
// Unary Operators
int num3 = 5;
System.out.println("Increment: " + (++num3));
System.out.println("Decrement: " + (--num3));
System.out.println("Negation: " + (-num3));
// Relational Operators
System.out.println("Equal to: " + (num1 == num2));
System.out.println("Not equal to: " + (num1 != num2));
System.out.println("Greater than: " + (num1 > num2));
System.out.println("Less than: " + (num1 < num2));
System.out.println("Greater than or equal to: " + (num1 >= num2));
System.out.println("Less than or equal to: " + (num1 <= num2));
// Logical Operators
boolean bool1 = true, bool2 = false;
System.out.println("AND: " + (bool1 && bool2));
System.out.println("OR: " + (bool1 || bool2));
System.out.println("NOT: " + (!bool1));
// Assignment Operators
int num4 = 5;
11
ANKIT KUMAR 240097140030
num4 += 5;
System.out.println("Add and assign: " + num4);
num4 -= 5;
System.out.println("Subtract and assign: " + num4);
num4 *= 5;
System.out.println("Multiply and assign: " + num4);
num4 /= 5;
System.out.println("Divide and assign: " + num4);
num4 %= 2;
System.out.println("Modulus and assign: " + num4);
// Conditional/Ternary Operator
int num5 = (num1 > num2) ? num1 : num2;
System.out.println("Ternary operator: " + num5);
}
}

Output:

12
ANKIT KUMAR 240097140030
Program No. 9

Objective: Write a program in Java for constructor overloading


Source Code:
class Box
{
double width, height, depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Box() { width = height = depth = 0; }
Box(double len) { width = height = depth = len; }
double volume() { return width * height * depth; }
}
public class Test {
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
13
ANKIT KUMAR 240097140030
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output:

14
ANKIT KUMAR 240097140030
Program No. 10

Objective: Write a program in Java for method overloading.


Source Code:
public class Sum
{
// Overloaded sum()
public int sum(int x, int y) { return (x + y); }
// Overloaded sum()
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum()
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

15
ANKIT KUMAR 240097140030
Output:

16
ANKIT KUMAR 240097140030
Program No. 11

Objective: Write a program in Java for method overriding.


Source Code:
class Animal
{
void sound()
{
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal
{
// Overriding the sound() method of Animal
@Override
void sound()
{
System.out.println("Dog barks");
}
}
public class MethodOverridingExample
{
public static void main(String[] args)
{
Animal a = new Animal();
a.sound();
Dog d = new Dog();
d.sound();
}
}

17
ANKIT KUMAR 240097140030
Output:

18
ANKIT KUMAR 240097140030
Program No. 12

Objective: Write a program in java to show run time polymorphism (up casting).
Source Code:
class Shape
{
void draw()
{
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
void draw()
{
System.out.println("Drawing a circle");
}
}
class Rectangle extends Shape
{
@Override
void draw()
{
System.out.println("Drawing a rectangle");
}
}
public class RuntimePolymorphismDemo
{
public static void main(String[] args)
{

19
ANKIT KUMAR 240097140030
Shape s;
s = new Circle();
s.draw();
s = new Rectangle();
s.draw();
}
}
Output:

20
ANKIT KUMAR 240097140030
Program No. 13

Objective: Write a program in java for access specifiers (all four)


Source Code:
class AccessSpecifierExample
{
private int privateVar = 10;
int defaultVar = 20;
protected int protectedVar = 30;
public int publicVar = 40;
// method to display all variables
public void display() {
System.out.println("Private Variable: " + privateVar);
System.out.println("Default Variable: " + defaultVar);
System.out.println("Protected Variable: " + protectedVar);
System.out.println("Public Variable: " + publicVar);

}
}
public class TestAccessSpecifiers {
public static void main(String[] args) {
AccessSpecifierExample obj = new AccessSpecifierExample();
System.out.println("Default Variable: " + obj.defaultVar);
System.out.println("Protected Variable: " + obj.protectedVar);
System.out.println("Public Variable: " + obj.publicVar);
obj.display();

}
}

21
ANKIT KUMAR 240097140030
Output:

22
ANKIT KUMAR 240097140030
Program No. 14

Objective: Write a program in java to implement the single dimension array.


Source Code:
public class ArrayExample
{
public static void main(String[] args)
{
// Declare and initialize a single-dimensional array
int[] numbers = {10, 20, 30, 40, 50};
// Display array elements using a for loop
System.out.println("Array elements are:");
for (int i = 0; i < numbers.length; i++)

{
System.out.println(numbers[i]);
}
}
}

Output:

23
ANKIT KUMAR 240097140030
Program No. 15

Objective: Write a program in java to copy the elements from one array to another
array.
Source Code:
public class CopyArrayExample
{
public static void main(String[] args)
{
int[] originalArray = {1, 2, 3, 4, 5};
int[] copiedArray = new int[originalArray.length];
// Copy elements one by one
for (int i = 0; i < originalArray.length; i++)
{
copiedArray[i] = originalArray[i];
}
System.out.print("Original array: ");
for (int i = 0; i < originalArray.length; i++)
{
System.out.print(originalArray[i] + " ");
}
System.out.print("\nCopied array: ");
for (int i = 0; i < copiedArray.length; i++)

{
System.out.print(copiedArray[i] + " ");
}
}
}

24
ANKIT KUMAR 240097140030
Output:

25
ANKIT KUMAR 240097140030
Program No. 16

Objective: Wap in java to perform the addition and multiplication in 2-D array.
SOURCE CODE:
public class MatrixOperations

public static void main(String[] args)

int[][] A = {1, 2, 3},{4, 5, 6}};

int[][] B = {{7, 8, 9},{10, 11, 12} };

// Addition of matrices

int[][] sum = new int[2][3];

for (int i = 0; i < 2; i++)

for (int j = 0; j < 3; j++)

sum[i][j] = A[i][j] + B[i][j];

System.out.println("Addition of matrices:");

printMatrix(sum);

// Multiplication (Matrix A 2x3 * Transpose of B 3x2 to get 2x2 result)

int[][] B_T = {{7, 10},{8, 11}, {9, 12}};

int[][] product = new int[2][2];

for (int i = 0; i < 2; i++)

for (int j = 0; j < 2; j++)

product[i][j] = 0;

for (int k = 0; k < 3; k++)

26
ANKIT KUMAR 240097140030
{

product[i][j] += A[i][k] * B_T[k][j];

System.out.println("Multiplication of matrices (A x B_T):");

printMatrix(product);

// Method to print a matrix

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

for (int[] row : matrix)

for (int val : row)

System.out.print(val + "\t");

System.out.println();

27
ANKIT KUMAR 240097140030
OUTPUT:
Addition of matrices:

8 10 12
14 16 18

Multiplication of matrices (A x B_T):


50 68
122 167

28
ANKIT KUMAR 240097140030
Program 17.
Objective: Wap in java for simple inheritance.
SOURCE CODE:

// Parent class
class Animal
{
void eat()
{
System.out.println("This animal eats food.");
}
}
// Child class
class Dog extends Animal
{
void bark()
{
System.out.println("The dog barks.");
}
}
// Main class
public class SimpleInheritance
{
public static void main(String[] args)
{
Dog myDog = new Dog();
// Calling method of parent class using child object
myDog.eat();
// Calling method of child class

29
ANKIT KUMAR 240097140030
myDog.bark();
}
}
OUTPUT:
This animal eats food.
The dog barks.

30
ANKIT KUMAR 240097140030
Program 18.
Objective: Wap in java for final keyword.
SOURCE CODE:

// Demonstration of final keyword in Java


class FinalDemo
{
// final variable
final int value = 100;
// final method
final void displayMessage()
{
System.out.println("This is a final method.");
}
// Uncommenting below will cause compile-time error
/*
void displayMessage()
{
System.out.println("Trying to override final method.");
}
*/
}
// Subclass
class SubFinalDemo extends FinalDemo
{
// Cannot override final method from FinalDemo
void showValue()

{
System.out.println("Final variable value is: " + value);

31
ANKIT KUMAR 240097140030
// Uncommenting below will cause compile-time error

// value = 200;
}
}
// Main class
public class FinalKeywordExample
{
public static void main(String[] args)
{
SubFinalDemo obj = new SubFinalDemo();
obj.displayMessage();
obj.showValue();
}
}
OUTPUT:
This is a final method.
Final variable value is: 100

32
ANKIT KUMAR 240097140030
Program 19.
Objective: Wap in java for super keyword.
SOURCE CODE:
class Animal
{
void sound()
{
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal
{
void sound()
{
super.sound(); // Calls the sound() method of Animal class
System.out.println("Dog barks");

}
}
public class TestSuper
{
public static void main(String[] args)
{
Dog dog = new Dog();
dog.sound();
}
}

33
ANKIT KUMAR 240097140030
OUTPUT:

Animal makes a sound


Dog barks

34
ANKIT KUMAR 240097140030
Program 20.
Objective: Wap in java chaining constructor.
SOURCE CODE:
class Employee
{
String name;
int id;
double salary;
// Constructor with no arguments
Employee()
{
this("Unknown", 0, 0.0); // Calls the parameterized constructor
System.out.println("No-argument constructor called.");

}
// Constructor with one argument
Employee(String name)

{
this(name, 0, 0.0); // Calls the parameterized constructor
System.out.println("Constructor with one argument called.");
}
// Constructor with two arguments
Employee(String name, int id)
{
this(name, id, 0.0); // Calls the parameterized constructor
System.out.println("Constructor with two arguments called.");
}
// Constructor with three arguments
Employee(String name, int id, double salary)

35
ANKIT KUMAR 240097140030
{
this.name = name;
this.id = id;
this.salary = salary;

System.out.println("Constructor with three arguments called.")


}
void display()
{
System.out.println("Employee Name: " + name);
System.out.println("Employee ID: " + id);
System.out.println("Employee Salary: " + salary);

}
}
public class TestConstructorChaining
{
public static void main(String[] args)
{

System.out.println("Creating employee1:");
Employee employee1 = new Employee();
employee1.display();
System.out.println("\nCreating employee2:");
Employee employee2 = new Employee("Alice");
employee2.display();
System.out.println("\nCreating employee3:");
Employee employee3 = new Employee("Bob", 101);
employee3.display();
System.out.println("\nCreating employee4:");

Employee employee4 = new Employee("Charlie", 102, 50000.0);

36
ANKIT KUMAR 240097140030
employee4.display();
}
}
OUTPUT:
Creating employee1:
Constructor with three arguments called.
No-argument constructor called.

Employee Name: Unknown


Employee ID: 0

Employee Salary: 0.0


Creating employee2:
Constructor with three arguments called.
Constructor with one argument called.
Employee Name: Alice
Employee ID: 0
Employee Salary: 0.0
Creating employee3:
Constructor with three arguments called.
Constructor with two arguments called.
Employee Name: Bob
Employee ID: 101
Employee Salary: 0.0
Creating employee4:
Constructor with three arguments called.
Constructor with three arguments called.
Employee Name: Charlie
Employee ID: 102
Employee Salary: 50000.0

37
ANKIT KUMAR 240097140030
Program 21.
Objective: Wap in java for abstract method and abstract class.
SOURCE CODE:

// Abstract class
abstract class Animal
{
// Abstract method (no body)
public abstract void sound();
// Regular method
public void sleep()
{
System.out.println("This animal is sleeping.");
}
}
// Dog class that extends Animal
class Dog extends Animal
{
// Providing implementation for abstract method
public void sound()
{
System.out.println("The dog says: Bark");
}
}
// Cat class that extends Animal
class Cat extends Animal

{
// Providing implementation for abstract method
public void sound()

38
ANKIT KUMAR 240097140030
{
System.out.println("The cat says: Meow");
}
}
// Main class to test the abstract class and its implementation
public class AbstractClassExample
{

public static void main(String[] args)


{

// Creating instances of Dog and Cat


Animal myDog = new Dog();
Animal myCat = new Cat();

// Calling the abstract method implemented by subclasses


myDog.sound(); // Output: The dog says: Bark
myCat.sound(); // Output: The cat says: Meow
// Calling the regular method from the abstract class
myDog.sleep(); // Output: This animal is sleeping.
myCat.sleep(); // Output: This animal is sleeping.

}
}
OUTPUT:
The dog says: Bark
The cat says: Meow
This animal is sleeping.
This animal is sleeping.

39
ANKIT KUMAR 240097140030
Program 22.
Objective: Wap in java for interface.
SOURCECODE:

// Define the interface


interface Animal
{
void sound(); // Abstract method
}
// Implement the interface in the Dog class
class Dog implements Animal
{
@Override
public void sound()
{
System.out.println("The dog barks");
}
}

// Implement the interface in the Cat class


class Cat implements Animal
{
@Override
public void sound()
{
System.out.println("The cat meows");
}
}
// Main class to test the interface implementation
public class TestInterface

40
ANKIT KUMAR 240097140030
{
public static void main(String[] args)
{
Animal myDog = new Dog(); // Create a Dog object
Animal myCat = new Cat(); // Create a Cat object
myDog.sound(); // Output: The dog barks
myCat.sound(); // Output: The cat meows

}
}
OUTPUT:
The dog barks
The cat meows

41
ANKIT KUMAR 240097140030
Program 23.
Objective: WAP IN JAVA MULTIPLE INHERITANCE.
SOURCE CODE:
// Interface for animal behavior
interface Animal

{
void eat();
}
// Interface for vehicle behavior
interface Vehicle

{
void drive();
}
// Class that implements both Animal and Vehicle interfaces
class AmphibiousVehicle implements Animal, Vehicle

{
public void eat()
{
System.out.println("This amphibious vehicle can eat.");
}
public void drive()
{
System.out.println("This amphibious vehicle can drive.");
}
}
public class TestMultipleInheritance
{
public static void main(String[] args)

42
ANKIT KUMAR 240097140030
{
AmphibiousVehicle av = new AmphibiousVehicle();
av.eat(); // Output: This amphibious vehicle can eat.
av.drive(); // Output: This amphibious vehicle can drive.

}
}
OUTPUT:
This amphibious vehicle can eat.
This amphibious vehicle can drive.

43
ANKIT KUMAR 240097140030
Program 24.
Objective: Wap in java for object cloning(SHALLOW AND DEEP COPY)
SOURCE CODE:

// Address class representing an address


class Address
{
String city;
Address(String city)

{
this.city = city;
}
}
// Person class representing a person with a name, age, and address
class Person implements Cloneable
{

String name;
int age;
Address address;
Person(String name, int age, Address address)
{
this.name = name;
this.age = age;
this.address = address;

}
// Overriding clone() method to perform shallow copy
@Override

protected Object clone() throws CloneNotSupportedException


{

44
ANKIT KUMAR 240097140030
return super.clone();
}
// Deep copy constructor
public Person(Person other)
{
this.name = other.name;
this.age = other.age;
this.address = new Address(other.address.city);
}
@Override
public String toString()
{
return "Person{name='" + name + "', age=" + age + ", address=" + address.city + "}";
}
}
public class ObjectCloningExample
{

public static void main(String[] args)


{
try
{
// Original Address and Person objects
Address originalAddress = new Address("New York");
Person originalPerson = new Person("Alice", 30, originalAddress);
// Shallow copy using clone()
Person shallowCopy = (Person) originalPerson.clone();
// Deep copy using copy constructor
Person deepCopy = new Person(originalPerson);

45
ANKIT KUMAR 240097140030
// Modifying the address in the shallow copy
shallowCopy.address.city = "Los Angeles";
// Displaying the original and copied objects
System.out.println("Original Person: " + originalPerson);
System.out.println("Shallow Copy: " + shallowCopy);
System.out.println("Deep Copy: " + deepCopy);

}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
}
}
}
OUTPUT:
Original Person: Person{name='Alice', age=30, address=Los Angeles}
Shallow Copy: Person{name='Alice', age=30, address=Los Angeles}
Deep Copy: Person{name='Alice', age=30, address=New York}

46
ANKIT KUMAR 240097140030
Program 25.
Objective: Wap in java for all inner classes(ALL TYPES)
SOURCE CODE:
// Outer class
class Outer
{
private String outerField = "Outer Field";
// 1. Non-static Inner Class
class Inner
{
void display()
{
System.out.println("Non-static Inner Class: " + outerField);
}
}
// 2. Static Nested Class
static class StaticNested
{
void display()
{
System.out.println("Static Nested Class");
}
}
void createLocalInnerClass()
{
// 3. Local Inner Class (defined inside a method)
class LocalInner
{

47
ANKIT KUMAR 240097140030
void display()
{
System.out.println("Local Inner Class: " + outerField);
}
}
LocalInner localInner = new LocalInner();
localInner.display();
}
void createAnonymousInnerClass()

{
// 4. Anonymous Inner Class
Runnable anonymousInner = new Runnable()
{
public void run()
{
System.out.println("Anonymous Inner Class");
}
};
anonymousInner.run();
}
}
public class InnerClassDemo
{
public static void main(String[] args)
{
// Creating instance of non-static inner class
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();

48
ANKIT KUMAR 240097140030
inner.display();
// Creating instance of static nested class
Outer.StaticNested staticNested = new Outer.StaticNested();
staticNested.display();
// Demonstrating local inner class
outer.createLocalInnerClass();
// Demonstrating anonymous inner class
outer.createAnonymousInnerClass();

}
}
OUTPUT:
Non-static Inner Class: Outer Field
Static Nested Class
Local Inner Class: Outer Field
Anonymous Inner Class

49
ANKIT KUMAR 240097140030
Program 26.
Objective: Wap in java to create package(USER DEFINED PACKAGE)
SOURCE CODE:
Step 1: Create a Package
First, define a package by adding the package keyword at the top of your Java source file.
File: mypackage/HelloWorld.java
package mypackage;
public class HelloWorld
{
public void displayMessage()
{
System.out.println("Hello from the user-defined package!");
}
}
Step 2: Compile the Package
To compile the HelloWorld.java file and place the resulting class file in the appropriate directory
structure:
javac -d . mypackage/HelloWorld.java
Step 3: Create a Class to Use the Package

Now, create another Java class that imports and uses the HelloWorld class from the mypackage package.
File: TestPackage.java
import mypackage.HelloWorld;
public class TestPackage
{
public static void main(String[] args)
{
HelloWorld obj = new HelloWorld();
obj.displayMessage();

50
ANKIT KUMAR 240097140030
}
}
Step 4: Compile and Run the Program
To compile and run the TestPackage class:
javac TestPackage.java

java TestPackage

OUTPUT:
Hello from the user-defined package!

51
ANKIT KUMAR 240097140030
Program 27.
Objective: Wap in java for exception handling by using TRY,CATCH AND FINALLY.
SOURCE CODE:
public class ExceptionHandlingExample
{
public static void main(String[] args)
{
Try
{
// Code that may throw an exception
int result = 10 / 0; // This will throw ArithmeticException
System.out.println("Result: " + result);
}
catch (ArithmeticException e)
{
// Handling the exception
System.out.println("Exception caught: " + e);
}
Finally
{
// Code that will execute regardless of exception
System.out.println("Finally block executed.");
}
}
}
OUTPUT:
Exception caught: java.lang.ArithmeticException: / by zero
Finally block executed.

52
ANKIT KUMAR 240097140030
Program 28.
Objective: Wap in java for THROW AND THROWS EXCEPTION
SOURCE CODE:
// Custom exception class
class InvalidAgeException extends Exception
{
public InvalidAgeException(String message)
{
super(message);
}
}
public class AgeValidator
{
// Method that may throw an exception
public void validateAge(int age) throws InvalidAgeException
{
if (age < 18)
{
throw new InvalidAgeException("Age must be at least 18.");
}
System.out.println("Age is valid: " + age);
}

public static void main(String[] args)


{
AgeValidator validator = new AgeValidator();
Try

{
validator.validateAge(16); // This will throw an exception

53
ANKIT KUMAR 240097140030
}
catch (InvalidAgeException e)
{
System.out.println("Caught exception: " + e.getMessage());
}
System.out.println("Program continues...");
}
}
OUTPUT:
Caught exception: Age must be at least 18.
Program continues...

54
ANKIT KUMAR 240097140030
Program 29.
Objective: Wap in java for throw your own exceptions..
SOURCE CODE:
// Custom exception class
class InvalidAgeException extends Exception
{
public InvalidAgeException(String message)
{
super(message);
}
}
public class AgeValidator
{
// Method that may throw an exception
public void validateAge(int age) throws InvalidAgeException
{
if (age < 18)
{
throw new InvalidAgeException("Age must be at least 18.");
}
System.out.println("Age is valid: " + age);
}
public static void main(String[] args)
{
AgeValidator validator = new AgeValidator();
Try

{
validator.validateAge(16); // This will throw an exception

55
ANKIT KUMAR 240097140030
}
catch (InvalidAgeException e)
{
System.out.println("Caught exception: " + e.getMessage());
}
System.out.println("Program continues...");
}
}
OUTPUT:
Caught exception: Age must be at least 18.
Program continues...

56
ANKIT KUMAR 240097140030
Program 30.
Objective: Wap in java to reading and writing in FILES USING BYTE STREAM.
SOURCE CODE:
import java.io.*;
public class ByteStreamExample
{
public static void main(String[] args)
{
// Data to write to the file
String data = "Hello, this is a test message.";
// Writing data to a file using FileOutputStream
try (FileOutputStream fos = new FileOutputStream("output.txt"))
{
byte[] byteData = data.getBytes(); // Convert string to byte array
fos.write(byteData); // Write byte array to file
System.out.println("Data written to file successfully.");

}
catch (IOException e)
{
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();

}
// Reading data from the file using FileInputStream
try (FileInputStream fis = new FileInputStream("output.txt"))
{
int content;
System.out.println("Reading from file:");
while ((content = fis.read()) != -1)

57
ANKIT KUMAR 240097140030
{
System.out.print((char) content); // Convert byte to char and print
}
System.out.println("\nData read from file successfully.");
}
catch (IOException e)
{
System.out.println("An error occurred while reading from the file.");
e.printStackTrace();
}
}
}
OUTPUT:
Data written to file successfully.
Reading from file:
Hello, this is a test message.
Data read from file successfully.

58
ANKIT KUMAR 240097140030
Program 31.
Objective: Wap in java to reading and writing in FILE USING CHARACTER STREAM.
SOURCE CODE:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CharacterStreamExample


{
public static void main(String[] args)
{
// Data to write to the file
String data = "Hello, this is a test message using character streams.";
// Writing data to a file using FileWriter
try (FileWriter writer = new FileWriter("output.txt"))
{
writer.write(data);
System.out.println("Data written to file successfully.");
}
catch (IOException e)
{
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
// Reading data from the file using FileReader
try (FileReader reader = new FileReader("output.txt"))
{
int character;
System.out.println("Reading from file:");

59
ANKIT KUMAR 240097140030
while ((character = reader.read()) != -1)
{
System.out.print((char) character);
}
System.out.println("\nData read from file successfully.");
}
catch (IOException e)
{
System.out.println("An error occurred while reading from the file.");
e.printStackTrace();

}
}
}
OUTPUT:
Data written to file successfully.
Reading from file:
Hello, this is a test message using character streams.
Data read from file successfully.

60
ANKIT KUMAR 240097140030
Program 32.
Objective: Wap in java for reading and writing THROUGH CONSOLE CLASS.
SOURCE CODE:

import java.io.Console;
public class ConsoleExample
{
public static void main(String[] args)
{
// Obtain the system console
Console console = System.console();

// Check if the console is available


if (console == null)
{
System.out.println("No console available.");
return;
}
String name = console.readLine("Enter your name: ");
String age = console.readLine("Enter your age: ");
String city = console.readLine("Enter your city: ");
// Writing formatted output
console.printf("Hello, %s! You are %s years old and live in %s.%n", name, age, city);
}
}
OUTPUT:
Enter your name: John
Enter your age: 30

Enter your city: New York


Hello, John! You are 30 years old and live in New York.

61
ANKIT KUMAR 240097140030
Program 33.
Objective: Wap in java how to create thread using thread class.
SOURCE CODE:

// Extending the Thread class


class MyThread extends Thread
{
@Override
public void run()

{
System.out.println("This code is running in a thread.");
}
}
public class ThreadExample
{
public static void main(String[] args)
{
MyThread thread = new MyThread();
thread.start(); // Start the thread

System.out.println("This code is outside of the thread.");


}
}
OUTPUT:

This code is outside of the thread.


This code is running in a thread.

62
ANKIT KUMAR 240097140030
Program 34.
Objective: Wap in java HOW TO CREATE THREAD USING RUNNABLE INTERFACE.
SOURCE CODE:
// Implementing the Runnable interface
class MyRunnable implements Runnable
{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is executing the run() method.");
}
}

public class RunnableExample


{
public static void main(String[] args)
{
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // Start the new thread

System.out.println(Thread.currentThread().getName() + " is executing the main() method.");


}
}
OUTPUT:
main is executing the main() method.
Thread-0 is executing the run() method.

63
ANKIT KUMAR 240097140030
PROGRAM NO: 35
Objective: Wap in java to implement multithreading.
SOURCE CODE:

class Multithreading extends Thread

public void run()

try

// Displaying the thread that is running

System.out.println(

"Thread " + Thread.currentThread().getId()

+ " is running");

catch (Exception e)

// Throwing an exception

System.out.println("Exception is caught");

// Main Class

public class Geeks

public static void main(String[] args)

int n = 8; // Number of threads


64
ANKIT KUMAR 240097140030
for (int i = 0; i < n; i++) {

Multithreading object = new Multithreading();

object.start();

OUTPUT:

Thread 13 is running

Thread 14 is running

Thread 12 is running

Thread 11 is running

Thread 16 is running

Thread 15 is running

Thread 18 is running

Thread 17 is running

65
ANKIT KUMAR 240097140030
PROGRAM NO: 36
Objective: WAP in java to achieve synchronization in threads.
Source code:

class TicketBooking

private int availableTickets = 10; // Shared resource (available tickets)

// Synchronized method for booking tickets

public synchronized void bookTicket(int tickets)

if (availableTickets >= tickets)

availableTickets -= tickets;

System.out.println("Booked " + tickets + " tickets, Remaining tickets: " + availableTickets);

else

System.out.println("Not enough tickets available to book " + tickets);

public int getAvailableTickets()

return availableTickets;

public class Geeks

public static void main(String[] args)


66
ANKIT KUMAR 240097140030
{

TicketBooking booking = new TicketBooking(); // Shared resource

// Thread 1 to book tickets

Thread t1 = new Thread(() ->

for (int i = 0; i < 2; i++)

booking.bookTicket(2); // Trying to book 2 tickets each time

try

Thread.sleep(50); // Simulate delay

catch (InterruptedException e)

e.printStackTrace();

});

// Thread 2 to book tickets

Thread t2 = new Thread(() ->

for (int i = 0; i < 2; i++)

booking.bookTicket(3); // Trying to book 3 tickets each time

try

Thread.sleep(40); // Simulate delay

67
ANKIT KUMAR 240097140030
}

catch (InterruptedException e)

e.printStackTrace();

});

// Start both threads

t1.start();

t2.start();

// Wait for threads to finish

Try

t1.join();

t2.join();

catch (InterruptedException e)

e.printStackTrace();

// Print final remaining tickets

System.out.println("Final Available Tickets: " + booking.getAvailableTickets());

68
ANKIT KUMAR 240097140030
OUTPUT:

Booked 2 tickets, Remaining tickets: 8

Booked 3 tickets, Remaining tickets: 5

Booked 3 tickets, Remaining tickets: 2

Booked 2 tickets, Remaining tickets: 0

Final Available Tickets: 0

69
ANKIT KUMAR 240097140030
PROGRAM NO: 37
Objective: WAP in java to implement the concept of priorities in threads.
Source code:

import java.lang.*;

class Thread1 extends Thread {

// run() method for the thread that is called

// as soon as start() is invoked for thread in main()

public void run()

System.out.println(Thread.currentThread().getName()

+ " is running with priority "

+ Thread.currentThread().getPriority());

// Main driver method

public static void main(String[] args)

// Creating random threads

// with the help of above class

Thread1 t1 = new Thread1();

Thread1 t2 = new Thread1();

Thread1 t3 = new Thread1();

// Display the priority of above threads

// using getPriority() method

System.out.println("t1 thread priority: " + t1.getPriority());

System.out.println("t2 thread priority: " + t2.getPriority());

System.out.println("t3 thread priority: " + t3.getPriority());

70
ANKIT KUMAR 240097140030
// Setting priorities of above threads by

// passing integer arguments

t1.setPriority(2);

t2.setPriority(5);

t3.setPriority(8);

// Error will be thrown in this case

// t3.setPriority(21);

// Last Execution as the Priority is low

System.out.println("t1 thread priority: " + t1.getPriority());

// Will be executed before t1 and after t3

System.out.println("t2 thread priority: " + t2.getPriority());

// First Execution as the Priority is High

System.out.println("t3 thread priority: " + t3.getPriority());

// Now Let us Demonstrate how it will work

// According to it's Priority

t1.start();

t2.start();

t3.start();

// Thread - 0, 1 , 2 signify 1 , 2 , 3

// respectively

71
ANKIT KUMAR 240097140030
OUTPUT:

t1 thread priority: 5
t2 thread priority: 5
t3 thread priority: 5
t1 thread priority: 2
t2 thread priority: 5
t3 thread priority: 8
Thread-1 is running with priority 5
Thread-2 is running with priority 8
Thread-0 is running with priority 2

72
ANKIT KUMAR 240097140030
PROGRAM NO: 38
Objective: WAP in java to illustrate the concept of generic programming.
SOURCE CODE:

class Test<T>

// An object of type T is declared

T obj;

Test(T obj) { this.obj = obj; } // constructor

public T getObject() { return this.obj; }

// Driver class to test above

class Geeks

public static void main(String[] args)

// instance of Integer type

Test<Integer> iObj = new Test<Integer>(15);

System.out.println(iObj.getObject());

// instance of String type

Test<String> sObj = new Test<String>("Hello World");

System.out.println(sObj.getObject());

OUTPUT:
15

Hello World

73
ANKIT KUMAR 240097140030
PROGRAM NO: 39
Objective: WAP in java to illustrate the concept of event handling(using
various event handlers)
SOURCE CODE:

import java.awt.*;

import java.awt.event.*;

class GFGTop extends Frame implements ActionListener

TextField textField;

GFGTop()

// Component Creation

textField = new TextField();

// setBounds method is used to provide

// position and size of the component

textField.setBounds(60, 50, 180, 25);

Button button = new Button("click Here");

button.setBounds(100, 120, 80, 30);

// Registering component with listener

// this refers to current instance

button.addActionListener(this);

// add Components

add(textField);

add(button);

// set visibility

setVisible(true);

}
74
ANKIT KUMAR 240097140030
// implementing method of actionListener

public void actionPerformed(ActionEvent e)

// Setting text to field

textField.setText("GFG!");

public static void main(String[] args)

new GFGTop();

OUTPUT:

75
ANKIT KUMAR 240097140030
PROGRAM NO: 40
OBJECTIVE:Create a simple student application using various swing components(like
Jframe,Jbutton,Jlabel,textfields,text areas,checkbox,radio box).
SOURCE CODE:

// Java program to implement

// a Simple Registration Form

// using Java Swing

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class MyFrame

extends JFrame

implements ActionListener

// Components of the Form

private Container c;

private JLabel title;

private JLabel name;

private JTextField tname;

private JLabel mno;

private JTextField tmno;

private JLabel gender;

private JRadioButton male;

private JRadioButton female;

private ButtonGroup gengp;

private JLabel dob;

private JComboBox date;

private JComboBox month;

76
ANKIT KUMAR 240097140030
private JComboBox year;

private JLabel add;

private JTextArea tadd;

private JCheckBox term;

private JButton sub;

private JButton reset;

private JTextArea tout;

private JLabel res;

private JTextArea resadd;

private String dates[]

= { "1", "2", "3", "4", "5",

"6", "7", "8", "9", "10",

"11", "12", "13", "14", "15",

"16", "17", "18", "19", "20",

"21", "22", "23", "24", "25",

"26", "27", "28", "29", "30",

"31" };

private String months[]

= { "Jan", "feb", "Mar", "Apr",

"May", "Jun", "July", "Aug",

"Sup", "Oct", "Nov", "Dec" };

private String years[]

= { "1995", "1996", "1997", "1998",

"1999", "2000", "2001", "2002",

"2003", "2004", "2005", "2006",

"2007", "2008", "2009", "2010",

"2011", "2012", "2013", "2014",

"2015", "2016", "2017", "2018",

"2019" };
77
ANKIT KUMAR 240097140030
// constructor, to initialize the components

// with default values.

public MyFrame()

setTitle("Registration Form");

setBounds(300, 90, 900, 600);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setResizable(false);

c = getContentPane();

c.setLayout(null);

title = new JLabel("Registration Form");

title.setFont(new Font("Arial", Font.PLAIN, 30));

title.setSize(300, 30);

title.setLocation(300, 30);

c.add(title);

name = new JLabel("Name");

name.setFont(new Font("Arial", Font.PLAIN, 20));

name.setSize(100, 20);

name.setLocation(100, 100);

c.add(name);

tname = new JTextField();

tname.setFont(new Font("Arial", Font.PLAIN, 15));

tname.setSize(190, 20);

tname.setLocation(200, 100);

c.add(tname);

mno = new JLabel("Mobile");

mno.setFont(new Font("Arial", Font.PLAIN, 20));

mno.setSize(100, 20);
78
ANKIT KUMAR 240097140030
mno.setLocation(100, 150);

c.add(mno);

tmno = new JTextField();

tmno.setFont(new Font("Arial", Font.PLAIN, 15));

tmno.setSize(150, 20);

tmno.setLocation(200, 150);

c.add(tmno);

gender = new JLabel("Gender");

gender.setFont(new Font("Arial", Font.PLAIN, 20));

gender.setSize(100, 20);

gender.setLocation(100, 200);

c.add(gender);

male = new JRadioButton("Male");

male.setFont(new Font("Arial", Font.PLAIN, 15));

male.setSelected(true);

male.setSize(75, 20);

male.setLocation(200, 200);

c.add(male);

female = new JRadioButton("Female");

female.setFont(new Font("Arial", Font.PLAIN, 15));

female.setSelected(false);

female.setSize(80, 20);

female.setLocation(275, 200);

c.add(female);

gengp = new ButtonGroup();

gengp.add(male);

gengp.add(female);

dob = new JLabel("DOB");

dob.setFont(new Font("Arial", Font.PLAIN, 20));


79
ANKIT KUMAR 240097140030
dob.setSize(100, 20);

dob.setLocation(100, 250);

c.add(dob);

date = new JComboBox(dates);

date.setFont(new Font("Arial", Font.PLAIN, 15));

date.setSize(50, 20);

date.setLocation(200, 250);

c.add(date);

month = new JComboBox(months);

month.setFont(new Font("Arial", Font.PLAIN, 15));

month.setSize(60, 20);

month.setLocation(250, 250);

c.add(month);

year = new JComboBox(years);

year.setFont(new Font("Arial", Font.PLAIN, 15));

year.setSize(60, 20);

year.setLocation(320, 250);

c.add(year);

add = new JLabel("Address");

add.setFont(new Font("Arial", Font.PLAIN, 20));

add.setSize(100, 20);

add.setLocation(100, 300);

c.add(add);

tadd = new JTextArea();

tadd.setFont(new Font("Arial", Font.PLAIN, 15));

tadd.setSize(200, 75);

tadd.setLocation(200, 300);

tadd.setLineWrap(true);

c.add(tadd);
80
ANKIT KUMAR 240097140030
term = new JCheckBox("Accept Terms And Conditions.");

term.setFont(new Font("Arial", Font.PLAIN, 15));

term.setSize(250, 20);

term.setLocation(150, 400);

c.add(term);

sub = new JButton("Submit");

sub.setFont(new Font("Arial", Font.PLAIN, 15));

sub.setSize(100, 20);

sub.setLocation(150, 450);

sub.addActionListener(this);

c.add(sub);

reset = new JButton("Reset");

reset.setFont(new Font("Arial", Font.PLAIN, 15));

reset.setSize(100, 20);

reset.setLocation(270, 450);

reset.addActionListener(this);

c.add(reset);

tout = new JTextArea();

tout.setFont(new Font("Arial", Font.PLAIN, 15));

tout.setSize(300, 400);

tout.setLocation(500, 100);

tout.setLineWrap(true);

tout.setEditable(false);

c.add(tout);

res = new JLabel("");

res.setFont(new Font("Arial", Font.PLAIN, 20));

res.setSize(500, 25);

res.setLocation(100, 500);
81
ANKIT KUMAR 240097140030
c.add(res);

resadd = new JTextArea();

resadd.setFont(new Font("Arial", Font.PLAIN, 15));

resadd.setSize(200, 75);

resadd.setLocation(580, 175);

resadd.setLineWrap(true);

c.add(resadd);

setVisible(true);

// method actionPerformed()

// to get the action performed

// by the user and act accordingly

public void actionPerformed(ActionEvent e)

if (e.getSource() == sub) {

if (term.isSelected()) {

String data1;

String data

= "Name : "

+ tname.getText() + "\n"

+ "Mobile : "

+ tmno.getText() + "\n";

if (male.isSelected())

data1 = "Gender : Male"

+ "\n";

else

data1 = "Gender : Female"

+ "\n";

String data2
82
ANKIT KUMAR 240097140030
= "DOB : "

+ (String)date.getSelectedItem()

+ "/" + (String)month.getSelectedItem()

+ "/" + (String)year.getSelectedItem()

+ "\n";

String data3 = "Address : " + tadd.getText();

tout.setText(data + data1 + data2 + data3);

tout.setEditable(false);

res.setText("Registration Successfully..");

else {

tout.setText("");

resadd.setText("");

res.setText("Please accept the"

+ " terms & conditions..");

else if (e.getSource() == reset) {

String def = "";

tname.setText(def);

tadd.setText(def);

tmno.setText(def);

res.setText(def);

tout.setText(def);

term.setSelected(false);

date.setSelectedIndex(0);

month.setSelectedIndex(0);

year.setSelectedIndex(0);

resadd.setText(def);
83
ANKIT KUMAR 240097140030
}

// Driver Code

class Registration {

public static void main(String[] args) throws Exception

MyFrame f = new MyFrame();

OUTPUT:

84
ANKIT KUMAR 240097140030

You might also like