Java File Ishan Sharma
Java File Ishan Sharma
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);
// Calculate the area of the circle using the formula: Area = π * radius^2
double area = Math.PI * radius * radius;
Output:
Page 1 of 102
Practical 2
Create a program to find the average of an array of values
Source code:
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);
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);
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;
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);
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;
Output:
Page 8 of 102
Practical 9
Create a program to demonstrate a two dimensional array
Source code:
Output:
Page 9 of 102
Practical 10
Create a program to demonstrate bitwise logical operators
Source code:
Output:
Page 10 of 102
Practical 11
Create a program to demonstrate boolean logical operators
Source code:
Output:
Page 11 of 102
Practical 12
Create a program to demonstrate left shifting a byte value
Source code:
int i;
i = a << 2;
b = (byte) (a << 2);
Output:
Page 12 of 102
Practical 13
Create a program to demonstrate unsigned shifting a byte value
Source code:
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:
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:
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:
Output:
Page 16 of 102
Practical 17
Create a program to test for primes
Source code:
num = 14;
if (num < 2)
isPrime = false;
else
isPrime = true;
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:
Output:
Page 18 of 102
Practical 19
Create a program to demonstrate if-else-if statements
Source code:
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;
}
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));
}
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:
// Constructor
Person(String name, int age) {
this.name = name;
this.age = age;
}
Output:
Page 27 of 102
Practical 30
Create a program to demonstrate string and string methods
Source code:
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
}
Output:
Page 29 of 102
Practical 32
Create a program to demonstrate the use of abstract classes and methods
Source code:
Output:
Page 30 of 102
Practical 33
Create a program to understand class hierarchy
Source code:
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");
}
}
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");
}
}
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:
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");
}
}
Output:
Page 39 of 102
Practical 42
Create a program to demonstrate the use of package
Source code:
// HelloWorld.java
import mypackage.Greetings; // Importing Greetings class from mypackage
Output:
Page 40 of 102
Practical 43
Create a program to demonstrate the inheritance of packages
Source code:
import animals.Animal;
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();
}
Output:
Page 43 of 102
Practical 46
Create a program to demonstrate the use of default method
Source code:
// Default method
default void sleep() {
System.out.println("Animal is sleeping");
}
}
// 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();
}
// 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:
}
}
}
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 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:
}
}
Output
Page 49 of 102
Practical 53
Create a program to create a custom exception time
Source Code:
} catch (CustomTimeException e) {
Output
Page 50 of 102
Practical 54
Create a program to demonstrate nested try statements
Source Code:
} catch (ArithmeticException e) {
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:
} catch (IllegalArgumentException e) {
} else {
Output
Page 52 of 102
Practical 56
Create a program to control the main thread
Source Code:
} catch (InterruptedException e) {
Output
Page 53 of 102
Practical 57
Create a program to use join() to wait for the thread to finish
Source Code:
@Override
{
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:
Output
Page 55 of 102
Practical 59
Create a program to demonstrate multiple threads
Source Code:
Output
Page 56 of 102
Practical 60
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:
Output
Page 58 of 102
Practical 62
Create a program to demonstrate that autoboxing and unboxing occurs inside expressions.
Source Code:
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
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();
// 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:
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:
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:
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:
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:
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:
// Static method
static void displayCount() {
System.out.println("Count: " + count);
}
Output
Page 76 of 102
Practical 76
Write a program to demonstrate the concept of “this”
Source Code:
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...");
}
}
// 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();
Output
Page 78 of 102
Practical 78
Write a program to use super() to invoke base class constructor
Source Code:
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;
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);
Output:
Page 81 of 102
Practical 81
Write a program to demonstrate the concept abstract class with constructor and ‘final’
method
Source Code:
Page 82 of 102
// Constructor for Circle class
public Circle(String name, double radius) {
super(name);
this.radius = radius;
}
System.out.println();
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
interface Drawable {
void draw(); // Unique method
}
@Override
public double calculateArea() {
return PI * radius * radius;
}
@Override
public void draw() {
System.out.println("Drawing Circle...");
}
}
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;
Output:
Page 85 of 102
Practical 84
Write a program to demonstrate unchecked exceptions.
Source Code:
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.");
}
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:
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;
try {
// Open the file
inputStream = new FileInputStream("example.txt");
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;
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");
if (choice == 5) {
System.out.println("Exiting calculator...");
break;
}
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;
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:
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.*;
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 SwingControlsExample() {
setTitle("Swing Controls Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
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:
Source Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
// Open a connection
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
private static void insertData(Connection conn, int id, String name, int age) throws
SQLException {
// Create a prepared statement
PreparedStatement preparedStatement = conn.prepareStatement(INSERT_SQL);
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);
Output:
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) {
Output: