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

Java File Ishan Sharma

Practical file of Java programming

Uploaded by

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

Java File Ishan Sharma

Practical file of Java programming

Uploaded by

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

Practical 1

Create a program to calculate the area of a circle

Source code:
public class CircleAreaCalculator {
public static void main(String[] args) {
// Create a Scanner object to read input from the console
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter the radius of the circle


System.out.print("Enter the radius of the circle: ");

// Read the radius from the user


double radius = scanner.nextDouble();

// Calculate the area of the circle using the formula: Area = π * radius^2
double area = Math.PI * radius * radius;

// Display the area of the circle


System.out.println("The area of the circle with radius " + radius + " is: " + area);

// Close the Scanner object to prevent resource leak


scanner.close();
}
}

Output:

Page 1 of 102
Practical 2
Create a program to find the average of an array of values

Source code:

public class ArrayAverageCalculator {


public static void main(String[] args) {
// Sample array of values
double[] values = {10.5, 20.3, 15.7, 8.2, 12.6};

// Calculate the sum of all values in the array


double sum = 0;
for (double value : values) {
sum += value;
}

// Calculate the average


double average = sum / values.length;

// Display the average


System.out.println("The average of the values in the array is: " + average);
}
}

Output:

Page 2 of 102
Practical 3
Create a program to demonstrate cast operation

Source code:
public class CastOperationDemo {
public static void main(String[] args) {
// Implicit Casting (Widening Conversion)
int integerValue = 10;
double doubleValue = integerValue; // Implicit casting from int to double
System.out.println("Implicit Casting (Widening Conversion):");
System.out.println("Integer Value: " + integerValue);
System.out.println("Double Value: " + doubleValue);

// Explicit Casting (Narrowing Conversion)


double anotherDoubleValue = 15.75;
int anotherIntegerValue = (int) anotherDoubleValue; // Explicit casting from double to int
System.out.println("\nExplicit Casting (Narrowing Conversion):");
System.out.println("Double Value: " + anotherDoubleValue);
System.out.println("Integer Value: " + anotherIntegerValue);

// Casting between related types


char charValue = 'A';
int intValue = charValue; // Implicit casting from char to int
System.out.println("\nCasting between related types:");
System.out.println("Char Value: " + charValue);
System.out.println("Integer Value: " + intValue);
}
}

Output:

Page 3 of 102
Practical 4
Create a program to demonstrate dynamic initialization

Source code:
public class DynamicInitializationDemo {
public static void main(String[] args) {
// Dynamic initialization of variables
int x = 5;
int y = 3;
int z = x + y; // Dynamic initialization using an expression

System.out.println("Dynamic Initialization:");
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("z = x + y = " + z);

// Dynamic initialization using method call


double radius = 5.0;
double area = calculateArea(radius); // Dynamic initialization using a method call

System.out.println("\nDynamic Initialization using Method Call:");


System.out.println("Radius = " + radius);
System.out.println("Area = " + area);
}

// Method to calculate the area of a circle


public static double calculateArea(double r) {
return Math.PI * r * r;
}
}

Output:

Page 4 of 102
Practical 5
Create a program to initialize two dimensional matrix

Source code:
public class MatrixInitialization {
public static void main(String[] args) {
// Define the dimensions of the matrix
int rows = 3;
int cols = 3;

// Initialize a two-dimensional matrix


int[][] matrix = new int[rows][cols];

// Populate the matrix with values


int value = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = value++;
}
}

// Display the matrix


System.out.println("Initialized Matrix:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

Output:

Page 5 of 102
Practical 6
Create a program to perform mathematical functions on different data types

Source code:
public class MathematicalFunctions {
public static void main(String[] args) {
int a = 10;
int b = 5;
System.out.println("Integer Arithmetic:");
System.out.println("Sum: " + (a + b));
System.out.println("Difference: " + (a - b));
System.out.println("Product: " + (a * b));
System.out.println("Quotient: " + (a / b));
System.out.println("Modulus: " + (a % b));
double x = 10.5;
double y = 3.5;
System.out.println("\nFloating-point Arithmetic:");
System.out.println("Sum: " + (x + y));
System.out.println("Difference: " + (x - y));
System.out.println("Product: " + (x * y));
System.out.println("Quotient: " + (x / y));
System.out.println("\nMixed Arithmetic:");
System.out.println("Sum (int + double): " + (a + x));
System.out.println("Difference (int - double): " + (a - x));
System.out.println("Product (int * double): " + (a * x));
System.out.println("Quotient (int / double): " + (a / x));
}
}

Output:

Page 6 of 102
Practical 7
Create a program to demonstrate block scope

Source code:
public class BlockScopeDemo {
public static void main(String[] args) {
// Accessing variables outside the block
int outsideBlockVar = 10;
System.out.println("Outside the block, outsideBlockVar: " + outsideBlockVar);

{
// Creating a new block
int insideBlockVar = 20;
System.out.println("Inside the block, insideBlockVar: " + insideBlockVar);

// Accessing variables from outer block


System.out.println("Inside the block, outsideBlockVar: " + outsideBlockVar);

// Modifying variables from outer block


outsideBlockVar = 30;
System.out.println("Inside the block, modified outsideBlockVar: " + outsideBlockVar);
}

// Variable insideBlockVar is out of scope here


// System.out.println("Outside the block, insideBlockVar: " + insideBlockVar); //
Uncommenting this line will cause a compilation error

// Accessing modified variable outside the block


System.out.println("Outside the block, modified outsideBlockVar: " + outsideBlockVar);
}
}

Output:

Page 7 of 102
Practical 8
Create a program to demonstrate three dimensional array

Source code:
public class ThreeDimensionalArrayDemo {
public static void main(String[] args) {
// Define the dimensions of the three-dimensional array
int rows = 2;
int columns = 3;
int depth = 4;

// Initialize a three-dimensional array


int[][][] threeDArray = new int[rows][columns][depth];

// Populate the three-dimensional array with values


int value = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
for (int k = 0; k < depth; k++) {
threeDArray[i][j][k] = value++;
}
}
}

// Display the three-dimensional array


System.out.println("Initialized Three-Dimensional Array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
for (int k = 0; k < depth; k++) {
System.out.print(threeDArray[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}

Output:

Page 8 of 102
Practical 9
Create a program to demonstrate a two dimensional array

Source code:

public class TwoDimensionalArrayDemo {


public static void main(String[] args) {
// Define the dimensions of the two-dimensional array
int rows = 3;
int columns = 4;

// Initialize a two-dimensional array


int[][] twoDArray = new int[rows][columns];

// Populate the two-dimensional array with values


int value = 1;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
twoDArray[i][j] = value++;
}
}

// Display the two-dimensional array


System.out.println("Initialized Two-Dimensional Array:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(twoDArray[i][j] + " ");
}
System.out.println();
}
}
}

Output:

Page 9 of 102
Practical 10
Create a program to demonstrate bitwise logical operators

Source code:

public static void main(String[] args) {


String[] binary = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;

System.out.println(" a = " + binary[a]);


System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}

Output:

Page 10 of 102
Practical 11
Create a program to demonstrate boolean logical operators

Source code:

public class BoolLogic {


public static void main(String[] args) {
boolean a = true;
boolean b = false;
boolean c = a || b; // logical OR
boolean d = a && b; // logical AND
boolean e = a ^ b; // logical XOR
boolean f = (!a && b) || (a && !b); // logical expression equivalent to f = (!a & b) | (a
& !b)
boolean g = !a;

System.out.println(" a = " + a);


System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}

Output:

Page 11 of 102
Practical 12
Create a program to demonstrate left shifting a byte value

Source code:

// Left shifting a byte value.


public class ByteShift {
public static void main(String[] args) {
byte a = 64;
byte b;

int i;

i = a << 2;
b = (byte) (a << 2);

System.out.println("Original value of a: " + a);


System.out.println("i and b: " + i + " " + b);
}
}

Output:

Page 12 of 102
Practical 13
Create a program to demonstrate unsigned shifting a byte value

Source code:

// Unsigned shifting a byte value.


public class ByteUShift {
static public void main(String[] args) {
char[] hex = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
byte b = (byte) 0xf1;
byte c = (byte) (b >> 4); // Error 1: Using signed right shift
byte d = (byte) (b >>> 4);
byte e = (byte) ((b & 0xff) >>> 4); // Error 2: Correcting signed to unsigned shift

System.out.println(" b = 0x"
+ hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
System.out.println(" b >> 4 = 0x"
+ hex[(c >> 4) & 0x0f] + hex[c & 0x0f]);
System.out.println(" b >>> 4 = 0x"
+ hex[(d >> 4) & 0x0f] + hex[d & 0x0f]);
System.out.println("(b & 0xff) >> 4 = 0x"
+ hex[(e >> 4) & 0x0f] + hex[e & 0x0f]);
}
}

Output:

Page 13 of 102
Practical 14
Create a program to demonstrate ternary operator

Source code:

public class Ternary {


public static void main(String[] args) {
int i, k;

i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);

i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}

Output:

Page 14 of 102
Practical 15
Create a program to use break as a civilized form of goto

Source code:

// Using break as a civilized form of goto.


public class Break {
public static void main(String[] args) {
boolean t = true;

first: {
second: {
third: {
System.out.println("Before the break.");
if (t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}

Output:

Page 15 of 102
Practical 16
Create a program using continue with label

Source code:

// Using continue with a label.


class ContinueLabel {
public static void main(String[] args) {
outer:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}

Output:

Page 16 of 102
Practical 17
Create a program to test for primes

Source code:

// Test for primes.


class FindPrime {
public static void main(String[] args) {
int num;
boolean isPrime;

num = 14;

if (num < 2)
isPrime = false;
else
isPrime = true;

for (int i = 2; i <= num / i; i++) {


if ((num % i) == 0) {
isPrime = false;
break;
}
}

if (isPrime)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
}

Output:

Page 17 of 102
Practical 18
Create a program to demonstrate the use of for-each style for loop

Source code:

// Use a for-each style for loop.


class ForEach {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;

// use for-each style for to display and sum the values


for (int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}

System.out.println("Summation: " + sum); // Corrected println statement


}
}

Output:

Page 18 of 102
Practical 19
Create a program to demonstrate if-else-if statements

Source code:

// Demonstrate if-else-if statements.


class IfElse {
public static void main(String[] args) {
int month = 4; // April
String season;

if (month == 12 || month == 1 || month == 2)


season = "Winter";
else if (month == 3 || month == 4 || month == 5)
season = "Spring";
else if (month == 6 || month == 7 || month == 8)
season = "Summer";
else if (month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";

System.out.println("April is in the " + season + ".");


}
}

Output:

Page 19 of 102
Practical 20
Write a program to create a class named box, use parametrized constructor to initialize
the dimension of a box, declare two box objects, add method volume() inside the box class,
use parametrized method

Source code:

class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String[] args) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Output:

Page 20 of 102
Practical 21
Create a program to define an integer stack that can hold 10 values, push some numbers
onto the stack, pop those numbers off the stack

Source code:

class Stack {
int[] stck = new int[10];
int tos;
// Initialize top-of-stack
Stack() {
tos = -1;
}
void push(int item) {
if (tos == 9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
int pop() {
if (tos < 0) {
System.out.println("Stack underflow.");
return 0;
} else
return stck[tos--];
}
public static void main(String[] args) {
Stack stack = new Stack();
for (int i = 0; i < 10; i++) {
stack.push(i);
}
System.out.println("Popping items from the stack:");
for (int i = 0; i < 10; i++) {
int item = stack.pop();
if (item != 0) {
System.out.println(item);
}
}
}
}

Output:

Page 21 of 102
Practical 22
Create a program to display all command line arguments
Source code:
class CommandLine {
public static void main(String[] args) {
for (int i = 0; i < args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}

Output:

Practical 23
Create a program to define an inner class within a for loop
Source code:
class Outer {
int outer_x = 100;
void test() {
for (int i = 0; i < 10; i++) {
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}}
Inner inner = new Inner();
inner.display();
}}}
class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
outer.test();
}}

Output:

Page 22 of 102
Practical 24
Create a program to demonstrate method overloading

Source code:

class OverloadingDemo {
// Method to add two integers
static int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


static int add(int a, int b, int c) {
return a + b + c;
}

// Overloaded method to add two doubles


static double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


int sum1 = add(3, 5);
int sum2 = add(3, 5, 7);
double sum3 = add(3.5, 4.5);

System.out.println("Sum of two integers: " + sum1);


System.out.println("Sum of three integers: " + sum2);
System.out.println("Sum of two doubles: " + sum3);
}
}

Output:

Page 23 of 102
Practical 25
Create a program to demonstrate automatic type conversions applied to overloading

Source code:

class OverloadingDemo {
// Method to add two integers
static void add(int a, int b) {
System.out.println("Adding two integers: " + (a + b));
}

// Overloaded method to add two doubles


static void add(double a, double b) {
System.out.println("Adding two doubles: " + (a + b));
}

// Overloaded method to add an int and a double


static void add(int a, double b) {
System.out.println("Adding an int and a double: " + (a + b));
}

// Overloaded method to add a double and an int


static void add(double a, int b) {
System.out.println("Adding a double and an int: " + (a + b));
}

public static void main(String[] args) {


add(5, 10); // Calls add(int, int)
add(3.5, 2.5); // Calls add(double, double)
add(4, 3.6); // Calls add(int, double) because 4 is automatically promoted to double
add(6.7, 2); // Calls add(double, int) because 2 is automatically promoted to double
}
}

Output:

Page 24 of 102
Practical 26
Create a program to demonstrate objects may be passed to methods

Source code:

class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
class ObjectPassingDemo {
static void displayStudentInfo(Student student) {
System.out.println("Name: " + student.name);
System.out.println("Age: " + student.age);
}
static void updateStudentAge(Student student, int newAge) {
student.age = newAge;
}
public static void main(String[] args) {
Student student1 = new Student("Alice", 20);
System.out.println("Initial student information:");
displayStudentInfo(student1);
updateStudentAge(student1, 21);
System.out.println("\nUpdated student information:");
displayStudentInfo(student1);
}
}

Output:

Page 25 of 102
Practical 27
Create a program to demonstrate a simple example of recursion

Source code:
class RecursionDemo {
static int factorial(int n) {
if (n == 0) {
return 1;
}
else {
return n * factorial(n - 1);
}
}
public static void main(String[] args) {
// Calculate the factorial of 5 using recursion
int result = factorial(5);
System.out.println("Factorial of 5: " + result);
}
}

Output:

Practical 28
Create a program to demonstrate local variable type inference with user defined class type

Source code:
class MyClass {
private String name;
MyClass(String name) {
this.name = name;
}
String getName() {
return name;
}
}
public class LocalVariableInferenceDemo {
public static void main(String[] args) {
var myObject = new MyClass("Hello");
System.out.println("Object name: " + myObject.getName());
}
}

Output:

Page 26 of 102
Practical 29
Create a program to demonstrate to return an object

Source code:

// Define a simple class representing a person


class Person {
private String name;
private int age;

// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}

// Method to get the name


String getName() {
return name;
}

// Method to get the age


int getAge() {
return age;
}
}

public class ReturnObjectDemo {


// Method to create and return a Person object
static Person createPerson(String name, int age) {
return new Person(name, age);
}

public static void main(String[] args) {


// Call the createPerson method to create a Person object
Person person = createPerson("Alice", 30);

// Display the information of the returned Person object


System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}

Output:

Page 27 of 102
Practical 30
Create a program to demonstrate string and string methods

Source code:

public class StringDemo {


public static void main(String[] args) {
String str = "Hello, World!";
int length = str.length();
System.out.println("Length of the string: " + length);
String substring = str.substring(7);
System.out.println("Substring from index 7: " + substring);
String newStr = str.concat(" How are you?");
System.out.println("Concatenated string: " + newStr);
String uppercase = str.toUpperCase();
System.out.println("Uppercase string: " + uppercase);
String lowercase = str.toLowerCase();
System.out.println("Lowercase string: " + lowercase);
boolean contains = str.contains("World");
System.out.println("Does the string contain 'World'? " + contains);
String replacedStr = str.replace('l', 'z');
System.out.println("String after replacing 'l' with 'z': " + replacedStr);
String[] parts = str.split(",");
System.out.println("String after splitting: ");
for (String part : parts) {
System.out.println(part);
}
String trimmedStr = " Trim Me ";
String trimmed = trimmedStr.trim();
System.out.println("Trimmed string: " + trimmed);
}
}

Output:

Page 28 of 102
Practical 31`
Create a program to demonstrate static variable, method and blocks

Source code:

class StaticDemo {
// Static variable
static int count = 0;

// Static method
static void incrementCount() {
count++;
}

// Static block
static {
System.out.println("Static block initialized.");
// You can perform any initialization tasks here
}

public static void main(String[] args) {


// Accessing static variable and method
System.out.println("Initial count: " + count);
incrementCount();
System.out.println("Count after increment: " + count);

// Static block is executed when the class is loaded


}
}

Output:

Page 29 of 102
Practical 32
Create a program to demonstrate the use of abstract classes and methods

Source code:

abstract class Shape {


abstract double calculateArea();
}
class Rectangle extends Shape {
double length;
double width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double calculateArea() {
return length * width;
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
}
public class AbstractDemo {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 3);
Circle circle = new Circle(4);
System.out.println("Area of rectangle: " + rectangle.calculateArea());
System.out.println("Area of circle: " + circle.calculateArea());
}
}

Output:

Page 30 of 102
Practical 33
Create a program to understand class hierarchy

Source code:

// Base class representing a Vehicle


class Vehicle {
void drive() {
System.out.println("Vehicle is being driven.");
}
}

// Subclass representing a Car


class Car extends Vehicle {
void accelerate() {
System.out.println("Car is accelerating.");
}
}

// Subclass representing a Truck


class Truck extends Vehicle {
void loadCargo() {
System.out.println("Truck is loading cargo.");
}
}
public class ClassHierarchyDemo {
public static void main(String[] args) {
// Create objects of different classes
Vehicle vehicle = new Vehicle();
Car car = new Car();
Truck truck = new Truck();
// Demonstrate method calls
vehicle.drive(); // Vehicle method
car.drive(); // Inherited method from Vehicle
car.accelerate(); // Car method
truck.drive(); // Inherited method from Vehicle
truck.loadCargo(); // Truck method
}
}

Output:

Page 31 of 102
Practical 34
Create a program to demonstrate inheritance all types

Source code:

class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking.");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing.");
}
}
interface Swimmable {
void swim();
}
class Fish extends Animal implements Swimmable {
@Override
public void swim() {
System.out.println("Fish is swimming.");
}
}
public class InheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
Fish fish = new Fish();
dog.eat(); // Inherited method from Animal
dog.bark(); // Method of Dog class
System.out.println();
cat.eat(); // Inherited method from Animal
cat.meow(); // Method of Cat class
System.out.println();
fish.eat(); // Inherited method from Animal
fish.swim(); // Method from Swimmable interface
}
}

Output:

Page 32 of 102
Practical 35
Create a program to demonstrate the use of super keyword

Source code:

// Base class
class Animal {
String type;

// Constructor
Animal(String type) {
this.type = type;
}
void display() {
System.out.println("Type of animal: " + type);
}
}
class Dog extends Animal {
String breed;
Dog(String type, String breed) {
// Call the constructor of the superclass using super keyword
super(type);
this.breed = breed;
}
// Method
void displayBreed() {
// Call the method of the superclass using super keyword
super.display();
System.out.println("Breed of dog: " + breed);
}
}
public class SuperKeywordDemo {
public static void main(String[] args) {
Dog dog = new Dog("Canine", "Labrador");
dog.displayBreed();
}
}

Output:

Page 33 of 102
Practical 36
Create a program to demonstrate when constructors are called

Source code:

class A {
// Constructor
A() {
System.out.println("Constructor of class A");
}
}

class B extends A {
// Constructor
B() {
System.out.println("Constructor of class B");
}
}

class C extends B {
// Constructor
C() {
System.out.println("Constructor of class C");
}
}

public class ConstructorDemo {


public static void main(String[] args) {
// Creating an object of class C
C obj = new C();
}
}

Output:

Page 34 of 102
Practical 37
Create a program to demonstrate dynamic method

Source code:

class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}

public class DynamicMethodDispatchDemo {


public static void main(String[] args) {
Animal animal1 = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new Cat();
animal1.makeSound(); // Calls makeSound() of Animal class
animal2.makeSound(); // Calls makeSound() of Dog class
animal3.makeSound(); // Calls makeSound() of Cat class
}
}

Output:

Page 35 of 102
Practical 38
Create a program to demonstrate the use of final keyword using run time polymorphism

Source code:

class Animal {
// Method
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
final class Bird extends Animal {
@Override
void makeSound() {
System.out.println("Bird chirps");
}
}
public class FinalKeywordDemo {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
Animal animal3 = new Bird(); // We can assign Bird object to Animal reference
animal1.makeSound(); // Calls makeSound() of Dog class
animal2.makeSound(); // Calls makeSound() of Cat class
animal3.makeSound(); // Calls makeSound() of Bird class
}
}

Output:

Page 36 of 102
Practical 39
Create a program to demonstrate method overriding

Source code:

class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
// Method overriding
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
// Method overriding
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public class MethodOverridingDemo {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.makeSound(); // Calls makeSound() of Dog class
animal2.makeSound(); // Calls makeSound() of Cat class
}
}

Output:

Page 37 of 102
Practical 40
Create a program to demonstrate that method with different type signatures are
overloaded

Source code:

public class MethodOverloadingDemo {

// Method with one parameter of type int


static void display(int num) {
System.out.println("Method with int parameter: " + num);
}

// Method with one parameter of type double


static void display(double num) {
System.out.println("Method with double parameter: " + num);
}

// Method with two parameters of different types


static void display(int num, double dbl) {
System.out.println("Method with int and double parameters: " + num + ", " + dbl);
}

// Method with two parameters of different types (order reversed)


static void display(double dbl, int num) {
System.out.println("Method with double and int parameters: " + dbl + ", " + num);
}

public static void main(String[] args) {


// Call each overloaded method
display(10); // Calls method with int parameter
display(3.14); // Calls method with double parameter
display(5, 3.14); // Calls method with int and double parameters
display(2.71, 20); // Calls method with double and int parameters
}
}

Output:

Page 38 of 102
Practical 41
Create a program to show when working with inheritance the inferred type is the
declared type of the initializer which may not be the most derived type of the object being
referred to by the initializer

Source code:

// Base class
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}

// Subclass inheriting from Animal


class Dog extends Animal {
// Overriding method
@Override
void makeSound() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
// Overriding method
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public class InheritanceTypeDemo {
public static void main(String[] args) {
Animal animal1 = new Animal(); // Base class object
Animal animal2 = new Dog(); // Subclass object assigned to superclass reference
Animal animal3 = new Cat();
animal1.makeSound(); // Calls makeSound() of Animal class
animal2.makeSound(); // Calls makeSound() of Dog class (dynamic method dispatch)
animal3.makeSound(); // Calls makeSound() of Cat class (dynamic method dispatch)
}
}

Output:

Page 39 of 102
Practical 42
Create a program to demonstrate the use of package

Source code:

// Greetings.java (placed in mypackage)


package mypackage;

public class Greetings {


public void greet() {
System.out.println("Hello from the mypackage!");
}
}

// HelloWorld.java
import mypackage.Greetings; // Importing Greetings class from mypackage

public class HelloWorld {


public static void main(String[] args) {
// Creating an object of Greetings class from mypackage
Greetings greetings = new Greetings();
// Calling the greet method
greetings.greet();
}
}

Output:

Page 40 of 102
Practical 43
Create a program to demonstrate the inheritance of packages

Source code:

// Animal.java (in animals package)


package animals;

public class Animal {


public void eat() {
System.out.println("Animal is eating");
}
}

// Mammal.java (in animals.mammals package)


package animals.mammals;

import animals.Animal;

public class Mammal extends Animal {


public void giveBirth() {
System.out.println("Mammal is giving birth");
}
}

// InheritanceDemo.java (in the default package)


import animals.Animal;
import animals.mammals.Mammal;

public class InheritanceDemo {


public static void main(String[] args) {
// Create an object of Animal class from animals package
Animal animal = new Animal();
animal.eat(); // Call eat method of Animal class

// Create an object of Mammal class from animals.mammals package


Mammal mammal = new Mammal();
mammal.eat(); // Call eat method of Animal class (inherited)
mammal.giveBirth(); // Call giveBirth method of Mammal class
}
}

Output:

Page 41 of 102
Practical 44
Create a program to demonstrate the use of interface

Source code:
interface Animal {
void eat(); // Abstract method declaration
void sleep(); // Abstract method declaration
}
class Dog implements Animal {
public void eat() {
System.out.println("Dog is eating");
}
public void sleep() {
System.out.println("Dog is sleeping");
}
}
class Cat implements Animal {
public void eat() {
System.out.println("Cat is eating");
}
public void sleep() {
System.out.println("Cat is sleeping");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.eat();
dog.sleep();
cat.eat();
cat.sleep();
}
}

Output:

Page 42 of 102
Practical 45
Create a program to demonstrate the inheritance of an interface

Source code:

// Base interface
interface Animal {
void eat();
void sleep();
}

// Sub-interface extending Animal


interface Pet extends Animal {
void play();
}

// Class implementing the Pet interface


class Dog implements Pet {
// Implementing methods from Animal interface
public void eat() {
System.out.println("Dog is eating");
}

public void sleep() {


System.out.println("Dog is sleeping");
}
public void play() {
System.out.println("Dog is playing");
}
}
public class InterfaceInheritanceDemo {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // From Animal interface
dog.sleep(); // From Animal interface
dog.play(); // From Pet interface
}
}

Output:

Page 43 of 102
Practical 46
Create a program to demonstrate the use of default method

Source code:

// Interface with a default method


interface Animal {
void eat(); // Abstract method

// Default method
default void sleep() {
System.out.println("Animal is sleeping");
}
}

// Class implementing the Animal interface


class Dog implements Animal {
// Implementing the eat method
public void eat() {
System.out.println("Dog is eating");
}
}

public class DefaultMethodDemo {


public static void main(String[] args) {
// Create object of Dog class
Dog dog = new Dog();

// Call methods
dog.eat(); // Provided by Dog class
dog.sleep(); // Provided by Animal interface (default method)
}
}

Output:

Page 44 of 102
Practical 47
Create one interface and extend another

Source code:

// Base interface
interface Animal {
void eat();
}

// Sub-interface extending Animal


interface Pet extends Animal {
void play();
}

// Class implementing the Pet interface


class Dog implements Pet {
// Implementing methods from Animal interface
public void eat() {
System.out.println("Dog is eating");
}

// Implementing method from Pet interface


public void play() {
System.out.println("Dog is playing");
}
}

public class InterfaceExtensionDemo {


public static void main(String[] args) {
// Create object of Dog class
Dog dog = new Dog();

// Call methods
dog.eat(); // From Animal interface
dog.play(); // From Pet interface
}
}

Output:

Page 45 of 102
Practical 48
Create a program to demonstrate exception chaining
Source code:
public class ExceptionChainingDemo {
static void process() throws Exception {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
throw new Exception("Error occurred during processing", e);
}}
public static void main(String[] args) {
try {
process();
} catch (Exception e) {
System.out.println("Caught exception: " + e.getMessage());
System.out.println("Original cause: " + e.getCause());
}}}

Output:

Practical 49
Create a program to demonstrate the use of finally
Source code:
import java.util.Scanner;
public class FinallyDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a number: ");
int num = scanner.nextInt();
System.out.println("Square of the number: " + num * num);
} catch (Exception e) {
System.out.println("Error occurred: " + e.getMessage());
} finally {
if (scanner != null) {
scanner.close();
System.out.println("Scanner closed");
}}}}

Output:

Page 46 of 102
Practical 50
Create a program to handle an exception and move on

Source code:

public class ExceptionHandlingExample {public


static void main(String[] args) {
String[] names = {"Alice", "Bob", "Charlie", “David"};
for (String name : names) {
try {
int length = name.length();if
(length % 2 != 0) {
throw new IllegalArgumentException("Name length is odd");
}
System.out.println(name);
} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
}

}
}
}

Output

Page 47 of 102
Practical 51
Create a program to demonstrate that try statements can be implicitly nested via calls
to method

SOURCE CODE:

public class NestedTryExample {


public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println("Caught exception in main: " + e);
}

}
public static void methodA() {try
{
methodB();
} catch (ArithmeticException e) {
System.out.println("Caught exception in methodA: " + e);
}

}
public static void methodB() {int
result = 10 / 0;
System.out.println("Result: " + result);
}

Output

Page 48 of 102
Practical 52
Create a program to demonstrate multi catch statements

Source Code:

public class MultiCatchExample {


public static void main(String[] args) {
try {
// Simulating an array index out of bounds exceptionint[]
numbers = {1, 2, 3};
System.out.println(numbers[5]);
// Simulating a division by zero exceptionint
result = 10 / 0;
System.out.println("Result: " + result);
} catch (ArrayIndexOutOfBoundsException | ArithmeticException e) {
// Handling both exceptions in one catch block
System.err.println("Caught exception: " + e);
}

}
}

Output

Page 49 of 102
Practical 53
Create a program to create a custom exception time

Source Code:

class CustomTimeException extends Exception {


public CustomTimeException(String message) {
super(message);
}

public class CustomExceptionExample {

public static void checkTime(int hour) throws CustomTimeException {


if (hour < 0 || hour > 23) {
throw new CustomTimeException("Invalid hour: " + hour);

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

public static void main(String[] args) {


try {
checkTime(25);

} catch (CustomTimeException e) {

System.err.println("Caught custom exception: " + e.getMessage());

Output

Page 50 of 102
Practical 54
Create a program to demonstrate nested try statements

Source Code:

public class NestedTryExample {

public static void main(String[] args) {


try {
System.out.println("Outer try block starts");
try {
System.out.println("Inner try block starts");
int result = 10 / 0;
System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.err.println("Inner catch block: " + e);

int[] numbers = {1, 2, 3};

System.out.println(numbers[5]);

} catch (ArrayIndexOutOfBoundsException e) {
System.err.println("Outer catch block: " + e);
}

System.out.println("End of program");

Output

Page 51 of 102
Practical 55
Create a program to demonstrate throw

SOURCE CODE:

public class ThrowExample {

public static void main(String[] args) {


try {
validateAge(15);

} catch (IllegalArgumentException e) {

System.err.println("Caught exception: " + e.getMessage());

public static void validateAge(int age) {


if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or older");

} else {

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

Output

Page 52 of 102
Practical 56
Create a program to control the main thread

Source Code:

public class MainThreadControlExample {


public static void main(String[] args) {
Thread mainThread = Thread.currentThread();

System.out.println("Main thread name: " + mainThread.getName());

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


mainThread.setName("MyMainThread");
mainThread.setPriority(Thread.MAX_PRIORITY);

System.out.println("Updated main thread name: " + mainThread.getName());

System.out.println("Updated main thread priority: " + mainThread.getPriority());


try {
System.out.println("Main thread is going to sleep for 3 seconds.");
Thread.sleep(3000);
System.out.println("Main thread woke up.");

} catch (InterruptedException e) {

System.err.println("Main thread interrupted.");

System.out.println("End of main thread.”);

Output

Page 53 of 102
Practical 57
Create a program to use join() to wait for the thread to finish

Source Code:

Class MyThread extends Thread

@Override

public void run()

{
System.out.println("Thread is running..."); try {
Thread.sleep(2000); // Simulating some task execution
}
catch (InterruptedException e) { System.out.println("Thread
interrupted");
}
System.out.println("Thread completed.");
}
}
public class JoinDemo {
public static void main(String[] args) {
MyThread myThread = new MyThread(); // Create an instance of MyThread
myThread.start(); // Start the thread
try {
System.out.println("Main thread is waiting for the child thread to finish...");
myThread.join(); // Main thread waits for myThread to finish System.out.println("Main
thread resumes after the child thread completes.");
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted while waiting for the child thread");
}
}
}

Output

Page 54 of 102
Practical 58
Create a second thread by extending thread

Source Code:

class SecondThread extends Thread { @Override


public void run()
{
System.out.println("Second thread is running..."); try {
Thread.sleep(3000); // Simulating some task execution
}
catch (InterruptedException e) { System.out.println("Second
thread interrupted");
}
System.out.println("Second thread completed.");
}
}
public class SecondThreadDemo { public static
void main(String[] args) {
SecondThread secondThread = new SecondThread(); // Create an instance of SecondThread
secondThread.start(); // Start the second thread
System.out.println("Main thread continues...");
}
}

Output

Page 55 of 102
Practical 59
Create a program to demonstrate multiple threads

Source Code:

Class MyThread extends Thread{


private String threadName; public
MyThread(String name) {
this.threadName = name;
}
@Override public void
run()
{
System.out.println("Thread " + threadName + " is running..."); try {
for (int i = 0; i < 5; i++) {
System.out.println("Thread " + threadName + ": " + i);
Thread.sleep(1000); // Simulating some task execution
}
}
catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted");
}
System.out.println("Thread " + threadName + " completed.");
}
}
public class MultipleThreadDemo { public static
void main(String[] args) {
MyThread thread1 = new MyThread("Thread 1"); MyThread
thread2 = new MyThread("Thread 2"); thread1.start();
thread2.start();
}
}

Output

Page 56 of 102
Practical 60

Create a program to demonstrate unsynchronization and synchronised block.

Source Code:
public class SynchronizationDemo { private int
count = 0;
public void unsynchronizedIncrement() { count++;
}
public synchronized void synchronizedIncrement() { count++;
}
public static void main(String[] args) {
final SynchronizationDemo demo = new SynchronizationDemo();
// Unsynchronized block
Runnable unsynchronizedTask = () -> { for (int i =
0; i < 1000; i++) {
demo.unsynchronizedIncrement();
}
System.out.println("Unsynchronized count: " + demo.count);
};
Runnable synchronizedTask = () -> { for (int i =
0; i < 1000; i++) {
demo.synchronizedIncrement();
}
System.out.println("Synchronized count: " + demo.count);
};
Thread unsynchronizedThread = new Thread(unsynchronizedTask); Thread
synchronizedThread = new Thread(synchronizedTask);
unsynchronizedThread.start();
synchronizedThread.start();
}
}

Output

Page 57 of 102
Practical 61
Create a program to demonstrate autoboxing and unboxing taking place with metho
parameters and return value.

Source Code:

public class AutoboxingUnboxingDemo {


// Autoboxing: Integer parameter
static void autoboxingExample(Integer num) {
System.out.println("Autoboxing example: " + num);
}
// Unboxing: int return value static int
unboxingExample() {
Integer value = 10; // Autoboxing return
value; // Unboxing
}
public static void main(String[] args) {
// Autoboxing: passing primitive int as argument int
primitiveValue = 20; autoboxingExample(primitiveValue);
// Unboxing: assigning Integer return value to primitive int int result =
unboxingExample(); System.out.println("Unboxing example: " +
result);
}
}

Output

Page 58 of 102
Practical 62
Create a program to demonstrate that autoboxing and unboxing occurs inside expressions.

Source Code:

public class AutoboxingUnboxingExpressionsDemo { public


static void main(String[] args) {
// Autoboxing inside expressions
Integer a = 10; // Autoboxing Integer
b = 20; // Autoboxing

// Addition: unboxing of a and b, addition, autoboxing of result Integer


sum = a + b;

// Subtraction: unboxing of a and b, subtraction, autoboxing of result Integer


difference = b - a;

// Multiplication: unboxing of a and b, multiplication, autoboxing of result Integer


product = a * b;

// Division: unboxing of a and b, division, autoboxing of result Integer


quotient = b / a;

System.out.println("Sum: " + sum);


System.out.println("Difference: " + difference);
System.out.println("Product: " + product);
System.out.println("Quotient: " + quotient);
}
}

Output

Page 59 of 102
Practical 63
Create a programme to autobox and unbox a boolean and character.

Source code:
public class AutoboxingUnboxingBooleanCharDemo { public static
void main(String[] args) {
// Autoboxing: boolean to Boolean Boolean
boolObj = true; // Autoboxing

// Unboxing: Boolean to boolean


boolean boolValue = boolObj; // Unboxing

System.out.println("Autoboxing and Unboxing for boolean:");


System.out.println("Boolean object: " + boolObj); System.out.println("Boolean value: " +
boolValue);

// Autoboxing: char to Character Character


charObj = 'A'; // Autoboxing

// Unboxing: Character to char


char charValue = charObj; // Unboxing

System.out.println("\nAutoboxing and Unboxing for char:");


System.out.println("Character object: " + charObj);
System.out.println("Character value: " + charValue);
}
}

Output

Page 60 of 102
Practical 64
Create a program to demonstrate a type wrapper

Source Code:
public class TypeWrapperDemo { public static
void main(String[] args)
{
Integer intValue = new Integer(10); int
primitiveInt = intValue.intValue();

Double doubleValue = new Double(3.14);


double primitiveDouble = doubleValue.doubleValue();

Boolean boolValue = new Boolean(true);


boolean primitiveBool = boolValue.booleanValue();

Character charValue = new Character('A'); char


primitiveChar = charValue.charValue();

// Using Long wrapper class (Since Java 9, using Integer as an example) Integer intValue2 =
Integer.valueOf("20"); // Autoboxing from String to Integer int primitiveInt2 = intValue2; //
Autounboxing to get the primitive int value

// Print values
System.out.println("Primitive int value: " + primitiveInt); System.out.println("Primitive
double value: " + primitiveDouble); System.out.println("Primitive boolean value: " +
primitiveBool); System.out.println("Primitive char value: " + primitiveChar);
System.out.println("Autoboxing from String to Integer: " + primitiveInt2);
}
}

Output

Page 61 of 102
Practical 65
Create a program to use a buffer reader to read characters and strings from the console.

Source Code:

import java.io.BufferedReader; import


java.io.IOException;
import java.io.InputStreamReader; public class
BufferedReaderDemo {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try {
// Reading a character System.out.print("Enter a
character: "); char ch = (char) reader.read();
System.out.println("Character entered: " + ch);

// Clearing the buffer reader.readLine();

// Reading a string System.out.print("Enter a


string: "); String str = reader.readLine();
System.out.println("String entered: " + str);

// Closing the reader reader.close();


}
catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
}
}
}

Output

Page 65 of 102
Practical 66
Create a program to use a buffer reader to read characters and strings from the console

Source Code:

import java.io.BufferedReader; import


java.io.BufferedWriter; import
java.io.FileReader; import
java.io.FileWriter; import
java.io.IOException; public class
FileCopy {
public static void main(String[] args) { String
sourceFileName = "source.txt"; String
targetFileName = "target.txt";

try (BufferedReader reader = new BufferedReader(new FileReader(sourceFileName)); BufferedWriter writer =


new BufferedWriter(new FileWriter(targetFileName)))
{
String line;
while ((line = reader.readLine()) != null) { writer.write(line);
writer.newLine(); // Adding newline for each line
}
System.out.println("File copied successfully!");
} catch (IOException e) { System.err.println("Error: " +
e.getMessage());
}
}
}

Output

Page 66 of 102
Practical 67
Create a program using concatenation to prevent long lines.

Source Code:
public class ConcatenationDemo { public static
void main(String[] args) {
String message = "Hello, "; message +=
"this is a "; message += "demonstration ";
message += "of ";
message += "concatenation "; message +=
"to ";
message += "prevent "; message
+= "long "; message +=
"lines.";

System.out.println(message);
}
}

Output

Page 67 of 102
Practical 68
Create a program using concatenation to prevent long lines

Source Code:

public class EqualsVsDoubleEquals { public static


void main(String[] args) {
String s1 = new String("hello"); String s2 =
new String("hello");

// Using equals() method to compare string contents System.out.println("Using equals()


method:");
System.out.println("s1 equals s2: " + s1.equals(s2)); // true, as both strings have the same content

// Using == to compare string references


System.out.println("\nUsing == operator:");
System.out.println("s1 == s2: " + (s1 == s2)); // false, as s1 and s2 refer to different objects

// Creating two string literals with the same content String s3 =


"hello";
String s4 = "hello";

// Using == to compare string literals System.out.println("\nUsing ==


operator with string literals:");
System.out.println("s3 == s4: " + (s3 == s4)); // true, as s3 and s4 reference the same string literal in the string
pool
}
}

Output

Page 68 of 102
Practical 69
Create a program that sums a list of numbers entered by the user. it converts the string
representation to each number into an int using parseInt().

Source Code:

import java.util.Scanner; public class


SumOfNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); System.out.print("Enter
numbers separated by spaces: "); String input = scanner.nextLine();

// Split the input string by spaces


String[] numbersAsString = input.split(" ");

int sum = 0;
for (String numberAsString : numbersAsString) { try {
// Convert each number string to an integer using parseInt() int num =
Integer.parseInt(numberAsString);
sum += num;
} catch (NumberFormatException e) { System.out.println("Invalid number:
" + numberAsString);
}
}
System.out.println("Sum of the numbers: " + sum);
scanner.close();
}
}

Output

Page 69 of 102
Practical 70
Create a program that sums a list of numbers entered by the user, it converts the string representation
to each number into an int using parseInt().

Source Code:

import java.util.Scanner;
public class NumberConversion { public static
void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();

// Convert to binary
String binary = Integer.toBinaryString(number); System.out.println("Binary
representation: " + binary);

// Convert to hexadecimal
String hexadecimal = Integer.toHexString(number); System.out.println("Hexadecimal
representation: " + hexadecimal);

// Convert to octal
String octal = Integer.toOctalString(number); System.out.println("Octal
representation: " + octal);

scanner.close();
}
}

Output

Page 70 of 102
Practical 71
Create a program to demonstrate various vector operation

Source Code:
import java.util.Scanner;
class Vector { private double
x; private double y;
private double z;
public Vector(double x, double y, double z) { this.x = x;
this.y = y; this.z = z;
}
// Vector addition
public Vector add(Vector v) {
return new Vector(this.x + v.x, this.y + v.y, this.z + v.z);
}
// Vector subtraction
public Vector subtract(Vector v) {
return new Vector(this.x - v.x, this.y - v.y, this.z - v.z);
}
// Dot product of two vectors
public double dotProduct(Vector v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
// Cross product of two vectors public Vector
crossProduct(Vector v) {
double newX = this.y * v.z - this.z * v.y; double
newY = this.z * v.x - this.x * v.z; double newZ =
this.x * v.y - this.y * v.x; return new Vector(newX,
newY, newZ);
}
// Magnitude of the vector public
double magnitude() {
return Math.sqrt(x * x + y * y + z * z);
}
// Print the vector public void
print() {
System.out.println("(" + x + ", " + y + ", " + z + ")");
}
}
public class VectorOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); System.out.println("Enter the
components of vector v1:"); System.out.print("x: ");
double x1 = scanner.nextDouble(); System.out.print("y: ");
double y1 = scanner.nextDouble(); System.out.print("z: ");
double z1 = scanner.nextDouble(); System.out.println("\nEnter the
components of vector v2:"); System.out.print("x: ");
double x2 = scanner.nextDouble(); System.out.print("y: ");

Page 71 of 102
double y2 = scanner.nextDouble();
System.out.print("z: ");
double z2 = scanner.nextDouble(); Vector v1
= new Vector(x1, y1, z1); Vector v2 = new
Vector(x2, y2, z2);
System.out.println("\nVector v1:");
v1.print();
System.out.println("Magnitude of v1: " + v1.magnitude());
System.out.println("\nVector v2:");
v2.print();
System.out.println("Magnitude of v2: " + v2.magnitude());
// Vector addition
System.out.println("\nVector addition (v1 + v2):"); Vector sum
= v1.add(v2);
sum.print();
// Vector subtraction
System.out.println("\nVector subtraction (v1 - v2):"); Vector
difference = v1.subtract(v2); difference.print();
// Dot product
System.out.println("\nDot product (v1 . v2): " + v1.dotProduct(v2));
// Cross product
System.out.println("\nCross product (v1 x v2):"); Vector
crossProduct = v1.crossProduct(v2); crossProduct.print();
scanner.close();
}
}

Output

Page 72 of 102
Practical 72

Create a program to use scanner to compute an average of the values in the file

Source Code:

import java.io.File;
import java.io.FileNotFoundException; import
java.util.Scanner;
public class AverageFromFile {
public static void main(String[] args) {
String fileName = "values.txt"; // Specify the file name try {
File file = new File(fileName); // Open the file
Scanner scanner = new Scanner(file); // Create a Scanner to read from the file double sum = 0;
int count = 0;
// Read each value from the file and compute sum and count while
(scanner.hasNextDouble()) {
double value = scanner.nextDouble(); sum +=
value;
count++;
}
scanner.close(); // Close the Scanner if (count >
0) {
double average = sum / count;
System.out.println("Average of values in the file: " + average);
} else {
System.out.println("No values found in the file.");
}
}
catch (FileNotFoundException e) { System.err.println("File not
found: " + fileName);
}
}
}

Output

Page 72 of 102
Practical 73

Write a program declaring a class rectangle with data members length and breadth and member
functions input, output and CalcArea

Source Code:

import java.util.Scanner; public


class Rectangle { private double
length;
private double breadth;
// Method to input length and breadth public void
input() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter length: ");
length = scanner.nextDouble();
System.out.print("Enter breadth: "); breadth =
scanner.nextDouble();
}
// Method to output length and breadth public void
output() {
System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
}
// Method to calculate area of rectangle public
double calcArea() {
return length * breadth;
}

public static void main(String[] args) { Rectangle


rectangle = new Rectangle(); rectangle.input(); // Input
length and breadth System.out.println("\nRectangle
details:");
rectangle.output(); // Output length and breadth
System.out.println("Area of rectangle: " + rectangle.calcArea()); // Calculate and print area
}
}

Output

Page 73 of 102
Practical 74
Write a program to demonstrate use of method, overloading to calculate area of square, rectangle
and triangle.
Source Code:
import java.util.Scanner; public class
AreaCalculator {
// Method to calculate area of a square
public static double calculateArea(double side) { return side *
side;
}
public static double calculateArea(double length, double breadth) { return length
* breadth;
}
public static double calculateArea(double base, double height, String shape) { if
(shape.equalsIgnoreCase("triangle")) {
return 0.5 * base * height;
} else {
return -1; // Invalid shape
}}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the side length of the square: "); double side =
scanner.nextDouble();
double squareArea = calculateArea(side); System.out.println("Area of the
square: " + squareArea);
System.out.print("\nEnter the length of the rectangle: "); double length =
scanner.nextDouble(); System.out.print("Enter the breadth of the
rectangle: "); double breadth = scanner.nextDouble();
double rectangleArea = calculateArea(length, breadth); System.out.println("Area of the
rectangle: " + rectangleArea);
System.out.print("\nEnter the base length of the triangle: "); double base
= scanner.nextDouble(); System.out.print("Enter the height of the
triangle: "); double height = scanner.nextDouble();
double triangleArea = calculateArea(base, height, "triangle"); if
(triangleArea == -1) {
System.out.println("Invalid shape entered.");
} else {
System.out.println("Area of the triangle: " + triangleArea);
}
scanner.close();
}}

Output

Page 75 of 102
Practical 75
Write a program to demonstrate the use of static variable, static method and static block.

Source Code:

public class StaticDemo {


// Static variable static int
count = 0;

// Static block static {


System.out.println("Static block executed."); count = 10; //
Initializing the static variable
}

// Static method
static void displayCount() {
System.out.println("Count: " + count);
}

public static void main(String[] args) {


// Calling the static method displayCount();

// Incrementing the static variable count++;

// Calling the static method again


displayCount();
}
}

Output

Page 76 of 102
Practical 76
Write a program to demonstrate the concept of “this”

Source Code:

public class Person { private


String name;
public Person(String name) { this.name =
name;
}

public void printInfo() { System.out.println("Name: " +


this.name); this.sayHello();
}

public void sayHello() { System.out.println("Hello, I'm " +


this.name);
}

public static void main(String[] args) { Person


person1 = new Person("Alice");
person1.printInfo();
Person person2 = new Person("Bob"); person2.printInfo();
}
}

Output

Page 77 of 102
Practical 77
Write a program to demonstrate multilevel and hierarchical inheritance.

Source Code:
// Base class class Animal
{
void eat() {
System.out.println("Animal is eating...");
}
}
// Subclass inheriting from Animal class Dog
extends Animal {
void bark() {
System.out.println("Dog is barking...");
}
}
// Subclass inheriting from Dog class
Labrador extends Dog {
void color() {
System.out.println("Labrador is brown in color.");
}
}
// Another subclass inheriting from Animal class Cat
extends Animal {
void meow() {
System.out.println("Cat is meowing...");
}
}

public class InheritanceDemo {


public static void main(String[] args) {

// Multilevel inheritance
Labrador labrador = new Labrador(); labrador.eat(); //
Inherited from Animal class labrador.bark(); // Inherited
from Dog class labrador.color(); // Specific to Labrador
class System.out.println();

// Hierarchical inheritance Cat cat =


new Cat();
cat.eat(); // Inherited from Animal class
cat.meow(); // Specific to Cat class
}
}

Output

Page 78 of 102
Practical 78
Write a program to use super() to invoke base class constructor

Source Code:

// Base class class Animal


{
String name;
// Base class constructor Animal(String name)
{
this.name = name;
}
void display() { System.out.println("Name: " +
name);
}
}

// Subclass inheriting from Animal class Dog


extends Animal {
String breed;
// Subclass constructor invoking base class constructor using super() Dog(String name,
String breed) {
super(name); // Calling base class constructor this.breed =
breed;
}
void display() {
super.display(); // Invoking display() method of base class
System.out.println("Breed: " + breed);
}
}

public class SuperConstructorDemo { public static


void main(String[] args) {
Dog dog = new Dog("Buddy", "Labrador"); dog.display();
}
}

Output

Page 78 of 102
Practical 79
Write a program to demonstrate runtime polymorphism.

Source Code:
Animal {
makeSound() {
System.out.println("Animal makes a sound");
}
}
// Subclass Dog inheriting from
Animal class Dog extends
Animal {
// Overriding makeSound method of base class
@Override
void makeSound() {
System.out.println("Dog
barks");
}
}
// Subclass Cat inheriting from
Animal class Cat extends
Animal {
// Overriding makeSound method of base class
@Override
void makeSound() {
System.out.println("Cat
meows");
}
}

public class
RuntimePolymorphismDemo {
public static void main(String[]
args) {
// Creating objects of Dog and Cat
class Animal dog = new Dog();
Animal cat = new Cat();
// Calling makeSound method of Dog class
dog.makeSound(); // Output: Dog barks
// Calling makeSound method of Cat class
cat.makeSound(); // Output: Cat meows
}
}

Output

Page 79 of 102
Practical 80
Write a program to demonstrate the concept of aggregation.

Source Code:

class Course {
private String name;
private int creditHours;
public Course(String name, int creditHours) {
this.name = name;
this.creditHours = creditHours;
}
public int getCreditHours() {
return creditHours;
}
}
class Student {
private String name;
private String id;
private Course[] courses;
private int numCourses;

public Student(String name, String id, int maxCourses) {


this.name = name;
this.id = id;
courses = new Course[maxCourses];
numCourses = 0;
}

public void addCourse(Course course) {


if (numCourses < courses.length) {
courses[numCourses] = course;
numCourses++;
} else {
System.out.println("Cannot add more courses. Maximum courses reached.");
}
}

public int totalCreditHours() {


int total = 0;
for (int i = 0; i < numCourses; i++) {
total += courses[i].getCreditHours();
}
return total;
}
}

public class AggregationExample {


public static void main(String[] args) {

Page 80 of 102
// Creating Course objects
Course mathCourse = new Course("Mathematics", 4);
Course physicsCourse = new Course("Physics", 3);
Course chemistryCourse = new Course("Chemistry", 3);

// Creating Student object


Student student1 = new Student("Alice", "12345", 5);

// Adding courses to the student


student1.addCourse(mathCourse);
student1.addCourse(physicsCourse);
student1.addCourse(chemistryCourse);

// Displaying total credit hours


System.out.println("Total credit hours for " + student1.getName() + ": " +
student1.totalCreditHours());
}
}

Output:

Page 81 of 102
Practical 81
Write a program to demonstrate the concept abstract class with constructor and ‘final’
method

Source Code:

abstract class Shape {


private String name;

// Constructor for Shape class


public Shape(String name) {
this.name = name;
}

// Abstract method to calculate area


public abstract double calculateArea();

// Final method to display information about the shape


public final void displayInfo() {
System.out.println("Shape: " + name);
System.out.println("Area: " + calculateArea());
}
}

class Rectangle extends Shape {


private double width;
private double height;

// Constructor for Rectangle class


public Rectangle(String name, double width, double height) {
super(name);
this.width = width;
this.height = height;
}

// Implementation of calculateArea method for Rectangle


@Override
public double calculateArea() {
return width * height;
}
}

class Circle extends Shape {


private double radius;

Page 82 of 102
// Constructor for Circle class
public Circle(String name, double radius) {
super(name);
this.radius = radius;
}

// Implementation of calculateArea method for Circle


@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

public class AbstractClassExample {


public static void main(String[] args) {
// Creating Rectangle object
Rectangle rectangle = new Rectangle("Rectangle", 5, 4);
rectangle.displayInfo();

System.out.println();

// Creating Circle object


Circle circle = new Circle("Circle", 3);
circle.displayInfo();
}
}

Output:

Page 83 of 102
Practical 82
Write a program to demonstrate the concept of interface when two interfaces have
unique methods and same data members.

Source Code:

interface Shape {
double PI = 3.14; // Common data member

double calculateArea(); // Unique method


}

interface Drawable {
void draw(); // Unique method
}

class Circle implements Shape, Drawable {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return PI * radius * radius;
}

@Override
public void draw() {
System.out.println("Drawing Circle...");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Circle circle = new Circle(5);
System.out.println("Area of circle: " + circle.calculateArea());
circle.draw();
}
}

Output:

Page 84 of 102
Practical 83
Write a program to demonstrate checked exceptions during file handling..

Source Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class FileHandlingExample {


public static void main(String[] args) {
try {
// Attempt to read from a file that does not exist
File file = new File("nonexistent_file.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
// Handle the FileNotFoundException by printing an error message
System.out.println("File not found: " + e.getMessage());
}
}
}

Output:

Page 85 of 102
Practical 84
Write a program to demonstrate unchecked exceptions.

Source Code:

public class UncheckedExceptionExample {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int index = 6; // Trying to access an index that is out of bounds

try {
int value = numbers[index]; // Potential ArrayIndexOutOfBoundsException
System.out.println("Value at index " + index + ": " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index out of bounds.");
}

// Attempting division by zero


int dividend = 10;
int divisor = 0;

try {
int result = dividend / divisor; // Potential ArithmeticException
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero.");
}
}
}

Output:

Page 86 of 102
Practical 85
Write a program to demonstrate creation of multiple child threads.

Source Code:

class ChildThread extends Thread {


public ChildThread(String name) {
super(name);
}

public void run() {


System.out.println("Thread " + getName() + " is running.");
try {
Thread.sleep(2000); // Simulate some task being performed
} catch (InterruptedException e) {
System.out.println("Thread " + getName() + " interrupted.");
}
System.out.println("Thread " + getName() + " finished.");
}
}

public class MultipleThreadsExample {


public static void main(String[] args) {
// Creating multiple child threads
ChildThread thread1 = new ChildThread("Thread 1");
ChildThread thread2 = new ChildThread("Thread 2");
ChildThread thread3 = new ChildThread("Thread 3");

// Starting the threads


thread1.start();
thread2.start();
thread3.start();
}
}

Output:

Page 87 of 102
Practical 86
Write a program to use Byte stream class to read from a text file and display the
content on the output screen.

Source Code:

import java.io.FileInputStream;
import java.io.IOException;

public class ByteStreamExample {


public static void main(String[] args) {
FileInputStream inputStream = null;

try {
// Open the file
inputStream = new FileInputStream("example.txt");

// Read bytes from the file and display them as characters


int character;
while ((character = inputStream.read()) != -1) {
System.out.print((char) character);
}
} catch (IOException e) {
System.out.println("Error reading the file: " + e.getMessage());
} finally {
try {
// Close the file
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
System.out.println("Error closing the file: " + e.getMessage());
}
}
}
}

Output:

Page 88 of 102
Practical 87
Write a program to demonstrate any event handling.

Source Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class EventHandlingExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Event Handling Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Button clicked!");
}
});
frame.getContentPane().add(button, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}

Output:

Page 89 of 102
Practical 88
Create a class employee which have name, age and address of employee, include
methods getdata() and showdata(), getdata() takes the input from the user, showdata()
display the data in following format:
Name:
Age:
Address:

Source Code:

import java.util.Scanner;
public class Employee {
private String name;
private int age;
private String address;
public void getData() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name: ");
this.name = scanner.nextLine();
System.out.print("Enter age: ");
this.age = scanner.nextInt();
scanner.nextLine(); // Consume newline character
System.out.print("Enter address: ");
this.address = scanner.nextLine();
}
public void showData() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
public static void main(String[] args) {
Employee employee = new Employee();
employee.getData();
System.out.println("\nEmployee Details:");
employee.showData();
}
}

Output:

Page 90 of 102
Practical 89
Write a Java program to perform basic Calcultor operations. Make a menu driven
program to select operation to perform(+,-,*,/). Take 2 integers and perform operation
as chosen by user.

Source Code:

import java.util.Scanner;

public class Calculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Choose operation:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.println("5. Exit");

System.out.print("Enter your choice: ");


int choice = scanner.nextInt();

if (choice == 5) {
System.out.println("Exiting calculator...");
break;
}

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


double num1 = scanner.nextDouble();

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


double num2 = scanner.nextDouble();

switch (choice) {
case 1:
System.out.println("Result: " + (num1 + num2));
break;
case 2:
System.out.println("Result: " + (num1 - num2));
break;
case 3:
System.out.println("Result: " + (num1 * num2));
break;
case 4:
if (num2 == 0) {
System.out.println("Error: Division by zero!");
} else {

Page 91 of 102
System.out.println("Result: " + (num1 / num2));
}
break;
default:
System.out.println("Invalid choice! Please select again.");
}
}

scanner.close();
}
}

Output:

Page 92 of 102
Practical 90
Write a program to make use of BufferedStream to read lines from the keyboard until
“STOP” is typed.

Source Code:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class BufferedStreamExample {


public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

try {
System.out.println("Enter lines (type 'STOP' to end):");
String line;
while (!(line = reader.readLine()).equals("STOP")) {
System.out.println("You entered: " + line);
}
} catch (IOException e) {
System.out.println("Error reading input: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.out.println("Error closing BufferedReader: " + e.getMessage());
}
}
}
}

Output:

Page 93 of 102
Practical 91
Write a program declaring a Java class called
SavingsAccount with members “accountNumber” and “Balance”. Provide members
functions as “depositAmount()” and “withdrawAmount()”. If user tries to withdraw an
amount greater than their balance them throw a user defined exception

Source Code:
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}}
class SavingsAccount {
private String accountNumber;
private double balance;
public SavingsAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}
public void depositAmount(double amount) {
balance += amount;
System.out.println("Amount deposited successfully. New balance: " + balance);
}
public void withdrawAmount(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Insufficient funds! Cannot withdraw amount greater
than balance.");
} else {
balance -= amount;
System.out.println("Amount withdrawn successfully. New balance: " + balance);
}}
public double getBalance() {
return balance;
}}
public class SavingsAccountExample {
public static void main(String[] args) {
SavingsAccount account = new SavingsAccount("12345", 1000);
try {
account.depositAmount(500);
account.withdrawAmount(200);
account.withdrawAmount(1000); // This should throw an exception
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}}}

Output:

Page 94 of 102
Practical 92
Write a program creating 2 threads using Runnable interface. Print your name in
“run()” method of first class and “Hello Java ” in “run ()” method of second thread.

Source Code:

public class MyNamePrinter implements Runnable {


@Override
public void run() {
System.out.println("My name is ChatGPT.");
}
}

public class HelloWorldPrinter implements Runnable {


@Override
public void run() {
System.out.println("Hello Java");
}
}

public class RunnableExample {


public static void main(String[] args) {
// Creating instances of Runnable implementations
Runnable myNamePrinter = new MyNamePrinter();
Runnable helloWorldPrinter = new HelloWorldPrinter();

// Creating threads using the Runnable instances


Thread thread1 = new Thread(myNamePrinter);
Thread thread2 = new Thread(helloWorldPrinter);

// Starting the threads


thread1.start();
thread2.start();
}
}

Output:

Page 95 of 102
Practical 93
Write a program that uses swings to display a combination of RGB using scrollbars.

Source Code:

import java.awt.*;
import java.awt.event.*;

public class ScrollDemo extends Frame implements AdjustmentListener


{
Scrollbar redScroll, greenScroll, blueScroll;
Label redLabel, greenLabel, blueLabel;
Panel p1;
public ScrollDemo()
{
addWindowListener(new MyWindowAdapter());
setBackground(Color.lightGray);
p1 = new Panel();
p1.setLayout(new GridLayout(3, 2, 5, 5));
redScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 0, 0, 255);
p1.add(redLabel = new Label("RED"));
redLabel.setBackground(Color.white);
p1.add(redScroll);
greenScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 0, 0, 255);
p1.add(greenLabel = new Label("GREEN"));
greenLabel.setBackground(Color.white);
p1.add(greenScroll);
blueScroll = new Scrollbar(Scrollbar.HORIZONTAL, 0, 0, 0, 255);
p1.add(blueLabel = new Label("BLUE"));
blueLabel.setBackground(Color.white);
p1.add(blueScroll);
redScroll.addAdjustmentListener(this);
greenScroll.addAdjustmentListener(this);
blueScroll.addAdjustmentListener(this);
add(p1,"South");
setTitle("Playing With Colors");
setSize(450,325);
setVisible(true);
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
int rv = redScroll.getValue();
int gv = greenScroll.getValue();
int bv = blueScroll.getValue();
redLabel.setText("RED: "+ rv);
greenLabel.setText("GREEN: "+ gv);
blueLabel.setText("BLUE: "+ bv);
Color clr1 = new Color(rv, gv, bv);
setBackground(clr1);

Page 96 of 102
}
public static void main(String args[])
{
new ScrollDemo();
}
}
class MyWindowAdapter extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

Output:

Page 97 of 102
Practical 94
Write a swing application that uses at least 5 swing controls.

Source Code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class SwingControlsExample extends JFrame implements ActionListener {


private JLabel label;
private JTextField textField;
private JButton button;
private JComboBox<String> comboBox;
private JCheckBox checkBox;
private JRadioButton radioButton1;
private JRadioButton radioButton2;
private ButtonGroup buttonGroup;

public SwingControlsExample() {
setTitle("Swing Controls Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());

label = new JLabel("Enter your name:");


add(label);

textField = new JTextField(20);


add(textField);

button = new JButton("Submit");


button.addActionListener(this);
add(button);

comboBox = new JComboBox<>(new String[]{"Option 1", "Option 2", "Option 3"});


add(comboBox);

checkBox = new JCheckBox("Enable");


add(checkBox);

radioButton1 = new JRadioButton("Option 1");


radioButton2 = new JRadioButton("Option 2");
buttonGroup = new ButtonGroup();

Page 98 of 102
buttonGroup.add(radioButton1);
buttonGroup.add(radioButton2);
add(radioButton1);
add(radioButton2);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
String name = textField.getText();
String selectedOption = (String) comboBox.getSelectedItem();
boolean enabled = checkBox.isSelected();
String radioOption = radioButton1.isSelected() ? "Option 1" : "Option 2";
JOptionPane.showMessageDialog(this, "Name: " + name + "\nSelected Option: " +
selectedOption +
"\nCheck Box Enabled: " + enabled + "\nRadio Button Selected: " +
radioOption);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SwingControlsExample();
}
});
}
}

Output:

Page 99 of 102
Practical 95
Write a program to implement border layout using Swing.

Source Code:

import javax.swing.*;
import java.awt.*;
public class BorderLayoutExample extends JFrame {
public BorderLayoutExample() {
setTitle("BorderLayout Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("North");
JButton button2 = new JButton("South");
JButton button3 = new JButton("East");
JButton button4 = new JButton("West");
JButton button5 = new JButton("Center");
setLayout(new BorderLayout());
add(button1, BorderLayout.NORTH);
add(button2, BorderLayout.SOUTH);
add(button3, BorderLayout.EAST);
add(button4, BorderLayout.WEST);
add(button5, BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new BorderLayoutExample();
}});}}

Output:

Page 100 of 102


Practical 96
Write a java program to insert and update details data in the database.

Source Code:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DatabaseExample {


// JDBC URL, username, and password of MySQL server
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "username";
private static final String PASSWORD = "password";

// SQL statements for inserting and updating data


private static final String INSERT_SQL = "INSERT INTO students (id, name, age)
VALUES (?, ?, ?)";
private static final String UPDATE_SQL = "UPDATE students SET age = ? WHERE id =
?";

public static void main(String[] args) {


try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Open a connection
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);

// Insert data into database


insertData(conn, 1, "John", 25);

// Update data in database


updateData(conn, 1, 26);

// Close the connection


conn.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

private static void insertData(Connection conn, int id, String name, int age) throws
SQLException {
// Create a prepared statement
PreparedStatement preparedStatement = conn.prepareStatement(INSERT_SQL);

Page 101 of 102


// Set parameters
preparedStatement.setInt(1, id);
preparedStatement.setString(2, name);
preparedStatement.setInt(3, age);

// Execute the query


int rowsInserted = preparedStatement.executeUpdate();
if (rowsInserted > 0) {
System.out.println("Data inserted successfully.");
}

// Close the prepared statement


preparedStatement.close();
}

private static void updateData(Connection conn, int id, int age) throws SQLException {
// Create a prepared statement
PreparedStatement preparedStatement = conn.prepareStatement(UPDATE_SQL);

// Set parameters
preparedStatement.setInt(1, age);
preparedStatement.setInt(2, id);

// Execute the query


int rowsUpdated = preparedStatement.executeUpdate();
if (rowsUpdated > 0) {
System.out.println("Data updated successfully.");
}

// Close the prepared statement


preparedStatement.close();
}
}

Output:

Page 102 of 102


Practical 97
Write a java program to retrieve data from a database and display it on GUI.

Source Code:

import javax.swing.*;
import java.awt.*;
import java.sql.*;
public class DatabaseGUIExample extends JFrame {
private JTable table;
private JScrollPane scrollPane;
public DatabaseGUIExample() {
setTitle("Database Data Viewer");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel tableModel = new DefaultTableModel();
table = new JTable(tableModel);
scrollPane = new JScrollPane(table);
add(scrollPane);
fetchData();
setVisible(true);
}
private void fetchData() {
String URL = "jdbc:mysql://localhost:3306/mydatabase"
String USER = "username";
String PASSWORD = "password";
String SQL = "SELECT * FROM students";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
Statement stmt = conn.createStatement();
ResultSet resultSet = stmt.executeQuery(SQL);
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
for (int i = 1; i <= columnCount; i++) {
tableModel.addColumn(metaData.getColumnName(i));
}
while (resultSet.next()) {
Object[] rowData = new Object[columnCount];
for (int i = 1; i <= columnCount; i++) {
rowData[i - 1] = resultSet.getObject(i);
}
tableModel.addRow(rowData);
}
resultSet.close();
stmt.close();
conn.close();
} catch (ClassNotFoundException | SQLException e) {

Page 103 of 102


e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DatabaseGUIExample();
}
});
}
}

Output:

Page 104 of 102

You might also like