javacode-GQT_merged
javacode-GQT_merged
Code:
public class PrintName {
public static void main(String[] args) {
System.out.println("Ningamma");
}
}
Output:
Ningamma
2. Write a program to print the sum of all even numbers from 1 to 100?
Code:
public class SumOfEvenNumbers {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
sum += i;
}
}
System.out.println("The sum of all even numbers from 1 to 100 is: " + sum);
}
}
Output:
The sum of all even numbers from 1 to 100 is: 2550
3. Write a program to swap two numbers without using a temporary variable?
Code:
public class SwapNumbers {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
System.out.println("Before swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After swapping:");
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);
}
}
Output:
Before swapping:
num1 = 10
num2 = 20
After swapping:
num1 = 20
num2 = 10
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
Output:
29 is a prime number.
System.out.println("\nThe quadratic equation is: " + a + "x^2 + " + b + "x + " + c + " = 0");
if (discriminant > 0) {
if (terms <= 0) {
System.out.println("Please enter a positive integer.");
} else {
System.out.println("The Fibonacci series up to " + terms + " terms is:");
if (secondLargest == Integer.MIN_VALUE) {
System.out.println("There is no second largest element.");
} else {
System.out.println("The second largest element is: " + secondLargest);
}
}
scanner.close();
}
}
Output:
Enter the number of elements in the array:
5
Enter the elements of the array:
12 45 78 34 56
The second largest element is: 56
Operators:
26. Write a program to perform arithmetic operations (+, -, *, /) on two numbers.?
Code:
import java.util.Scanner;
27. Write a program to perform bitwise AND, OR, and XOR operations on two integers.?
Code:
import java.util.Scanner;
49. Write a program to print the multiplication table of a given number using for loop.?
Code:
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
}
}
Output:
5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
50. Write a program to check whether a given number is Armstrong or not using while loop.?
Code:
import java.util.Scanner;
public class ArmstrongNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int original = num, sum = 0;
while (num > 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
System.out.println(sum == original ? "Armstrong Number" : "Not Armstrong Number");
}
}
Output:
153
Armstrong Number
ARRAY:
51. Write a program to find the sum of all elements in an array.?
Code:
import java.util.Scanner;
public class SumArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
sum += arr[i];
}
System.out.println(sum);
}
}
Output:
5
12345
15
52. Write a program to find the largest and smallest elements in an array.?
Code:
import java.util.Scanner;
public class MinMaxArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
int max = arr[0], min = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
System.out.println(max + " " + min);
}
}
Output:
5
12345
51
53. Write a program to copy elements from one array to another.?
Code:
import java.util.Scanner;
public class CopyArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr1 = new int[n];
int[] arr2 = new int[n];
for (int i = 0; i < n; i++) arr1[i] = sc.nextInt();
for (int i = 0; i < n; i++) arr2[i] = arr1[i];
for (int i : arr2) System.out.print(i + " ");
}
}
Output:
5
12345
12345
54. Write a program to remove duplicate elements from an array?
Code:
import java.util.Scanner;
public class RemoveDuplicates {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
for (int i = 0; i < n; i++) {
boolean isDuplicate = false;
for (int j = 0; j < i; j++) if (arr[i] == arr[j]) isDuplicate = true;
if (!isDuplicate) System.out.print(arr[i] + " ");
}
}
}
Output:
6
122344
1234
55. Write a program to reverse an array.?
Code:
import java.util.Scanner;
public class ReverseArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
for (int i = n - 1; i >= 0; i--) System.out.print(arr[i] + " ");
}
}
Output:
5
12345
54321
56. Write a program to sort an array in ascending and descending order. ?
Code:
import java.util.Arrays;
import java.util.Scanner;
public class SortArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
Arrays.sort(arr);
for (int i : arr) System.out.print(i + " ");
System.out.println();
for (int i = n - 1; i >= 0; i--) System.out.print(arr[i] + " ");
}
}
Output:
5
52314
12345
54321
57. Write a program to find the frequency of each element in an array.?
Code:
import java.util.Scanner;
public class FrequencyArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
boolean[] visited = new boolean[n];
for (int i = 0; i < n; i++) {
if (!visited[i]) {
int count = 1;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
visited[j] = true;
}
}
System.out.println(arr[i] + " " + count);
}
}
}
}
Output: 5
12233
11
22
32
58. Write a program to merge two sorted arrays?
Code:
import java.util.Arrays;
public class MergeSortedArrays {
public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};
int[] merged = new int[arr1.length + arr2.length];
int i = 0, j = 0, k = 0;
while (i < arr1.length && j < arr2.length) {
if (arr1[i] < arr2[j]) {
merged[k++] = arr1[i++];
} else {
merged[k++] = arr2[j++];
}
}
while (i < arr1.length) {
merged[k++] = arr1[i++];
}
while (j < arr2.length) {
merged[k++] = arr2[j++];
}
System.out.println("Merged Array: " + Arrays.toString(merged));
}
}
Output:
Merged Array: [1, 2, 3, 4, 5, 6]
59. Write a program to find the intersection of two arrays.?
Code:
import java.util.ArrayList;
public class IntersectionOfArrays {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {4, 5, 6, 7, 8};
Output:
Intersection: [4, 5]
60. Check if an Array is Palindrome?
Code:
public class PalindromeArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 2, 1};
boolean isPalindrome = true;
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
if (arr[i] != arr[j]) {
isPalindrome = false;
break;
}
}
System.out.println("Is Palindrome: " + isPalindrome);
}
}
Output:
Is Palindrome: true
61. Find the Sum of All Positive Numbers in an Array?
Code:
public class SumPositiveNumbers {
public static void main(String[] args) {
int[] arr = {-1, 2, 3, -4, 5};
int sum = 0;
for (int num : arr) {
if (num > 0) {
sum += num;
}
}
System.out.println("Sum of Positive Numbers: " + sum);
}
}
Output:
Sum of Positive Numbers: 10
62. Find the Sum of All Negative Numbers in an Array?
Code:
public class SumNegativeNumbers {
public static void main(String[] args) {
int[] arr = {-1, 2, -3, 4, -5};
int sum = 0;
Data types:
76. Demonstrate the Copy of Primitive Data Types in Java?
Code:
public class CopyPrimitiveDataTypes {
public static void main(String[] args) {
int a = 10;
double b = 5.5;
char c = 'A';
boolean d = true;
int x = a;
double y = b;
char z = c;
boolean w = d;
System.out.println("Copied Integer: " + x);
System.out.println("Copied Double: " + y);
System.out.println("Copied Char: " + z);
System.out.println("Copied Boolean: " + w);
}
}
Output:
Copied Integer: 10
Copied Double: 5.5
Copied Char: A
Copied Boolean: true
77. Perform Arithmetic Operations Using float and double Data Types?
Code:
public class ArithmeticOperations {
public static void main(String[] args) {
float a = 5.5f;
double b = 2.5;
System.out.println("Sum: " + (a + b));
System.out.println("Difference: " + (a - b));
System.out.println("Product: " + (a * b));
System.out.println("Quotient: " + (a / b));
}
}
Output:
Sum: 8.0
Difference: 3.0
Product: 13.75
Quotient: 2.2
97. Find the Second Largest and Second Smallest Elements in an Array?
Code:
import java.util.Arrays;
public class SecondLargestSmallest {
public static void main(String[] args) {
int[] arr = {10, 20, 4, 45, 99};
Arrays.sort(arr);
System.out.println("Second Smallest: " + arr[1]);
System.out.println("Second Largest: " + arr[arr.length - 2]);
}
}
Output:
Second Smallest: 10
Second Largest: 45
98. Find the Sum of Diagonal Elements of a Matrix?
Code:
public class MatrixDiagonalSum {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int sum = 0;
for (int i = 0; i < matrix.length; i++) {
sum += matrix[i][i];
}
System.out.println("Sum of diagonal elements: " + sum);
}
}
Output:
Sum of diagonal elements: 15
Strings:
101. Write a java code for Reverse a String?
Code:
public class ReverseString {
public static void main(String[] args) {
String str = "Hello";
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Reversed String: " + reversed);
}
}
Output:
Reversed String: olleH
Encapsulation:
151. Create a class representing a student with private member variables (name, roll number,age) and
public methods (getters and setters).?
Code:
class Student {
private String name;
private int rollNumber;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
Student student = new Student();
student.setName("Alice");
student.setRollNumber(101);
student.setAge(20);
System.out.println("Student Details:");
System.out.println("Name: " + student.getName());
System.out.println("Roll Number: " + student.getRollNumber());
System.out.println("Age: " + student.getAge());
}
}
Output:
Student Details:
Name: Alice
Roll Number: 101
Age: 20
152. Write a program to demonstrale encapsulation by accessing private member variables through
public accessor methods.?
Code:
class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static void main(String[] args) {
Person person = new Person();
person.setName("John");
person.setAge(25);
System.out.println("Person Details:");
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}
Output:
Person Details:
Name: John
Age: 25
153. Bank Account class with deposit and withdraw methods?
Code:
class BankAccount {
private int accountNumber;
private double balance;
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public double getBalance() {
return balance;
}
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
System.out.println("Deposited: $" + amount);
} else {
System.out.println("Invalid deposit amount.");
}
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.out.println("Withdrew: $" + amount);
} else {
System.out.println("Insufficient funds or invalid amount.");
}
}
public static void main(String[] args) {
BankAccount account = new BankAccount();
account.setAccountNumber(123456);
account.deposit(1000.0);
account.withdraw(300.0);
account.withdraw(800.0);
System.out.println("Account Details:");
System.out.println("Account Number: " + account.getAccountNumber());
System.out.println("Balance: $" + account.getBalance());
}
}
Output:
Deposited: $1000.0
Withdrew: $300.0
Withdrew: $800.0
Account Details:
Account Number: 123456
Balance: $0.0
154. Demonstrating encapsulation by accessing private member variables through public accessor
methods?
Code:
class EncapsulationDemo {
private String exampleVariable;
public String getExampleVariable() {
return exampleVariable;
}
public void setExampleVariable(String exampleVariable) {
this.exampleVariable = exampleVariable;
}
public static void main(String[] args) {
EncapsulationDemo demo = new EncapsulationDemo();
demo.setExampleVariable("Encapsulation Example");
System.out.println("Example Variable: " + demo.getExampleVariable());
}
}
155. Car Class with Encapsulation?
Code:
class Car {
private String model;
private String color;
private double price;
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static void main(String[] args) {
Car car = new Car();
car.setModel("Tesla Model S");
car.setColor("Red");
car.setPrice(79999.99);
System.out.println("Car Details:");
System.out.println("Model: " + car.getModel());
System.out.println("Color: " + car.getColor());
System.out.println("Price: $" + car.getPrice());
}
}
Output:
Car Details:
Model: Tesla Model S
Color: Red
Price: $79999.99
156. Book Class with Encapsulation?
Code:
class Book {
private String title;
private String author;
private double price;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static void main(String[] args) {
Book book = new Book();
book.setTitle("To Kill a Mockingbird");
book.setAuthor("Harper Lee");
book.setPrice(15.99);
System.out.println("Book Details:");
System.out.println("Title: " + book.getTitle());
Output:
Book Details:
Title: To Kill a Mockingbird
Author: Harper Lee
Price: $10.99
157. Demonstrating Encapsulation by Accessing Private Member Variables Through Public Methods?
Code:
class EncapsulationDemo {
private String exampleVariable;
public String getExampleVariable() {
return exampleVariable;
}
public void setExampleVariable(String exampleVariable) {
this.exampleVariable = exampleVariable;
}
public static void main(String[] args) {
EncapsulationDemo demo = new EncapsulationDemo();
demo.setExampleVariable("Hello, Encapsulation!");
System.out.println("Example Variable: " + demo.getExampleVariable());
}
}
Output:
Example Variable: Hello, Encapsulation!
Static:
162: Count the Number of Objects Created for a Class Using a Static Variable?
Code:
class ObjectCount {
static int count = 0;
ObjectCount() {
count++;
}
public static void main(String[] args) {
new ObjectCount();
new ObjectCount();
new ObjectCount();
System.out.println("Number of objects created: " + count);
}
}
Output:
Number of objects created: 3
163.Static Method to Find the Factorial of a Number?
Code:
class Factorial {
static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
int result = factorial(5);
System.out.println("Factorial: " + result);
}
}
Output:
Factorial: 120
164. Static Method to Calculate the Area of a Circle?
Code:
class CircleArea {
static double area(double radius) {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
double result = area(5);
System.out.println("Area of circle: " + result);
}
}
Output:
Area of circle: 78.53981633974483
Abstraction:
187. Abstract Class "Shape" with Abstract Methods "calculateArea" and "calculatePerimeter",
Implemented in Subclasses "Circle" and "Rectangle"?
Code:
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double calculateArea() {
return length * width;
}
@Override
double calculatePerimeter() {
return 2 * (length + width);
}
}
public class Main {
public static void main(String[] args) {
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());
System.out.println("Rectangle Area: " + rectangle.calculateArea());
System.out.println("Rectangle Perimeter: " + rectangle.calculatePerimeter());
}
}
Output:
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Rectangle Area: 24.0
Rectangle Perimeter: 20.0
188. Demonstrate Abstraction by Creating Objects of Subclasses and Invoking Abstract Methods?
Code:
abstract class Animal {
abstract void eat();
abstract void sleep();
}
class Dog extends Animal {
@Override
void eat() {
System.out.println("Dog is eating");
}
@Override
void sleep() {
System.out.println("Dog is sleeping");
}
}
class Cat extends Animal {
@Override
void eat() {
System.out.println("Cat is eating");
}
@Override
void sleep() {
System.out.println("Cat is sleeping");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.eat();
dog.sleep();
cat.eat();
cat.sleep();
}
}
Output:
Dog is eating
Dog is sleeping
Cat is eating
Cat is sleeping
190. Abstract Class "BankAccount" with Abstract Methods "deposit" and "withdraw", Implemented
in Subclasses "SavingsAccount" and "CurrentAccount"
Code:
abstract class BankAccount {
abstract void deposit(double amount);
abstract void withdraw(double amount);
}
class SavingsAccount extends BankAccount {
double balance = 0;
@Override
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
@Override
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}
}
class CurrentAccount extends BankAccount {
double balance = 0;
@Override
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
@Override
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount savings = new SavingsAccount();
BankAccount current = new CurrentAccount();
savings.deposit(1000);
savings.withdraw(500);
current.deposit(2000);
current.withdraw(1500);
}
}
Output:
Deposited: 1000.0
Withdrawn: 500.0
Deposited: 2000.0
Withdrawn: 1500.0
191. Abstract Class "Vehicle" with Abstract Methods "start" and "stop", Implemented in Subclasses
"Car" and "Motorcycle"?
Code:
abstract class Vehicle {
abstract void start();
abstract void stop();
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting");
}
@Override
void stop() {
System.out.println("Car is stopping");
}
}
class Motorcycle extends Vehicle {
@Override
void start() {
System.out.println("Motorcycle is starting");
}
@Override
void stop() {
System.out.println("Motorcycle is stopping");
}
}
public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle motorcycle = new Motorcycle();
car.start();
car.stop();
motorcycle.start();
motorcycle.stop();
}
}
Output:
Car is starting
Car is stopping
Motorcycle is starting
Motorcycle is stopping
193. Abstract Class "Bank" with Abstract Methods "openAccount" and "closeAccount", Implemented
in Subclasses "SavingsBank" and "CurrentBank"?
Code:
abstract class Bank {
abstract void openAccount();
abstract void closeAccount();
}
class SavingsBank extends Bank {
@Override
void openAccount() {
System.out.println("Savings Account opened");
}
@Override
void closeAccount() {
System.out.println("Savings Account closed");
}
}
class CurrentBank extends Bank {
@Override
void openAccount() {
System.out.println("Current Account opened");
}
@Override
void closeAccount() {
System.out.println("Current Account closed");
}
}
public class Main {
public static void main(String[] args) {
Bank savingsBank = new SavingsBank();
Bank currentBank = new CurrentBank();
savingsBank.openAccount();
savingsBank.closeAccount();
currentBank.openAccount();
currentBank.closeAccount();
}
}
Output:
Savings Account opened
Savings Account closed
Current Account opened
Current Account closed
194. Program to Demonstrate Abstraction by Creating Objects of Subclasses and Invoking Abstract Methods?
Code:
abstract class Animal {
abstract void eat();
abstract void sleep();
}
class Dog extends Animal {
@Override
void eat() {
System.out.println("Dog is eating");
}
@Override
void sleep() {
System.out.println("Dog is sleeping");
}
}
class Cat extends Animal {
@Override
void eat() {
System.out.println("Cat is eating");
}
@Override
void sleep() {
System.out.println("Cat is sleeping");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.eat();
dog.sleep();
cat.eat();
cat.sleep();
}
}
Output:
Dog is eating
Dog is sleeping
Cat is eating
Cat is sleeping
195. Abstract Class "Animal" with Abstract Methods "eat" and "sleep", Implemented in Subclasses
"Dog" and "Cat"?
Code:
abstract class Animal {
abstract void eat();
abstract void sleep();
}
class Dog extends Animal {
@Override
void eat() {
System.out.println("Dog is eating");
}
@Override
void sleep() {
System.out.println("Dog is sleeping");
}
}
class Cat extends Animal {
@Override
void eat() {
System.out.println("Cat is eating");
}
@Override
void sleep() {
System.out.println("Cat is sleeping");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();
dog.eat();
dog.sleep();
cat.eat();
cat.sleep();
}
}
Output:
Dog is eating
Dog is sleeping
Cat is eating
Cat is sleeping
196. Program to Demonstrate Abstraction by Creating Objects of Subclasses and Invoking Abstract
Methods?
Code:
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
@Override
double calculateArea() {
return length * width;
}
@Override
double calculatePerimeter() {
return 2 * (length + width);
}
}
class Square extends Shape {
double side;
Square(double side) {
this.side = side;
}
@Override
double calculateArea() {
return side * side;
}
@Override
double calculatePerimeter() {
return 4 * side;
}
}
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle(4, 5);
Shape square = new Square(3);
System.out.println("Rectangle Area: " + rectangle.calculateArea());
System.out.println("Rectangle Perimeter: " + rectangle.calculatePerimeter());
System.out.println("Square Area: " + square.calculateArea());
System.out.println("Square Perimeter: " + square.calculatePerimeter());
}
}
Output:
Rectangle Area: 20.0
Rectangle Perimeter: 18.0
Square Area: 9.0
Square Perimeter: 12.0
197. Abstract Class "Bank" with Abstract Methods "openAccount" and "closeAccount", Implemented
in Subclasses "SavingsBank" and "CurrentBank"?
Code:
abstract class Bank {
abstract void openAccount();
abstract void closeAccount();
}
class SavingsBank extends Bank {
@Override
void openAccount() {
System.out.println("Savings Account opened");
}
@Override
void closeAccount() {
System.out.println("Savings Account closed");
}
}
class CurrentBank extends Bank {
@Override
void openAccount() {
System.out.println("Current Account opened");
}
@Override
void closeAccount() {
System.out.println("Current Account closed");
}
}
public class Main {
public static void main(String[] args) {
Bank savings = new SavingsBank();
Bank current = new CurrentBank();
savings.openAccount();
savings.closeAccount();
current.openAccount();
current.closeAccount();
}
}
Output:
Savings Account opened
Savings Account closed
Current Account opened
Current Account closed
198. Program to Demonstrate Abstraction by Creating Objects of Subclasses and Invoking Abstract
Methods?
Code:
abstract class Vehicle {
abstract void start();
abstract void stop();
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting");
}
@Override
void stop() {
System.out.println("Car is stopping");
}
}
class Motorcycle extends Vehicle {
@Override
void start() {
System.out.println("Motorcycle is starting");
}
@Override
void stop() {
System.out.println("Motorcycle is stopping");
}
}
public class Main {
public static void main(String[] args) {
Vehicle car = new Car();
Vehicle motorcycle = new Motorcycle();
car.start();
car.stop();
motorcycle.start();
motorcycle.stop();
}
}
Output:
Car is starting
Car is stopping
Motorcycle is starting
Motorcycle is stopping
199. Abstract Class "Shape" with Abstract Methods "calculateArea" and "calculatePerimeter",
Implemented in Subclasses "Triangle" and "Circle".?
Code:
abstract class Shape {
abstract double calculateArea();
abstract double calculatePerimeter();
}
class Triangle extends Shape {
double base, height;
Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
double calculateArea() {
return 0.5 * base * height;
}
@Override
double calculatePerimeter() {
return 3 * base;
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
@Override
double calculateArea() {
return Math.PI * radius * radius;
}
@Override
double calculatePerimeter() {
return 2 * Math.PI * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape triangle = new Triangle(4, 5);
Shape circle = new Circle(7);
System.out.println("Triangle Area: " + triangle.calculateArea());
System.out.println("Triangle Perimeter: " + triangle.calculatePerimeter());
System.out.println("Circle Area: " + circle.calculateArea());
System.out.println("Circle Perimeter: " + circle.calculatePerimeter());
}
}
Output:
Triangle Area: 10.0
Triangle Perimeter: 12.0
Circle Area: 153.93804002589985
Circle Perimeter: 43.982297150257104
200. Program to Demonstrate Abstraction by Creating Objects of Subclasses and Invoking Abstract
Methods
Code:
abstract class BankAccount {
abstract void deposit(double amount);
abstract void withdraw(double amount);
}
class SavingsAccount extends BankAccount {
double balance = 0;
@Override
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
@Override
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}
}
class CurrentAccount extends BankAccount {
double balance = 0;
@Override
void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}
@Override
void withdraw(double amount) {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}
}
public class Main {
public static void main(String[] args) {
BankAccount savings = new SavingsAccount();
BankAccount current = new CurrentAccount();
savings.deposit(1000);
savings.withdraw(500);
current.deposit(2000);
current.withdraw(1500);
}
}
Output:
Deposited: 1000.0
Withdrawn: 500.0
Deposited: 2000.0
Withdrawn: 1500.0
201. Abstract Class "Vehicle" with Abstract Methods "start" and "stop", Implemented in Subclasses
"Car" and "Truck"?
Code:
abstract class Vehicle {
abstract void drive();
abstract void stop();
}
@Override
void stop() {
System.out.println("Car has stopped");
}
}
class Truck extends Vehicle {
@Override
void drive() {
System.out.println("Truck is driving");
}
@Override
void stop() {
System.out.println("Truck has stopped");
}
}
car.drive();
car.stop();
truck.drive();
truck.stop();
}
}
Output:
Car is driving
Car has stopped
Truck is driving
Truck has stopped
MULTI THREADING
package MultiThreading;
t1.start();
t2.start();
10 is not a palindrome.
package MultiThreading;
class synchronizedExample {
synchronized (this) {
count++;
return count;
}
MULTI THREADING
});
});
t1.start();
t2.start();
t1.join();
t2.join();
package MultiThreading;
t1.setPriority(Thread.MIN_PRIORITY);
MULTI THREADING
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
//4. Create a thread pool and execute multiple tasks using ExecutorService
package MultiThreading;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
executor.submit(new Task());
executor.shutdown();
package MultiThreading;
MULTI THREADING
t1.start();
t2.start();
t1.join();
t2.join();
thread1.start();
thread2.start();
Thread.sleep(500);
thread1.interrupt();
thread2.interrupt();
}
MULTI THREADING
Output:
thread1.start();
thread2.start();
Thread.sleep(500);
thread1.interrupt();
thread2.interrupt();
}
}
Output: Thread Name: Thread-1
Thread Name: Thread-0
//8. Demonstrate thread-local variables:
MULTI THREADING
threadLocal.set(threadLocal.get() + 1);
thread1.start();
thread2.start();
import java.util.concurrent.CountDownLatch;
this.latch = latch;
}
MULTI THREADING
try {
} finally {
latch.countDown();
thread1.start();
thread2.start();
latch.await();
Thread-1 is running
thread1.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.setPriority(Thread.MAX_PRIORITY);
thread2.start();
thread1.setThreadGroup(group);
thread1.start();
thread2.setThreadGroup(group);
thread2.start();
this.lock = lock;
@Override
synchronized (lock) {
}
MULTI THREADING
this.lock = lock;
@Override
synchronized (lock) {
try {
} catch (InterruptedException e) {
e.printStackTrace();
consumer.start();
MULTI THREADING
producer.start();
consumer.join();
producer.join();
threadLocal.set(threadLocal.get() + 1);
thread1.start();
thread2.start();
}
MULTI THREADING
class SharedResource {
flag = !flag;
return flag;
this.resource = resource;
while (!resource.getFlag()) {
}
MULTI THREADING
thread1.start();
thread2.start();
Thread.sleep(2000);
import java.util.concurrent.*;
executor.submit(task1);
executor.submit(task2);
executor.shutdown();
try {
if (isInterrupted()) {
return;
Thread.sleep(500);
} catch (InterruptedException e) {
}
MULTI THREADING
thread.start();
Thread.sleep(2000);
thread.interrupt();
Thread-1 is running
import java.util.concurrent.*;
@Override
return 100;
executor.shutdown();
import java.util.concurrent.*;
this.queue = queue;
@Override
try {
queue.put(1);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
this.queue = queue;
@Override
try {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
producer.start();
consumer.start();
producer.join();
consumer.join();
Consumed item 1
import java.util.concurrent.*;
};
new Thread(task).start();
Thread-1 is starting
Thread-2 is starting
Thread-0 is completed
Thread-1 is completed
Thread-2 is completed
MULTI THREADING
import java.util.concurrent.*;
this.barrier = barrier;
@Override
try {
e.printStackTrace();
}
MULTI THREADING
Thread-1 is ready
Thread-2 is ready
import java.util.concurrent.*;
this.semaphore = semaphore;
@Override
try {
semaphore.acquire();
Thread.sleep(2000);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
MULTI THREADING
Thread-1 is executing
Thread-2 is executing
Thread-3 is executing
Thread-4 is executing
import java.util.concurrent.*;
this.exchanger = exchanger;
@Override
try {
} catch (InterruptedException e) {
e.printStackTrace();
Output:
import java.util.concurrent.*;
@Override
return 100;
}
MULTI THREADING
completionService.submit(new Task());
completionService.submit(new Task());
executor.shutdown();
Result: 100
import java.util.concurrent.*;
this.queue = queue;
}
MULTI THREADING
@Override
try {
} catch (InterruptedException e) {
e.printStackTrace();
queue.transfer(1);
Thread-1 consumed: 1
import java.util.concurrent.*;
...
import java.util.concurrent.locks.*;
this.lock = lock;
this.condition = condition;
@Override
lock.lock();
try {
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
lock.lock();
try {
} finally {
lock.unlock();
Thread-1 is waiting
Thread-0 is notified
Thread-1 is notified
Interface
1. Create interfaces "Drawable" and "Resizable" with methods "draw()" and "resize()".
public class InterfaceDemo {
public static void main(String[] args) {
Shape shape = new Shape(); // Create an object of the Shape class
3. Create interfaces "Flyable" and "Swimable" with methods "fly()" and "swim()". Impler them in
classes representing a bird and a fish.
public class InterfaceDemo {
public static void main(String[] args) {
Shape shape = new Shape(); // Create an object of the Shape class
5. Create interfaces "Comparable" and "Cloneable" with methods "compareTo()" and "clone()".
Implement them in classes representing a number and a person
interface Comparable {
int compareTo(Object o);
}
interface Cloneable {
Object clone();
}
Number(int value) {
this.value = value;
}
@Override
public int compareTo(Object o) {
Number other = (Number) o;
return Integer.compare(this.value, other.value);
}
@Override
public Object clone() {
return new Number(this.value);
}
@Override
public String toString() {
return "Number: " + value;
}
}
Interface
Person(String name) {
this.name = name;
}
@Override
public int compareTo(Object o) {
Person other = (Person) o;
return this.name.compareTo(other.name);
}
@Override
public Object clone() {
return new Person(this.name);
}
@Override
public String toString() {
return "Person: " + name;
}
}
// Cloning
Number clonedNum = (Number) num1.clone();
Person clonedPerson = (Person) person1.clone();
System.out.println("Cloned Number: " + clonedNum);
System.out.println("Cloned Person: " + clonedPerson);
}
}
// Cloning
Number clonedNum = (Number) num1.clone();
Person clonedPerson = (Person) person1.clone();
System.out.println("Cloned Number: " + clonedNum);
System.out.println("Cloned Person: " + clonedPerson);
}
}
7. Create interfaces "List" and "Set" with methods "add()", "remove()", and "contains()" Implement
them in classes representing an array list and a hash set.
interface List {
void add(Object obj);
void remove(Object obj);
boolean contains(Object obj);
}
interface Set {
void add(Object obj);
void remove(Object obj);
boolean contains(Object obj);
}
@Override
public void add(Object obj) {
list.add(obj);
}
@Override
public void remove(Object obj) {
list.remove(obj);
}
@Override
public boolean contains(Object obj) {
return list.contains(obj);
}
}
@Override
public void add(Object obj) {
set.add(obj);
}
@Override
public void remove(Object obj) {
set.remove(obj);
}
@Override
public boolean contains(Object obj) {
return set.contains(obj);
}
}
8. Write a program to demonstrate interface implementation by creating objects of the array list
and hash set classes and invoking interface methods.
Interface
9. Create interfaces "Printable" and "Scannable" with methods "print()" and "scan()" Implement
them in classes representing a printer and a scanner.
interface Printable {
void print();
}
interface Scannable {
void scan();
}
}
}
Scanning document...
10. Write a program to demonstrate interface implementation by creating objects of the printer and
scanner classes and invoking interface methods.
public class PrinterScannerDemo {
public static void main(String[] args) {
Printer printer = new Printer();
printer.print();
Scanning document...
11. Create interfaces "Sortable" and "Searchable" with methods "sort()" and "search()" Implement
them in classes representing a list and a dictionary.
interface Sortable {
void sort();
}
interface Searchable {
boolean search(Object obj);
}
@Override
public void sort() {
java.util.Collections.sort(list, null);
System.out.println("List sorted: " + list);
}
@Override
public boolean search(Object obj) {
return list.contains(obj);
}
Interface
@Override
public boolean search(Object obj) {
return map.containsValue(obj);
}
12. Write a program to demonstrate interface implementation by creating objects of the list and
dictionary classes and invoking interface methods.
public class ListDictionaryDemo {
public static void main(String[] args) {
List list = new List();
list.add("Item1");
list.add("Item2");
list.sort();
System.out.println("Item 'Item1' found in list: " + list.search("Item1"));
13. Create interfaces "Serializable" and "Deserializable" with methods "serialize()" and
"deserialize()". Implement them in classes representing a file and a database.
Interface
interface Serializable {
void serialize();
}
interface Deserializable {
void deserialize();
}
file.serialize();
database.deserialize();
}
}
Database deserialized.
14. Write a program to demonstrate interface implementation by creating objects of the file and
database classes and invoking interface methods.
public class FileDatabaseDemo {
public static void main(String[] args) {
File file = new File();
file.serialize();
file.deserialize();
database.deserialize();
}
}
File deserialized.
Database serialized.
Database deserialized.
15. Create interfaces "Encryptable" and "Decryptable" with methods "encrypt()" and "decrypt()".
Implement them in classes representing an encoder and a decoder.
interface Encryptable {
void encrypt();
}
interface Decryptable {
void decrypt();
}
Decrypting data...
16. Write a program to demonstrate interface implementation by creating objects of the encoder
and decoder classes and invoking interface methods.
public class EncoderDecoderDemo {
public static void main(String[] args) {
Encoder encoder = new Encoder();
encoder.encrypt();
decoder.decrypt();
}
}
Decrypting data...
17. Create interfaces "Runnable" and "Walkable" with methods "run()" and "walk()" Implement
them in classes representing a cheetah and a tortoise.
interface Runnable {
void run();
}
interface Walkable {
void walk();
}
cheetah.run();
tortoise.walk();
}
}
Tortoise is walking...
Interface
18. Write a program to demonstrate interface implementation by creating objects of the cheetah
and tortoise classes and invoking interface methods.
public class CheetahTortoiseDemo {
public static void main(String[] args) {
Cheetah cheetah = new Cheetah();
cheetah.run();
Tortoise is walking...
19. Create interfaces "Playable" and "Recordable" with methods "play()" and "record()" Implement
them in classes representing a music player and a recorder.
interface Playable {
void play();
}
interface Recordable {
void record();
}
musicPlayer.play();
Interface
recorder.record();
}
}
Recording audio...
20. Write a program to demonstrate interface implementation by creating objects of the music
player and recorder classes and invoking interface methods.
public class MusicPlayerRecorderDemo {
public static void main(String[] args) {
MusicPlayer player = new MusicPlayer();
player.play();
Recording audio...
21. Create interfaces "Drawable" and "Erasable" with methods "draw()" and "erase()" Implement
them in classes representing a whiteboard and a chalkboard.
interface Drawable {
void draw();
}
interface Erasable {
void erase();
}
@Override
public void erase() {
System.out.println("Erasing the whiteboard...");
}
}
@Override
public void draw() {
System.out.println("Drawing on the chalkboard...");
}
@Override
public void erase() {
System.out.println("Erasing the chalkboard...");
}
}
22. Write a program to demonstrate interface implementation by creating objects of the whiteboard
and chalkboard classes and invoking interface methods.
public class WhiteboardChalkboardDemo {
public static void main(String[] args) {
Whiteboard whiteboard = new Whiteboard();
whiteboard.draw();
whiteboard.erase();
23. Create interfaces "Sendable" and "Receivable" with methods "send()" and "receive()" Implement
them in classes representing a transmitter and a receiver.
interface Sendable {
void send();
}
interface Receivable {
void receive();
}
@Override
public void send() {
System.out.println("Transmitter sending data...");
}
}
24. Write a program to demonstrate interface implementation by creating objects of the transmitter
and receiver classes and invoking interface methods.
public class TransmitterReceiverDemo {
public static void main(String[] args) {
Transmitter transmitter = new Transmitter();
transmitter.send();
25. Create interfaces "Encryptable" and "Decryptable" with methods "encrypt()" and "decrypt()".
Implement them in classes representing an encryption algorithm and a
interface Encryptable {
void encrypt();
}
interface Decryptable {
void decrypt();
}
}
}
1. Create a base class "Vehicle" with properties (make, model, year) and a subclass "Car" with
additional properties (color, mileage).
// Base class Vehicle
class Vehicle {
String make;
String model;
int year;
// Subclass Car
class Car extends Vehicle {
String color;
int mileage;
Output: Car Details: Make - Toyota, Model - Camry, Year - 2022, Color - Blue, Mileage – 15000
2. Write a program to demonstrate inheritance by creating objects of both classes and accessing
properties.
// Reusing the previous Vehicle and Car classes
Output: Car Details: Make - Toyota, Model - Corolla, Year - 2021, Color - Red, Mileage – 12000
3. Create a base class "Shape" with methods to calculate area and perimeter. Derive classes "Circle"
and "Rectangle" from it and override the methods.
// Base class Shape
abstract class Shape {
String color;
// Subclass Circle
class Circle extends Shape {
double radius;
// Subclass Rectangle
class Rectangle extends Shape {
double length;
double width;
4. Write a program to demonstrate inheritance by creating objects of derived classes and invoking
base class methods.
// Reusing Shape, Circle, and Rectangle classes
5. Create a base class "Animal" with properties (name, age) and subclasses "Dog" and "Cat" with
additional properties (breed, color).
// Base class Animal
class Animal {
String name;
int age;
this.name = name;
this.age = age;
}
}
// Subclass Dog
class Dog extends Animal {
String breed;
String color;
// Subclass Cat
class Cat extends Animal {
String breed;
String color;
Output: Dog Details: Name - Buddy, Age - 3, Breed - Golden Retriever, Color - Golden
6. Write a program to demonstrate inheritance by creating objects of derived classes and accessing
properties.
// Base class Animal
class Animal {
String name;
int age;
// Subclass Dog
class Dog extends Animal {
String breed;
// Subclass Cat
class Cat extends Animal {
String color;
Inheritance
7. Create a base class "Employee" with properties (name, id, salary) and a subclass "Manager" with
additional properties (department, designation).
class Employee {
String name;
int id;
double salary;
this.name = name;
this.id = id;
this.salary = salary;
String department;
String designation;
public Manager(String name, int id, double salary, String department, String designation) {
this.department = department;
this.designation = designation;
System.out.println("Manager Details: Name - " + name + ", ID - " + id + ", Salary - " + salary + ",
Department - " + department + ", Designation - " + designation);
manager.displayDetails();
Output: Manager Details: Name - Alice, ID - 101, Salary - 90000.0, Department - HR, Designation - Senior
Manager
8.Write a program to demonstrate inheritance by creating objects of both classes and accessing
properties.
manager.displayDetails();
Manager Details: Name - Alice, ID - 101, Salary - 90000.0, Department - HR, Designation - Senior
Manager
9. Create a base class "Person" with properties (name, age) and subclasses "Student" and "Teacher" with
additional properties (roll number, subject).
class Person {
String name;
int age;
this.name = name;
this.age = age;
int rollNumber;
super(name, age);
this.rollNumber = rollNumber;
System.out.println("Student Details: Name - " + name + ", Age - " + age + ", Roll Number - " +
rollNumber);
String subject;
super(name, age);
this.subject = subject;
System.out.println("Teacher Details: Name - " + name + ", Age - " + age + ", Subject - " + subject);
student.displayDetails();
teacher.displayDetails();
Output: Student Details: Name - Tom, Age - 20, Roll Number - 101
10. Write a program to demonstrate inheritance by creating objects of derived classes and accessing
properties.
student.displayDetails();
teacher.displayDetails();
Output: Student Details: Name - Alice, Age - 18, Roll Number - 102
11. Create a base class "BankAccount" with properties (account number, balance) and subclasses
"SavingsAccount" and "CurrentAccount".
class BankAccount {
String accountNumber;
double balance;
this.accountNumber = accountNumber;
this.balance = balance;
double interestRate;
super(accountNumber, balance);
Inheritance
this.interestRate = interestRate;
double overdraftLimit;
super(accountNumber, balance);
this.overdraftLimit = overdraftLimit;
savings.displayDetails();
current.displayDetails();
Inheritance
Output: Savings Account - Account Number: SA123, Balance: 10000.0, Interest Rate: 0.04
Current Account - Account Number: CA456, Balance: 5000.0, Overdraft Limit: 2000.0
12. Write a program to demonstrate inheritance by creating objects of derived classes and accessing
properties.
savings.displayDetails();
current.displayDetails();
Output: Savings Account - Account Number: SA789, Balance: 12000.0, Interest Rate: 0.03
Current Account - Account Number: CA321, Balance: 8000.0, Overdraft Limit: 3000.0
13. Create a base class "Shape" with properties (type, color) and a subclass "Triangle" with additional
properties (base, height).
class Shape {
String type;
String color;
this.type = type;
this.color = color;
double base;
double height;
super(type, color);
this.base = base;
this.height = height;
System.out.println("Triangle Details: Type - " + type + ", Color - " + color + ", Base - " + base + ",
Height - " + height);
triangle.displayDetails();
Output: Triangle Details: Type - Equilateral, Color - Red, Base - 5.0, Height - 8.0
14. Write a program to demonstrate inheritance by creating objects of both classes and accessing
properties.
triangle.displayDetails();
Inheritance
Output: Triangle Details: Type - Isosceles, Color - Green, Base – 6.0, Height - 10.0
15. Create a base class "Vehicle" with properties (make, model, year) and a subclass "Truck" with
additional properties (capacity, mileage).
class Vehicle {
String make;
String model;
int year;
this.make = make;
this.model = model;
this.year = year;
double capacity;
double mileage;
public Truck(String make, String model, int year, double capacity, double mileage) {
this.capacity = capacity;
this.mileage = mileage;
System.out.println("Truck Details: Make - " + make + ", Model - " + model + ", Year - " + year + ",
Capacity - " + capacity + ", Mileage - " + mileage);
truck.displayDetails();
Output: Truck Details: Make - Ford, Model - F150, Year - 2022, Capacity - 1.5, Mileage - 12.0
16. Write a program to demonstrate inheritance by creating objects of both classes and accessing
properties.
truck.displayDetails();
Output: Truck Details: Make - Chevrolet, Model - Silverado, Year - 2023, Capacity - 2.0, Mileage - 10.0
17. Create a base class "Fruit" with properties (name, color) and subclasses "Apple" and "Banana" with
additional properties (taste, size)..
class Fruit {
String name;
String color;
this.name = name;
this.color = color;
Inheritance
String taste;
double size;
super(name, color);
this.taste = taste;
this.size = size;
System.out.println("Apple Details: Name - " + name + ", Color - " + color + ", Taste - " + taste + ", Size
- " + size);
String taste;
double size;
super(name, color);
this.taste = taste;
this.size = size;
}
Inheritance
System.out.println("Banana Details: Name - " + name + ", Color - " + color + ", Taste - " + taste + ",
Size - " + size);
apple.displayDetails();
banana.displayDetails();
Output: Apple Details: Name - Apple, Color - Red, Taste - Sweet, Size - 4.5
Banana Details: Name - Banana, Color - Yellow, Taste - Sweet, Size - 6.0
18. Write a program to demonstrate inheritance by creating objects of derived classes and accessing
properties.
apple.displayDetails();
banana.displayDetails();
Output: Apple Details: Name - Apple, Color - Green, Taste - Sour, Size - 5.0
Inheritance
Banana Details: Name - Banana, Color - Yellow, Taste - Sweet, Size - 7.0
19. Create a base class "Animal" with properties (name, type) and subclasses "Dog" and "Cat" with
additional properties (breed, color).
class Animal {
String name;
String type;
this.name = name;
this.type = type;
String breed;
String color;
super(name, type);
this.breed = breed;
this.color = color;
System.out.println("Dog Details: Name - " + name + ", Type - " + type + ", Breed - " + breed + ", Color
- " + color);
}
Inheritance
String breed;
String color;
super(name, type);
this.breed = breed;
this.color = color;
System.out.println("Cat Details: Name - " + name + ", Type - " + type + ", Breed - " + breed + ", Color
- " + color);
dog.displayDetails();
cat.displayDetails();
Output: Dog Details: Name - Buddy, Type - Mammal, Breed - Golden Retriever, Color - Golden
Cat Details: Name - Whiskers, Type - Mammal, Breed - Persian, Color – White
20. Write a program to demonstrate inheritance by creating objects of both classes and accessing
properties.
Inheritance
dog.displayDetails();
cat.displayDetails();
Output: Dog Details: Name - Rex, Type - Mammal, Breed - Bulldog, Color - Brown
Cat Details: Name - Luna, Type - Mammal, Breed - Siamese, Color – Grey
21. Create a base class "Person" with properties (name, age) and a subclass "Employee" with additional
properties (id, salary).
class Person {
String name;
int age;
this.name = name;
this.age = age;
int id;
double salary;
super(name, age);
Inheritance
this.id = id;
this.salary = salary;
System.out.println("Employee Details: Name - " + name + ", Age - " + age + ", ID - " + id + ", Salary - "
+ salary);
employee.displayDetails();
Output: Employee Details: Name - Alice, Age - 30, ID - 101, Salary - 50000.0
22. Write a program to demonstrate inheritance by creating objects of both classes and accessing
properties.
employee.displayDetails();
23. Create a base class "Shape" with properties (type, color) and a subclass "Rectangle" with additional
properties (length, width).
class Shape {
String type;
String color;
this.type = type;
this.color = color;
double length;
double width;
super(type, color);
this.length = length;
this.width = width;
System.out.println("Rectangle Details: Type - " + type + ", Color - " + color + ", Length - " + length + ",
Width - " + width);
}
Inheritance
rectangle.displayDetails();
Output: Rectangle Details: Type - Quadrilateral, Color - Blue, Length - 4.0, Width - 6.0
24. Write a program to demonstrate inheritance by creating objects of both classes and accessing
properties.
rectangle.displayDetails();
Output: Rectangle Details: Type - Rectangle, Color - Red, Length - 5.0, Width - 8.0
25. Create a base class "Vehicle" with properties (make, model, year) and a subclass "Car" with
additional properties (color, mileage).
class Vehicle {
String make;
String model;
int year;
this.make = make;
this.model = model;
this.year = year;
}
Inheritance
String color;
double mileage;
public Car(String make, String model, int year, String color, double mileage) {
this.color = color;
this.mileage = mileage;
System.out.println("Car Details: Make - " + make + ", Model - " + model + ", Year - " + year + ", Color -
" + color + ", Mileage - " + mileage);
car.displayDetails();
Output: Car Details: Make - Toyota, Model - Camry, Year - 2021, Color - Black, Mileage - 30.5
Exception Handling
try {
} catch (InterruptedException e) {
});
thread.start();
try {
} catch (ArrayStoreException e) {
try {
} catch (IllegalStateException e) {
}
Exception Handling
import java.util.*;
try {
scanner.close();
} catch (NoSuchElementException e) {
import java.util.*;
try {
} catch (UnsupportedOperationException e) {
}
Exception Handling
(same as above)
import java.util.*;
try {
list.add("A");
list.add("B");
iterator.next();
} catch (ConcurrentModificationException e) {
try {
} catch (IllegalArgumentException e) {
}
Exception Handling
try {
System.setSecurityManager(new SecurityManager());
} catch (SecurityException e) {
Output: Exception caught: java.security.SecurityException: exit called from the security manager
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
try {
} catch (DateTimeParseException e) {
}
Exception Handling
import java.util.regex.*;
try {
} catch (PatternSyntaxException e) {
import java.util.*;
try {
ResourceBundle rb = ResourceBundle.getBundle("nonexistent");
} catch (MissingResourceException e) {
}
Exception Handling
Output: Exception caught: java.util.MissingResourceException: Can't find bundle for base name
nonexistent, locale en_US
import java.util.*;
try {
formatter.close();
} catch (FormatterClosedException e) {
import java.nio.*;
try {
} catch (BufferOverflowException e) {
}
Exception Handling
import java.nio.*;
try {
} catch (BufferUnderflowException e) {
import java.time.*;
try {
} catch (DateTimeException e) {
}
Exception Handling
Output: Exception caught: java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 -
23): 25
Collection:
// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Removing elements
list.remove("Banana");
After removal:
Apple
Cherry
//2. Demonstrate LinkedList by adding, removing, and iterating over elements:
import java.util.LinkedList;
// Adding elements
Collection:
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Removing elements
list.remove("Banana");
After removal:
Apple
Cherry
//3. Demonstrate HashSet by adding, removing, and iterating over elements:
import java.util.HashSet;
// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");
// Removing elements
set.remove("Banana");
After removal:
Apple
Cherry
//4. Demonstrate TreeSet by adding, removing, and iterating over elements:
import java.util.TreeSet;
// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");
// Removing elements
set.remove("Banana");
System.out.println(fruit);
}
}
}
Output: TreeSet:
Apple
Banana
Cherry
After removal:
Apple
Cherry
//5. Demonstrate HashMap by adding and retrieving key-value pairs:
import java.util.HashMap;
// Retrieving values
System.out.println("HashMap:");
System.out.println("Key 1: " + map.get(1));
System.out.println("Key 2: " + map.get(2));
System.out.println("Key 3: " + map.get(3));
}
}
Output: HashMap:
Key 1: Apple
Key 2: Banana
Key 3: Cherry
//6. Demonstrate TreeMap by adding and retrieving key-value pairs:
import java.util.TreeMap;
map.put(3, "Cherry");
// Retrieving values
System.out.println("TreeMap:");
System.out.println("Key 1: " + map.get(1));
System.out.println("Key 2: " + map.get(2));
System.out.println("Key 3: " + map.get(3));
}
}
Output: TreeMap:
Key 1: Apple
Key 2: Banana
Key 3: Cherry
//7. Demonstrate LinkedHashMap by adding and retrieving key-value pairs:
import java.util.LinkedHashMap;
// Retrieving values
System.out.println("LinkedHashMap:");
System.out.println("Key 1: " + map.get(1));
System.out.println("Key 2: " + map.get(2));
System.out.println("Key 3: " + map.get(3));
}
}
Output: LinkedHashMap:
Key 1: Apple
Key 2: Banana
Key 3: Cherry
//8. Demonstrate Queue by adding, removing, and iterating over elements:
import java.util.LinkedList;
import java.util.Queue;
// Adding elements
queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");
// Removing elements
queue.poll();
After removal:
Banana
Cherry
//9. Demonstrate PriorityQueue by adding, removing, and iterating over elements:
import java.util.PriorityQueue;
// Adding elements
queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");
// Adding elements
stack.push("Apple");
stack.push("Banana");
stack.push("Cherry");
// Adding elements
deque.add("Apple");
deque.add("Banana");
deque.add("Cherry");
System.out.println("ArrayDeque:");
for (String fruit : deque) {
System.out.println(fruit);
}
// Removing elements
deque.removeFirst();
// Adding an element
set.add(Fruit.CHERRY);
// Removing an element
set.remove(Fruit.BANANA);
// Adding elements
bitSet.set(0);
bitSet.set(2);
bitSet.set(4);
// Removing an element
bitSet.clear(2);
Collection:
output: Hashtable:
Key 1: Apple
Key 2: Banana
Key 3: Cherry
//15. Multiple thread and use Executors framework
import java.util.Properties;
properties.setProperty("password", "12345");
properties.setProperty("email", "[email protected]");
// Displaying elements
System.out.println("Original Vector: " + vector);
}
}
}
Output: Original Vector: [Apple, Banana, Cherry]
After removing Banana: [Apple, Cherry]
Iterating over Vector:
Apple
Cherry
//17. Write a program to demonstrate Enumeration by iterating over elements of a collection.
import java.util.Vector;
import java.util.Enumeration;
list.add("Cherry");
// Creating a ListIterator
ListIterator<String> listIterator = list.listIterator();
System.out.println(iterator.next());
}
}
}
Output: Iterating over ArrayList using Iterator:
Apple
Banana
Cherry
//20. Implement a program to demonstrate ArrayBlockingQueue by adding, removing, and Q
iterating over elements.
import java.util.concurrent.ArrayBlockingQueue;
try {
// Adding elements to the queue
queue.put("Apple");
queue.put("Banana");
queue.put("Cherry");
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e.getMessage());
}
}
}
Output: Queue after adding elements: [Apple, Banana, Cherry]
Removed Element: Apple
Queue after removal: [Banana, Cherry]
Iterating over Queue:
Banana
Collection:
Cherry
//22. Implement a program to demonstrate PriorityBlockingQueue by adding, removing,
anditerating over elements
import java.util.concurrent.PriorityBlockingQueue;
// Removing elements from the queue (elements will be removed in priority order)
try {
String removedElement = queue.take();
System.out.println("Removed Element: " + removedElement);
@Override
public long getDelay(TimeUnit unit) {
long diff = expiryTime - System.currentTimeMillis();
return unit.convert(diff, TimeUnit.MILLISECONDS);
}
@Override
public int compareTo(Delayed o) {
if (this.expiryTime < ((DelayedElement) o).expiryTime) {
return -1;
}
if (this.expiryTime > ((DelayedElement) o).expiryTime) {
return 1;
}
return 0;
}
}
}
Output: Queue after adding elements: [Apple, Banana, Cherry]
Removed Element: Apple
Queue after removal: [Banana, Cherry]
Iterating over Queue:
Banana
Cherry