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

javacode-GQT_merged

The document contains a series of Java programming exercises, each with a code snippet and its corresponding output. Topics include printing names, calculating sums, swapping numbers, checking for prime numbers, and more. It serves as a comprehensive guide for beginners to practice and understand basic programming concepts in Java.

Uploaded by

Ningamma Biradar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

javacode-GQT_merged

The document contains a series of Java programming exercises, each with a code snippet and its corresponding output. Topics include printing names, calculating sums, swapping numbers, checking for prime numbers, and more. It serves as a comprehensive guide for beginners to practice and understand basic programming concepts in Java.

Uploaded by

Ningamma Biradar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 218

1. Write a Java program to print your name?

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

4. Write a program to check whether a given number is prime or not.?


Code:
public class PrimeCheck {
public static void main(String[] args) {
int num = 29;
boolean isPrime = true;

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.

5. Write a program to calculate the factorial of a given number using recursion?


Code:
public class FactorialRecursion {
public static long factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
int num = 5;
long result = factorial(num);
System.out.println("The factorial of " + num + " is: " + result);
}
}
Output:
The factorial of 5 is: 120
6. Write a program to find the roots of a quadratic equation.?
Code:
import java.util.Scanner;

public class QuadraticEquation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter coefficient a: ");
double a = scanner.nextDouble();
System.out.print("Enter coefficient b: ");
double b = scanner.nextDouble();
System.out.print("Enter coefficient c: ");
double c = scanner.nextDouble();
double discriminant = b * b - 4 * a * c;

System.out.println("\nThe quadratic equation is: " + a + "x^2 + " + b + "x + " + c + " = 0");

if (discriminant > 0) {

double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);


double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are real and distinct:");
System.out.println("Root 1: " + root1);
System.out.println("Root 2: " + root2);
}
else if (discriminant == 0) {
double root = -b / (2 * a);
System.out.println("The roots are real and repeated:");
System.out.println("Root: " + root);
}
else {

double realPart = -b / (2 * a);


double imaginaryPart = Math.sqrt(-discriminant) / (2 * a);
System.out.println("The roots are complex and imaginary:");
System.out.println("Root 1: " + realPart + " + " + imaginaryPart + "i");
System.out.println("Root 2: " + realPart + " - " + imaginaryPart + "i");
}
scanner.close();
}
}
Output:
Enter coefficient a:
1
Enter coefficient b:
-3
Enter coefficient c:
2
The quadratic equation is: 1.0x^2 + -3.0x + 2.0 = 0
The roots are real and distinct:
Root 1: 2.0
Root 2: 1.0

7. Write a program to calculate the area of a triangle.?


Code:
import java.util.Scanner;
public class TriangleArea {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of side a: ");
double a = scanner.nextDouble();
System.out.print("Enter the length of side b: ");
double b = scanner.nextDouble();
System.out.print("Enter the length of side c: ");
double c = scanner.nextDouble();
if (a + b > c && a + c > b && b + c > a) {
double s = (a + b + c) / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
System.out.println("\nThe area of the triangle is: " + area);
}
else {
System.out.println("\nThe given sides do not form a valid triangle.");
}
scanner.close();
}
}
Output:
Enter the length of side a:
3
Enter the length of side b:
4
Enter the length of side c:
5
The area of the triangle is: 6.0
8. Write a program to print the Fibonacci series up to a given number of terms?
Code:
import java.util.Scanner;
public class FibonacciSeries {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int terms = scanner.nextInt();

if (terms <= 0) {
System.out.println("Please enter a positive integer.");
} else {
System.out.println("The Fibonacci series up to " + terms + " terms is:");

int first = 0, second = 1;


System.out.print(first);
for (int i = 1; i < terms; i++) {
System.out.print(", " + second);
int next = first + second;
first = second;
second = next;
}
System.out.println();
}
scanner.close();
}
}
Output:
Enter the number of terms:
10
The Fibonacci series up to 10 terms is:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

9. Write a program to find the second largest number in an array?


Code:
import java.util.Scanner;

public class SecondLargestNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
if (n < 2) {
System.out.println("Array should have at least two elements.");
}
else {
int largest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}

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

10. Write a program to reverse a string?


Code:
import java.util.Scanner;

public class ReverseString {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Reversed string: " + reversed);
scanner.close();
}
}
Output:
Enter a string:
Hello
Reversed string: olleH

11. Write a program to check if a given string is a palindrome.?


Code:
import java.util.Scanner;
public class Palindrome {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
if (str.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
scanner.close();
}
}
Output:
Enter a string:
Madam
The string is a palindrome.

12. Write a program to count the occurrences of a character in a string?


Code:
import java.util.Scanner;

public class CharacterCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
System.out.print("Enter a character to count: ");
char ch = scanner.next().charAt(0);
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
System.out.println("The character '" + ch + "' appears " + count + " times.");
scanner.close();
}
}
Output:
Enter a string:
hello world
Enter a character to count:
o
The character 'o' appears 2 times.

13. Find GCD of Two Numbers?


CODE:
import java.util.Scanner;
public class GCD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
System.out.println(a);
}
}
OUTPUT:
54
24
6
14. Convert Decimal to Binary?
CODE:
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int decimal = sc.nextInt();
System.out.println(Integer.toBinaryString(decimal));}
}
OUTPUT: 10
1010
15. Calculate Sum of Digits?
CODE:
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
System.out.println(sum);
}
}
OUTPUT:
123
6
16. Write a program to check whether a given year is a leap year or not.?
CODE:
import java.util.Scanner;

public class LeapYear {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
System.out.println("Leap Year");
} else {
System.out.println("Not a Leap Year");
}
}
}
OUTPUT:
2024
Leap Year
17. Find Factorial Using Iteration?
Code:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println(factorial);
}
}
Output:
5
120
`18. Print Pascal's Triangle?
Code:
import java.util.Scanner;

public class PascalsTriangle {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int rows = sc.nextInt();
for (int i = 0; i < rows; i++) {
int number = 1;
for (int j = 0; j <= i; j++) {
System.out.print(number + " ");
number = number * (i - j) / (j + 1);
}
System.out.println();
}
}
}
Output:
5
1
11
121
1331
1 4641

19. Check Armstrong Number?


Code:
import java.util.Scanner;

public class Armstrong {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0, temp = num, n = String.valueOf(num).length();
while (temp > 0) {
sum += Math.pow(temp % 10, n);
temp /= 10;
}
System.out.println(sum == num ? "Armstrong" : "Not Armstrong");
}
}
Output:
153
Armstrong

20. Area and Perimeter of a Circle?


Code:
import java.util.Scanner;

public class Circle {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double radius = sc.nextDouble();
System.out.printf("%.2f %.2f", Math.PI * radius * radius, 2 * Math.PI * radius);
}
}
Output:
5
78.54 31.42

21. Write a program to print the multiplication table of a given number?


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 <= 3; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
}
}
Output:
5
5x1=5
5 x 2 = 10
5 x 3 = 15

22. Sum of Elements in Array?


Code:
import java.util.Scanner;

public class ArraySum {


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:
3
123
6
23. Check Perfect Number?
Code:
import java.util.Scanner;

public class PerfectNumber {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0;
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) sum += i;
}
System.out.println(sum == num ? "Perfect Number" : "Not Perfect Number");
}
}
Ouput:
28
Perfect Number

24. Find ASCII Value?


Code:
import java.util.Scanner;

public class AsciiValue {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0);
System.out.println((int) ch);
}
}
Output:
A
65

25. Calculate Power of a Number?


Code:
import java.util.Scanner;

public class Power {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double base = sc.nextDouble();
int exponent = sc.nextInt();
System.out.println(Math.pow(base, exponent));
}
}
Output:
23
8.0

Operators:
26. Write a program to perform arithmetic operations (+, -, *, /) on two numbers.?
Code:
import java.util.Scanner;

public class ArithmeticOperations {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("Addition: " + (a + b));
System.out.println("Subtraction: " + (a - b));
System.out.println("Multiplication: " + (a * b));
System.out.println("Division: " + (a / b));
}
}
Output:
10
5
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2

27. Write a program to perform bitwise AND, OR, and XOR operations on two integers.?
Code:
import java.util.Scanner;

public class BitwiseOperations {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println("AND: " + (a & b));
System.out.println("OR: " + (a | b));
System.out.println("XOR: " + (a ^ b));
}
}
Output:
5
3
AND: 1
OR: 7
XOR: 6
28.Write a program to check whether a given number is positive, negative, or zero.?
Code:
import java.util.Scanner;
public class CheckNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (num > 0) System.out.println("Positive");
else if (num < 0) System.out.println("Negative");
else System.out.println("Zero");
}
}
Output:
0
Zero
29. Write a program to swap two numbers using bitwise XOR operator.?
Code:
import java.util.Scanner;
public class SwapUsingXOR {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
a = a ^ b;
b = a ^ b;
a = a ^ b;
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}
Output:4
7
After Swap: a = 4, b = 7
30. Write a program to calculate the area of a circle using the radius entered by the user.?
Code:
import java.util.Scanner;
public class CircleArea {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double radius = sc.nextDouble();
System.out.println("Area: " + (Math.PI * radius * radius));
}
}
Output:
5
Area: 78.53981633974483
31. Write a program to convert temperature from Fahrenheit to Celsius.?
Code:
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double fahrenheit = sc.nextDouble();
System.out.println("Celsius: " + ((fahrenheit - 32) * 5 / 9));
}
}
Output:
9.86
Celsius: 37.0
32. Write a program to check if a given number is divisible by both 5 and 7.?
Code:
import java.util.Scanner;
public class DivisibleBy5And7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
if (num % 5 == 0 && num % 7 == 0) System.out.println("Divisible by both");
else System.out.println("Not divisible by both");
}
}
Output:
35
Divisible by both
33. Write a program to calculate the compound interest.?
Code:
import java.util.Scanner;
public class CompoundInterest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double principal = sc.nextDouble();
double rate = sc.nextDouble();
int time = sc.nextInt();
System.out.println("Compound Interest: " + (principal * Math.pow(1 + rate / 100, time) - principal));
}
}
Output:
1000 5 2
Compound Interest: 102.5
34. Write a program to check whether a given character is a vowel or consonant?
Code:
import java.util.Scanner;
public class VowelOrConsonant {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0);
if ("AEIOUaeiou".indexOf(ch) != -1) System.out.println("Vowel");
else System.out.println("Consonant");
}
}
Output: A
Vowel
35. Write a program to find the maximum of three numbers using conditional operator?
Code:
import java.util.Scanner;
public class MaxOfThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
System.out.println("Maximum: " + max);
}
}
Output
2 5 2
Maximum: 5
36. Write a program to find the sum of digits of a number using while loop.?
Code:
import java.util.Scanner;
public class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
System.out.println("Sum of Digits: " + sum);
}
}
Output:
123
Sum of Digits: 6
37. Check Palindrome Using Recursion?
Code:
import java.util.Scanner;
public class Palindrome {
public static boolean isPalindrome(String str, int start, int end) {
if (start >= end) return true;
return str.charAt(start) == str.charAt(end) && isPalindrome(str, start + 1, end - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String num = sc.next();
System.out.println(isPalindrome(num, 0, num.length() - 1) ? "Palindrome" : "Not Palindrome");
}
}
Output:
121
Palindrome
38. Write a program to check whether a given number is prime or not using for loop.?
Code:
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
boolean isPrime = true;
if (num <= 1) isPrime = false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime ? "Prime" : "Not Prime");
}
}
Output:
7
Prime
39. Write a program to find the factorial of a number using recursion.?
Code:
import java.util.Scanner;
public class Factorial {
public static long factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println("Factorial: " + factorial(num));
}
}
Output:
5
Factorial: 120
40. Write a program to calculate the power of a number using recursion.?
Code:
import java.util.Scanner;
public class Power {
public static int power(int base, int exp) {
if (exp == 0) return 1;
return base * power(base, exp - 1);
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
int base = sc.nextInt();
int exp = sc.nextInt();
System.out.println("Result: " + power(base, exp));
}
}
Output:
2 3
Result: 8
41. Write a program to print the Fibonacci series using recursion.?
Code:
import java.util.Scanner;
public class Fibonacci {
public static int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
Output:
5
01123
42. Write a program to reverse a string using recursion.?
Code:
import java.util.Scanner;
public class ReverseString {
public static String reverse(String str) {
if (str.isEmpty()) return str;
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
System.out.println("Reversed: " + reverse(str));
}
}
Output: hello
olleh
43. Write a program to calculate the sum of natural numbers up to a given term.?
Code:
import java.util.Scanner;
public class SumNaturalNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = n * (n + 1) / 2;
System.out.println("Sum: " + sum);
}
}
Output:
10
Sum: 55
44. Write a program to check whether a given year is leap year or not using conditional operator.?
Code:
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int year = sc.nextInt();
System.out.println((year % 4 == 0 && year % 100 != 0 || year % 400 == 0) ? "Leap Year" : "Not
Leap Year");
}
}
Output: 2024
Leap Year
45. Write a program to find the LCM (Least Common Multiple) of two numbers.?
Code:
import java.util.Scanner;
public class LCM {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int max = Math.max(a, b);
while (true) {
if (max % a == 0 && max % b == 0) {
System.out.println("LCM: " + max);
break;
}
max++;
}
}
}
Output:
4 6
LCM: 12
46. Write a program to calculate the area of a triangle using Heron's formula.?
Code:
import java.util.Scanner;
public class HeronsFormula {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
double s = (a + b + c) / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
System.out.println("Area: " + area);
}
}
Output:
3 4 5
Area: 6.0
47. Write a program to find the sum of all even numbers between 1 to 100 using for loop.?
Code:
public class SumEvenNumbers {
public static void main(String[] args) {
int sum = 0;
for (int i = 2; i <= 100; i += 2) {
sum += i;
}
System.out.println("Sum: " + sum);
}
}
Output:
Sum: 2550
48. Write a program to calculate the simple interest?
Code:
import java.util.Scanner;
public class SimpleInterest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double principal = sc.nextDouble();
double rate = sc.nextDouble();
double time = sc.nextDouble();
System.out.println("Simple Interest: " + (principal * rate * time / 100));
}
}
Output:
1000 5 2
Simple Interest: 100.0

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};

ArrayList<Integer> intersection = new ArrayList<>();


for (int num1 : arr1) {
for (int num2 : arr2) {
if (num1 == num2 && !intersection.contains(num1)) {
intersection.add(num1);
}
}
}
System.out.println("Intersection: " + intersection);
}
}

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;

for (int num : arr) {


if (num < 0) {
sum += num;
}
}
System.out.println("Sum of Negative Numbers: " + sum);
}
}
Output:
Sum of Negative Numbers: -9

63. Find the Product of All Elements in an Array?


Code:
public class ProductOfArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int product = 1;
for (int num : arr) {
product *= num;
}
System.out.println("Product of Elements: " + product);
}
}
Output:
Product of Elements: 24
64. 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 = {3, 1, 4, 2, 5};
Arrays.sort(arr);
System.out.println("Second Smallest: " + arr[1]);
System.out.println("Second Largest: " + arr[arr.length - 2]);
}
}
Output:
Second Smallest: 2
Second Largest: 4
65. Find the Index of a Given Element in an Array?
Code:
public class FindIndex {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int element = 3;
int index = -1;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == element) {
index = i;
break;
}
}
System.out.println("Index of " + element + ": " + index);
}
}
Output:
Index of 3: 2
66. Rotate an Array to the Left or Right?
Code:
import java.util.Arrays;
public class RotateArray {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int k = 2; // Number of rotations
boolean rotateRight = true;
int n = arr.length;
k %= n;
if (!rotateRight) {
k = n - k;
}
int[] rotated = new int[n];
for (int i = 0; i < n; i++) {
rotated[(i + k) % n] = arr[i];
}
System.out.println("Rotated Array: " + Arrays.toString(rotated));
}
}
Output:
Rotated Array: [4, 5, 1, 2, 3]
67. Print the Elements of a 2D Array in Spiral Order?
Code:
public class SpiralOrder {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;


while (top <= bottom && left <= right) {
for (int i = left; i <= right; i++) System.out.print(matrix[top][i] + " ");
top++;
for (int i = top; i <= bottom; i++) System.out.print(matrix[i][right] + " ");
right--;
if (top <= bottom) {
for (int i = right; i >= left; i--) System.out.print(matrix[bottom][i] + " ");
bottom--;
}
if (left <= right) {
for (int i = bottom; i >= top; i--) System.out.print(matrix[i][left] + " ");
left++;
}
}
}
}
Output:
123698745
68. Check Whether Two Arrays Are Equal or No?
Code:
import java.util.Arrays;
public class ArrayEquality {
public static void main(String[] args) {
int[] arr1 = {1, 2, 3, 4, 5};
int[] arr2 = {1, 2, 3, 4, 5};

boolean isEqual = Arrays.equals(arr1, arr2);


System.out.println("Arrays are equal: " + isEqual);
}
}
Output:
Arrays are equal: true
69. Find the Sum of Elements in the Upper Triangle of a Matrix?
Code:
public class UpperTriangleSum {
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++) {
for (int j = i; j < matrix[i].length; j++) {
sum += matrix[i][j];
}
}

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


}
}
Output:
Sum of Upper Triangle: 23
70. Find the Sum of Elements in the Lower Triangle of a Matrix?
Code:
public class LowerTriangleSum {
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++) {
for (int j = 0; j <= i; j++) {
sum += matrix[i][j];
}
}

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


}
}
Output:
Sum of Lower Triangle: 15
71. Find the Sum of Elements in Each Row and Column of a Matrix?
Code:
public class RowColumnSum {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
int rowSum = 0;
for (int j = 0; j < matrix[i].length; j++) {
rowSum += matrix[i][j];
}
System.out.println("Sum of Row " + (i + 1) + ": " + rowSum);
}
for (int j = 0; j < matrix[0].length; j++) {
int colSum = 0;
for (int i = 0; i < matrix.length; i++) {
colSum += matrix[i][j];
}
System.out.println("Sum of Column " + (j + 1) + ": " + colSum);
}
}
}
Output:
Sum of Row 1: 6
Sum of Row 2: 15
Sum of Row 3: 24
Sum of Column 1: 12
Sum of Column 2: 15
Sum of Column 3: 18
72. Check Whether a Given Matrix Is Symmetric or Not?
Code:
public class SymmetricMatrix {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{2, 4, 5},
{3, 5, 6}
};

boolean isSymmetric = true;


for (int i = 0; i < matrix.length; i++) {
for (int j = i + 1; j < matrix[i].length; j++) {
if (matrix[i][j] != matrix[j][i]) {
isSymmetric = false;
break;
}
}
}

System.out.println("Matrix is Symmetric: " + isSymmetric);


}
}
Output:
Matrix is Symmetric: true
73. Find the Saddle Point of a Matrix?
Code:
public class SaddlePoint {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
for (int i = 0; i < matrix.length; i++) {
int min = matrix[i][0];
int minIndex = 0;
for (int j = 1; j < matrix[i].length; j++) {
if (matrix[i][j] < min) {
min = matrix[i][j];
minIndex = j;
}
}
boolean isSaddle = true;
for (int k = 0; k < matrix.length; k++) {
if (matrix[k][minIndex] > min) {
isSaddle = false;
break;
}
}
if (isSaddle) {
System.out.println("Saddle Point: " + min);
return;
}
}
System.out.println("No Saddle Point");
}
}
Output:
No Saddle Point
74. Find the k-th Smallest and k-th Largest Elements in an Array?
Code:
import java.util.Arrays;
public class KthSmallestLargest {
public static void main(String[] args) {
int[] arr = {12, 3, 5, 7, 19};
int k = 2;
Arrays.sort(arr);
System.out.println(k + "th Smallest Element: " + arr[k - 1]);
System.out.println(k + "th Largest Element: " + arr[arr.length - k]);
}
}
Output:
2th Smallest Element: 5
2th Largest Element: 12
75. Count the Number of Negative, Positive, and Zero Elements in an Array?
Code:
public class CountElements {
public static void main(String[] args) {
int[] arr = {-1, 2, 0, 3, -4, 5, 0};
int positive = 0, negative = 0, zero = 0;
for (int num : arr) {
if (num > 0) positive++;
else if (num < 0) negative++;
else zero++;
}
System.out.println("Positive: " + positive);
System.out.println("Negative: " + negative);
System.out.println("Zero: " + zero);
}
}
Output:
Positive: 4
Negative: 2
Zero: 2

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

78. Convert an Integer to String and Vice Versa?


Code:
public class IntegerStringConversion {
public static void main(String[] args) {
int num = 123;
String str = String.valueOf(num);
System.out.println("Integer to String: " + str);
String str2 = "456";
int num2 = Integer.parseInt(str2)
System.out.println("String to Integer: " + num2);
}
}
Output:
Integer to String: 123
String to Integer: 456

79. Perform Operations on Characters (Uppercase and Lowercase Conversion)?


Code:
public class CharacterOperations {
public static void main(String[] args) {
char ch = 'a';
char upperCh = Character.toUpperCase(ch);
System.out.println("Lowercase to Uppercase: " + upperCh);
char lowerCh = Character.toLowerCase(upperCh);
System.out.println("Uppercase to Lowercase: " + lowerCh);
}
}
Output:
Lowercase to Uppercase: A
Uppercase to Lowercase: a

80.Demonstrate the Use of Boolean Data Type?


Code:
public class BooleanDataType {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println("Is Java fun? " + isJavaFun);
System.out.println("Is fish tasty? " + isFishTasty);
}
}
Output:
Is Java fun? true
Is fish tasty? false

81. Demonstrate the Use of Arrays in Java?


Code:
public class ArraysExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

82. Find the Maximum and Minimum Values in an Array of Integers?


Code:
public class MaxMinArray {
public static void main(String[] args) {
int[] arr = {1, 3, 7, 9, 2};
int max = arr[0];
int min = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) max = arr[i];
if (arr[i] < min) min = arr[i];
}
System.out.println("Max value: " + max);
System.out.println("Min value: " + min);
}
}
Output:
Max value: 9
Min value: 1

83. Calculate the Average of Elements in an Array?


Code:
public class AverageArray {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : arr) {
sum += num;
}
double average = sum / (double) arr.length;
System.out.println("Average: " + average);
}
}
Output:
Average: 30.0

84. Find the Length of a String?


Code:
public class StringLength {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println("Length of string: " + str.length());
}
}
Output:
Length of string: 13

85. Concatenate Two Strings?


Code:
public class ConcatenateStrings {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;

System.out.println("Concatenated String: " + result);


}
}
Output: Concatenated String: Hello World
86. Demonstrate the Use of Wrapper Classes in Java?
Code:
public class WrapperClasses {
public static void main(String[] args) {
int num = 10;
Integer integerObj = num;
int unboxedNum = integerObj;
System.out.println("Integer object: " + integerObj);
System.out.println("Unboxed int: " + unboxedNum);
}
}
Output:
Integer object: 10
Unboxed int: 10
87. Convert a String to Integer and Vice Versa?
Code:
public class StringIntegerConversion {
public static void main(String[] args) {
String str = "123";
int num = Integer.parseInt(str);
System.out.println("String to Integer: " + num);
String str2 = String.valueOf(num);
System.out.println("Integer to String: " + str2);
}
}
Output:
String to Integer: 123
Integer to String: 123

88. Demonstrate the Use of String Methods (substring, indexOf, equals)?


Code:
public class StringMethods {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println("Substring: " + str.substring(7, 12));
System.out.println("Index of 'World': " + str.indexOf("World"));
System.out.println("Equals: " + str.equals("Hello, World!"));
}
}
Output:
Substring: World
Index of 'World': 7
Equals: true

89. Count the Occurrences of a Character in a String?


Code:
public class CountCharacter {
public static void main(String[] args) {
String str = "Hello, World!";
char ch = 'o';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
System.out.println("Occurrences of '" + ch + "': " + count);
}
}
Output:
Occurrences of 'o': 2

90. Check Whether a Given String Is Palindrome or Not?


Code:
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
if (str.equals(reversed)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}
}
Output:
madam is a palindrome.
91. Reverse a String Without Using Any Built-in Methods?
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

92. Convert a String to Uppercase and Vice Versa?


Code:
public class ConvertCase {
public static void main(String[] args) {
String str = "Hello World";
String upper = "";
String lower = "";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
upper += Character.toUpperCase(ch);
} else {
lower += Character.toLowerCase(ch);
}
}
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
Output:
Uppercase: HELLO WORLD
Lowercase: hello world

93. Demonstrate the Use of StringBuilder Class?


Code:
public class StringBuilderExample {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
sb.insert(5, ",");
sb.reverse();
System.out.println(sb);
}
}
Output:
dlroW ,olleH

94. Find the Factorial of a Number Using BigInteger Class?


Code:
import java.math.BigInteger;
public class FactorialBigInteger {
public static void main(String[] args) {
int num = 100;
BigInteger factorial = BigInteger.ONE;
for (int i = 1; i <= num; i++) {
factorial = factorial.multiply(BigInteger.valueOf(i));
}
System.out.println("Factorial of " + num + " is: " + factorial);
}
}
Output:
Factorial of 100 is:
933262154439441526816992388562667004907159682643816214685929638952175999932299156089414
639761565182862536979208272237582511852109168640000000000000000000000000

95. Demonstrate the Use of Arrays of Objects?


Code:
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println(name + " is " + age + " years old.");
}
}
public class ArraysOfObjects {
public static void main(String[] args) {
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
};
for (Person person : people) {
person.display();
}
}
}
Output:
Alice is 30 years old.
Bob is 25 years old.
Charlie is 35 years old.

96. Sort an Array of Integers in Ascending and Descending Order?


Code:
import java.util.Arrays;
import java.util.Collections;
public class SortArray {
public static void main(String[] args) {
Integer[] arr = {5, 2, 8, 1, 3};
Arrays.sort(arr);
System.out.println("Ascending Order: " + Arrays.toString(arr));
Arrays.sort(arr, Collections.reverseOrder());
System.out.println("Descending Order: " + Arrays.toString(arr));
}
}
Output:
Ascending Order: [1, 2, 3, 5, 8]
Descending Order: [8, 5, 3, 2, 1]

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

99. write a java code for Transpose a Matrix?


Code:
public class MatrixTranspose {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] transpose = new int[matrix[0].length][matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];
}
}
for (int[] row : transpose) {
for (int elem : row) {
System.out.print(elem + " ");
}
System.out.println();
}
}
}
Output:
147
258
369

100.write a java code for Multiply Two Matrices?


Code:
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] matrix1 = {
{1, 2},
{3, 4}
};
int[][] matrix2 = {
{5, 6},
{7, 8}
};
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = 0;
for (int k = 0; k < 2; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
for (int[] row : result) {
for (int elem : row) {
System.out.print(elem + " ");
}
System.out.println();
}
}
}
Output:
19 22
43 50

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

102. Check Whether a Given String is Palindrome or Not?


Code:
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
if (str.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
Output:
The string is a palindrome.
103. Count the Number of Vowels and Consonants in a String?
Code:
public class VowelConsonantCount {
public static void main(String[] args) {
String str = "Hello World";
int vowels = 0, consonants = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
if ("AEIOUaeiou".indexOf(ch) != -1) {
vowels++;
} else {
consonants++;
}
}
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}
Output:
Vowels: 3
Consonants: 7

104. Count the Occurrences of a Character in a String?


Code:
public class CharacterCount {
public static void main(String[] args) {
String str = "Hello World";
char ch = 'o';
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ch) {
count++;
}
}
System.out.println("Occurrences of '" + ch + "': " + count);
}
}
Output:
Occurrences of 'o': 2

105. Remove All White Spaces from a String?


Code:
public class RemoveWhitespace {
public static void main(String[] args) {
String str = "Hello World";
String result = str.replaceAll("\\s+", "");
System.out.println("String without spaces: " + result);
}
}
Output:
String without spaces: HelloWorld
106. Find the Length of a String?
Code:
public class StringLength {
public static void main(String[] args) {
String str = "Hello World";
System.out.println("Length of the string: " + str.length());
}
}
Output:
Length of the string: 11
107. Concatenate Two Strings?
Code:
public class ConcatenateStrings {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World";
String result = str1.concat(str2);
System.out.println("Concatenated String: " + result);
}
}
Output:
Concatenated String: Hello World
108. Convert Lowercase Letters to Uppercase and Vice Versa?
Code:
public class ConvertCase {
public static void main(String[] args) {
String str = "Hello World";
StringBuilder upper = new StringBuilder();
StringBuilder lower = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLowerCase(ch)) {
upper.append(Character.toUpperCase(ch));
} else {
lower.append(Character.toLowerCase(ch));
}
}
System.out.println("Uppercase: " + upper.toString());
System.out.println("Lowercase: " + lower.toString());
}
}
Output:
Uppercase: HELLOWORLD
Lowercase: helloworld
109. Find the Longest Word in a String?
Code:
public class LongestWord {
public static void main(String[] args) {
String str = "This is a simple test string";
String[] words = str.split(" ");
String longest = "";
for (String word : words) {
if (word.length() > longest.length()) {
longest = word;
}
}
System.out.println("Longest word: " + longest);
}
}
Output:
Longest word: simple

110. Check Whether Two Strings are Anagrams or Not?


Code:
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
char[] arr1 = str1.toCharArray();
char[] arr2 = str2.toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
if (Arrays.equals(arr1, arr2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
}
Output:
The strings are anagrams.

111. Find the First Non-Repeated Character in a String?


Code:
public class FirstNonRepeatedCharacter {
public static void main(String[] args) {
String str = "swiss";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (str.indexOf(ch) == str.lastIndexOf(ch)) {
System.out.println("First non-repeated character: " + ch);
break;
}
}
}
}
Output:
First non-repeated character: w

112. Check Whether a String Contains Only Digits or Not?


Code:
public class IsDigit {
public static void main(String[] args) {
String str = "12345";
if (str.matches("[0-9]+")) {
System.out.println("The string contains only digits.");
} else {
System.out.println("The string does not contain only digits.");
}
}
}
Output: The string contains only digits.
113. Find All Permutations of a String?
Code:
public class StringPermutations {
public static void main(String[] args) {
String str = "ABC";
permute(str, 0, str.length() - 1);
}
public static void permute(String str, int left, int right) {
if (left == right) {
System.out.println(str);
} else {
for (int i = left; i <= right; i++) {
str = swap(str, left, i);
permute(str, left + 1, right);
str = swap(str, left, i); // backtrack
}
}
}
public static String swap(String str, int i, int j) {
char temp;
char[] charArray = str.toCharArray();
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return String.valueOf(charArray);
}
}
Output:
ABC
ACB
BAC
BCA
CAB
CBA
114. Find the Frequency of Each Character in a String?
Code:
import java.util.HashMap;
public class CharacterFrequency {
public static void main(String[] args) {
String str = "hello";
HashMap<Character, Integer> frequency = new HashMap<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
frequency.put(ch, frequency.getOrDefault(ch, 0) + 1);
}
System.out.println(frequency);
}
}
Output:
{h=1, e=1, l=2, o=1}

115. Reverse Words in a Sentence?


Code:
public class ReverseWords {
public static void main(String[] args) {
String sentence = "Hello World from Java";
String[] words = sentence.split(" ");
String reversedSentence = "";
for (int i = words.length - 1; i >= 0; i--) {
reversedSentence += words[i] + " ";
}
System.out.println("Reversed Sentence: " + reversedSentence.trim());
}
}
Output:
Reversed Sentence: Java from World Hello
116. Find the Duplicate Characters in a String?
Code:
import java.util.HashSet;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
HashSet<Character> duplicates = new HashSet<>();
HashSet<Character> visited = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (visited.contains(ch)) {
duplicates.add(ch);
} else {
visited.add(ch);
}
}
System.out.println("Duplicate Characters: " + duplicates);
}
}
Output:
Duplicate Characters: [r, g]
117. Find the First Repeating Character in a String?
Code:
import java.util.HashSet;
public class FirstRepeatingCharacter {
public static void main(String[] args) {
String str = "swiss";
HashSet<Character> set = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (set.contains(ch)) {
System.out.println("First Repeating Character: " + ch);
break;
}
set.add(ch);
}
}
}
Output:
First Repeating Character: s

118. Capitalize the First Letter of Each Word in a Sentence?


Code:
public class CapitalizeWords {
public static void main(String[] args) {
String sentence = "hello world from java";
String[] words = sentence.split(" ");
String result = "";
for (String word : words) {
result += word.substring(0, 1).toUpperCase() + word.substring(1) + " ";
}
System.out.println("Capitalized Sentence: " + result.trim());
}
}
Output:
Capitalized Sentence: Hello World From Java

119. Check Whether a String is a Rotation of Another String?


Code:
public class StringRotation {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "lohel";
if (str1.length() == str2.length() && (str1 + str1).contains(str2)) {
System.out.println("The string is a rotation of the other.");
} else {
System.out.println("The string is not a rotation of the other.");
}
}
}
Output:
The string is a rotation of the other.
120. Check Whether a String is a Substring of Another String?
Code:
public class SubstringCheck {
public static void main(String[] args) {
String str1 = "Hello World";
String str2 = "World";
if (str1.contains(str2)) {
System.out.println(str2 + " is a substring of " + str1);
} else {
System.out.println(str2 + " is not a substring of " + str1);
}
}
}
Output:
World is a substring of Hello World

121. Remove Duplicates from a String?


Code:
public class RemoveDuplicates {
public static void main(String[] args) {
String str = "programming";
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (result.indexOf(String.valueOf(str.charAt(i))) == -1) {
result.append(str.charAt(i));
}
}
System.out.println("String after removing duplicates: " + result);
}
}
Output:
String after removing duplicates: progamin

122. Find the Common Characters in Two Given Strings?


Code:
import java.util.HashSet;
public class CommonCharacters {
public static void main(String[] args) {
String str1 = "hello";
String str2 = "world";
HashSet<Character> commonChars = new HashSet<>();
for (int i = 0; i < str1.length(); i++) {
for (int j = 0; j < str2.length(); j++) {
if (str1.charAt(i) == str2.charAt(j)) {
commonChars.add(str1.charAt(i));
}
}
}
System.out.println("Common Characters: " + commonChars);
}
}
Output:
Common Characters: [o, l]

123. Check Whether a Given String is a Pangram or Not?


Code:
public class PangramCheck {
public static void main(String[] args) {
String str = "The quick brown fox jumps over the lazy dog";
str = str.replaceAll("[^a-zA-Z]", "").toLowerCase();
boolean isPangram = str.chars().distinct().count() == 26;
if (isPangram) {
System.out.println("The string is a pangram.");
} else {
System.out.println("The string is not a pangram.");
}
}
}
Output:
The string is a pangram.
124. Find the Smallest Window in a String Containing All Characters of Another String?
Code:
public class SmallestWindow {
public static void main(String[] args) {
String str = "ADOBECODEBANC";
String pattern = "ABC";
System.out.println("Smallest window: " + smallestWindow(str, pattern));
}
public static String smallestWindow(String str, String pattern) {
int[] strFreq = new int[256];
int[] patternFreq = new int[256];
int start = 0, minLen = Integer.MAX_VALUE, startIndex = -1;
for (char ch : pattern.toCharArray()) {
patternFreq[ch]++;
}
int count = 0;
for (int end = 0; end < str.length(); end++) {
char endChar = str.charAt(end);
strFreq[endChar]++;
if (strFreq[endChar] <= patternFreq[endChar]) {
count++;
}
while (count == pattern.length()) {
if (end - start + 1 < minLen) {
minLen = end - start + 1;
startIndex = start;
}
char startChar = str.charAt(start);
strFreq[startChar]--;
if (strFreq[startChar] < patternFreq[startChar]) {
count--;
}
start++;
}
}
if (startIndex == -1) {
return "";
}
return str.substring(startIndex, startIndex + minLen);
}
}
Output:
Smallest window: BANC

125. Find the Longest Common Prefix Among an Array of Strings?


Code:
public class LongestCommonPrefix {
public static void main(String[] args) {
String[] strs = {"flower", "flow", "flight"};
System.out.println("Longest Common Prefix: " + longestCommonPrefix(strs));
}
public static String longestCommonPrefix(String[] strs) {
if (strs == null || strs.length == 0) {
return "";
}
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (strs[i].indexOf(prefix) != 0) {
prefix = prefix.substring(0, prefix.length() - 1);
}
}
return prefix;
}
}
Output:
Longest Common Prefix: fl

126. write a java program for Sum of Two Integers?


Code:
import java.util.Scanner;
public class SumOfTwoIntegers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(a + b);
}
}
Output:
5 10
15

127. Sum of Two Floats?


Code:
import java.util.Scanner;
public class SumOfTwoFloats {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float a = sc.nextFloat();
float b = sc.nextFloat();
System.out.println(a + b);
}
}
Output:
5.5 4.5
10.0

128. Area of a Rectangle?


Code:
import java.util.Scanner;
public class AreaOfRectangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float length = sc.nextFloat();
float width = sc.nextFloat();
System.out.println(length * width);
}
}
Output:
5.0 4.0
20.0

129. Volume of a Cylinder?


Code:
import java.util.Scanner;
public class VolumeOfCylinder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double radius = sc.nextDouble();
double height = sc.nextDouble();
double volume = Math.PI * radius * radius * height;
System.out.println(volume);
}
}
Output:
35
141.3716694115407

130. Factorial of a Number?


Code:
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
}
System.out.println(factorial);
}
}
Output:
5
120

131. Average of Three Numbers?


Code:
import java.util.Scanner;
public class AverageOfThreeNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float a = sc.nextFloat();
float b = sc.nextFloat();
float c = sc.nextFloat();
float average = (a + b + c) / 3;
System.out.println(average);
}
}
Output:
5 10 15
10.0
132. Maximum of Two Numbers?
Code:
import java.util.Scanner;
public class MaxOfTwoNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(Math.max(a, b));
}
}
Output:
7 10
1
133. Minimum of Two Numbers?
Code:
import java.util.Scanner;
public class MinOfTwoNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println(Math.min(a, b));
}
}
Output:
7 10
7
134. Power of a Number?
Code:
import java.util.Scanner;
public class PowerOfNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double base = sc.nextDouble();
int exponent = sc.nextInt();
double result = Math.pow(base, exponent);
System.out.println(result);
}
}
Output:
23
8.0
135. Check Whether a Number is Prime?
Code:
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime && n > 1) {
System.out.println("Prime");
} else {
System.out.println("Not Prime");
}
}
}
Output:
7
Prime
136. Square Root of a Number?
Code:
import java.util.Scanner;
public class SquareRoot {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double number = sc.nextDouble();
System.out.println(Math.sqrt(number));
}
}
Output:
16
4.0
137. Perimeter of a Rectangle?
Code:
import java.util.Scanner;
public class PerimeterOfRectangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float length = sc.nextFloat();
float width = sc.nextFloat();
System.out.println(2 * (length + width));
}
}
Output:
5 10
30.0

138. Area of a Circle?


Code:
import java.util.Scanner;
public class AreaOfCircle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double radius = sc.nextDouble();
System.out.println(Math.PI * radius * radius);
}
}
Output:
3
28.274333882308138

139. Area of a Triangle?


Code:
import java.util.Scanner;
public class AreaOfTriangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double base = sc.nextDouble();
double height = sc.nextDouble();
System.out.println(0.5 * base * height);
}
}
Output:
5 10
25.0

140. Convert Celsius to Fahrenheit?


Code:
import java.util.Scanner;
public class CelsiusToFahrenheit {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double celsius = sc.nextDouble();
double fahrenheit = (celsius * 9 / 5) + 32;
System.out.println(fahrenheit);
}
}
Output:
25
77.0
141. Convert Fahrenheit to Celsius?
Code:
import java.util.Scanner;
public class FahrenheitToCelsius {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double fahrenheit = sc.nextDouble();
double celsius = (fahrenheit - 32) * 5 / 9;
System.out.println(celsius);
}
}
Output:
77
25.0
142. Volume of a Sphere?
Code:
import java.util.Scanner;
public class VolumeOfSphere {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double radius = sc.nextDouble();
double volume = (4 / 3) * Math.PI * Math.pow(radius, 3);
System.out.println(volume);
}
}
Output:
3
113.09733537928271

143. Average of an Array of Integers?


Code:
import java.util.Scanner;
public class AverageOfArray {
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 / n);
}
}
Output:
5
12345
3
144. Compound Interest?
Code:
import java.util.Scanner;
public class CompoundInterest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double principal = sc.nextDouble();
double rate = sc.nextDouble();
int time = sc.nextInt();
double compoundInterest = principal * Math.pow(1 + rate / 100, time) - principal;
System.out.println(compoundInterest);
}
}
Output:
1000 5 2
102.5

145. Area of a Trapezoid?


Code:
import java.util.Scanner;
public class AreaOfTrapezoid {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double height = sc.nextDouble();
System.out.println(0.5 * (a + b) * height);
}
}
Output:
5 10 8
60.0

146. Area of a Parallelogram?


Code:
import java.util.Scanner;
public class AreaOfParallelogram {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double base = sc.nextDouble();
double height = sc.nextDouble();
System.out.println(base * height);
}
}
Output:
58
40.0

147 Simple Interest?


Code:
import java.util.Scanner;
public class SimpleInterest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double principal = sc.nextDouble();
double rate = sc.nextDouble();
int time = sc.nextInt();
double interest = (principal * rate * time) / 100;
System.out.println(interest);
}
}
Output:
1000 5 2
100.0

148. Area of a Square?


Code:
import java.util.Scanner;
public class AreaOfSquare {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double side = sc.nextDouble();
System.out.println(side * side);
}
}
Output:
4
16.0

149. Area of a Rhombus?


Code:
import java.util.Scanner;
public class AreaOfRhombus {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double diagonal1 = sc.nextDouble();
double diagonal2 = sc.nextDouble();
System.out.println(0.5 * diagonal1 * diagonal2);
}
}
Output:
58
20.0
150. Area of a Regular Polygon?
Code:
import java.util.Scanner;
public class AreaOfRegularPolygon {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sides = sc.nextInt();
double sideLength = sc.nextDouble();
double area = (sides * Math.pow(sideLength, 2)) / (4 * Math.tan(Math.PI / sides));
System.out.println(area);
}
}
Output:
64
41.569219381653056

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!

158 Car Class with Private Variables and Getters/Setters?


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

159: Book Class with Private Variables and Getters/Setters?


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(10.99);
System.out.println("Book Details:");
System.out.println("Title: " + book.getTitle());
System.out.println("Author: " + book.getAuthor());
System.out.println("Price: $" + book.getPrice());
}
}
Output:
Book Details:
Title: To Kill a Mockingbird
Author: Harper Lee
Price: $10.99

160. Student Class with Private Variables and Getters/Setters?


Code:
class Student {
private String name;
private int rollNumber;
private double marks;
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 double getMarks() {
return marks;
}
public void setMarks(double marks) {
this.marks = marks;
}
public static void main(String[] args) {
Student student = new Student();
student.setName("Alice");
student.setRollNumber(101);
student.setMarks(95.5);
System.out.println("Student Details:");
System.out.println("Name: " + student.getName());
System.out.println("Roll Number: " + student.getRollNumber());
System.out.println("Marks: " + student.getMarks());
}
}
Output:
Student Details:
Name: Alice
Roll Number: 101
Marks: 95.5

161. Circle Class with Private Variables and Getters/Setters?


Code:
class Circle {
private double radius;
private double area;
private double circumference;
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
calculateArea();
calculateCircumference();
}
public double getArea() {
return area;
}
public double getCircumference() {
return circumference;
}
private void calculateArea() {
this.area = Math.PI * radius * radius;
}
private void calculateCircumference() {
this.circumference = 2 * Math.PI * radius;
}
public static void main(String[] args) {
Circle circle = new Circle();
circle.setRadius(5);
System.out.println("Circle Details:");
System.out.println("Radius: " + circle.getRadius());
System.out.println("Area: " + circle.getArea());
System.out.println("Circumference: " + circle.getCircumference());
}
}
Output:
Circle Details:
Radius: 5.0
Area: 78.53981633974483
Circumference: 31.41592653589793

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

165. Static Method to Find the Sum of Elements in an Array?


Code:
class ArraySum {
static int sum(int[] arr) {
int total = 0;
for (int num : arr) {
total += num;
}
return total;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int result = sum(arr);
System.out.println("Sum of array elements: " + result);
}
}
Output:
Sum of array elements: 15
166. Static Method to Find the Maximum of Two Numbers?
Code:
class MaxNumber {
static int max(int a, int b) {
return (a > b) ? a : b;
}
public static void main(String[] args) {
int result = max(10, 20);
System.out.println("Maximum: " + result);
}
}
Output:
Maximum: 20
167. Static Method to Find the Minimum of Two Numbers?
Code:
class MinNumber {
static int min(int a, int b) {
return (a < b) ? a : b;
}
public static void main(String[] args) {
int result = min(10, 20);
System.out.println("Minimum: " + result);
}
}
Output:
Minimum: 10

168. Static Method to Find the Power of a Number?


Code:
class Power {
static int power(int base, int exponent) {
return (int) Math.pow(base, exponent);
}
public static void main(String[] args) {
int result = power(2, 3);
System.out.println("Power: " + result);
}
}
Output:
Power: 8
169. Static Method to Calculate the Square Root of a Number?
Code:
class SquareRoot {
static double squareRoot(double number) {
return Math.sqrt(number);
}
public static void main(String[] args) {
double result = squareRoot(25);
System.out.println("Square root: " + result);
}
}
Output:
Square root: 5.0
170. Static Method to Find the Area of a Triangle?
Code:
class TriangleArea {
static double area(double base, double height) {
return 0.5 * base * height;
}
public static void main(String[] args) {
double result = area(10, 5);
System.out.println("Area of triangle: " + result);
}
}
Output:
Area of triangle: 25.0
171. Static Method to Calculate Simple Interest?
Code:
class SimpleInterest {
static double calculateSI(double principal, double rate, double time) {
return (principal * rate * time) / 100;
}
public static void main(String[] args) {
double result = calculateSI(1000, 5, 2);
System.out.println("Simple Interest: " + result);
}
}
Output:
Simple Interest: 100.0
172.Static Method to Find the Volume of a Cylinder?
Code:
class CylinderVolume {
static double volume(double radius, double height) {
return Math.PI * radius * radius * height;
}
public static void main(String[] args) {
double result = volume(3, 7);
System.out.println("Volume of cylinder: " + result);
}
}
Output:
Volume of cylinder: 197.92033717615698
173. Static Method to Calculate Compound Interest?
Code:
class CompoundInterest {
static double calculateCI(double principal, double rate, double time) {
return principal * Math.pow((1 + rate / 100), time) - principal;
}
public static void main(String[] args) {
double result = calculateCI(1000, 5, 2);
System.out.println("Compound Interest: " + result);
}
}
Output:
Compound Interest: 102.5
174. Static Method to Find the Area of a Rectangle?
Code:
class RectangleArea {
static double area(double length, double breadth) {
return length * breadth;
}
public static void main(String[] args) {
double result = area(10, 5);
System.out.println("Area of rectangle: " + result);
}
}
Output:
Area of rectangle: 50.0
175.Static Method to Find the Area of a Square?
Code:
class SquareArea {
static double area(double side) {
return side * side;
}
public static void main(String[] args) {
double result = area(4);
System.out.println("Area of square: " + result);
}
}
Output:
Area of square: 16.0
176. Static Method to Find the Area of a Rhombus?
Code:
class RhombusArea {
static double area(double diagonal1, double diagonal2) {
return 0.5 * diagonal1 * diagonal2;
}
public static void main(String[] args) {
double result = area(6, 8);
System.out.println("Area of rhombus: " + result);
}
}
Output:
Area of rhombus: 24.0
177. Static Method to Find the Area of a Parallelogram?
Code:
class ParallelogramArea {
static double area(double base, double height) {
return base * height;
}
public static void main(String[] args) {
double result = area(10, 5);
System.out.println("Area of parallelogram: " + result);
}
}
Output:
Area of parallelogram: 50.0
178. Static Method to Find the Area of a Trapezoid?
java
Copy code
class TrapezoidArea {
static double area(double base1, double base2, double height) {
return 0.5 * (base1 + base2) * height;
}
public static void main(String[] args) {
double result = area(5, 10, 4);
System.out.println("Area of trapezoid: " + result);
}
}
Output:
Area of trapezoid: 30.0
179. Static Method to Find the Area of a Regular Polygon?
Code:
class RegularPolygonArea {
static double area(double sides, double length) {
return (sides * length * length) / (4 * Math.tan(Math.PI / sides));
}
public static void main(String[] args) {
double result = area(6, 10);
System.out.println("Area of regular polygon: " + result);
}
}
Output:
Area of regular polygon: 259.8076
180. Static Method to Convert Temperature from Celsius to Fahrenheit?
Code:
class CelsiusToFahrenheit {
static double convert(double celsius) {
return (celsius * 9 / 5) + 32;
}
public static void main(String[] args) {
double result = convert(25);
System.out.println("Fahrenheit: " + result);
}
}
Output:
Fahrenheit: 77.0
181. Static Method to Convert Temperature from Fahrenheit to Celsius?
Code:
class FahrenheitToCelsius {
static double convert(double fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
public static void main(String[] args) {
double result = convert(77);
System.out.println("Celsius: " + result);
}
}
Output:
Celsius: 25.0
182.Static Method to Find the Factorial of a Number Using Recursion?
code
class FactorialRecursion {
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
183. Static Method to Find the Sum of Digits of a Number Using Recursion?
Code:
class SumOfDigits {
static int sum(int number) {
if (number == 0) return 0;
return number % 10 + sum(number / 10);
}
public static void main(String[] args) {
int result = sum(123);
System.out.println("Sum of digits: " + result);
}
}
Output:
Sum of digits: 6
184.Static Method to Find the Power of a Number Using Recursion?
Code:
class PowerRecursion {
static int power(int base, int exponent) {
if (exponent == 0) return 1;
return base * power(base, exponent - 1);
}
public static void main(String[] args) {
int result = power(2, 3);
System.out.println("Power: " + result);
}
}
Output:
Power: 8
185. Static Method to Find the Fibonacci Series Using Recursion?
Code:
class Fibonacci {
static int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
int result = fibonacci(6);
System.out.println("Fibonacci: " + result);
}
}
Output:
Fibonacci: 8
186. Static Method to Reverse a String Using Recursion
java
Copy code
class ReverseString {
static String reverse(String str) {
if (str.isEmpty()) return str;
return reverse(str.substring(1)) + str.charAt(0);
}
public static void main(String[] args) {
String result = reverse("hello");
System.out.println("Reversed String: " + result);
}
}
Output:
Reversed String: olleh

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

189.Abstract Class "Employee" with Abstract Methods "calculateSalary" and "calculateBonus",


Implemented in Subclasses "Manager" and "Clerk"?
Code:
abstract class Employee {
abstract double calculateSalary();
abstract double calculateBonus();
}
class Manager extends Employee {
@Override
double calculateSalary() {
return 50000;
}
@Override
double calculateBonus() {
return 10000;
}
}
class Clerk extends Employee {
@Override
double calculateSalary() {
return 20000;
}
@Override
double calculateBonus() {
return 3000;
}
}
public class Main {
public static void main(String[] args) {
Employee manager = new Manager();
Employee clerk = new Clerk();
System.out.println("Manager Salary: " + manager.calculateSalary());
System.out.println("Manager Bonus: " + manager.calculateBonus());
System.out.println("Clerk Salary: " + clerk.calculateSalary());
System.out.println("Clerk Bonus: " + clerk.calculateBonus());
}
}
Output:
Manager Salary: 50000.0
Manager Bonus: 10000.0
Clerk Salary: 20000.0
Clerk Bonus: 3000.0

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

192.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 base * 3; // Assuming an equilateral triangle for simplicity
}
}
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

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();
}

class Car extends Vehicle {


@Override
void drive() {
System.out.println("Car is driving");
}

@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");
}
}

public class Main {


public static void main(String[] args) {
Vehicle car = new Car();
Vehicle truck = new Truck();

car.drive();
car.stop();

truck.drive();
truck.stop();
}
}
Output:
Car is driving
Car has stopped
Truck is driving
Truck has stopped
MULTI THREADING

1.Create multiple threads and display their names

package MultiThreading;

class MyThread extends Thread {

public void run() {

System.out.println("Thread Name: " + Thread.currentThread().getName());

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

t1.start();

t2.start();

Output: Enter a number: 10

10 is not a palindrome.

//2. Thread synchronization using synchronized block

package MultiThreading;

class synchronizedExample {

private int count = 0;

public void increment() {

synchronized (this) {

count++;

public int getCount() {

return count;

}
MULTI THREADING

public static void main(String[] args) throws InterruptedException {

synchronizedExample obj = new synchronizedExample();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) obj.increment();

});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) obj.increment();

});

t1.start();

t2.start();

t1.join();

t2.join();

System.out.println("Final count: " + obj.getCount());

Output: Final count: 2000

//3. Create multiple threads and display their priorities

package MultiThreading;

public class Threadwithpriority extends Thread {

public void run() {

System.out.println("Thread " + Thread.currentThread().getName() + " Priority: " +


Thread.currentThread().getPriority());

public static void main(String[] args) {

Thread t1 = new Threadwithpriority();

Thread t2 = new Threadwithpriority();

t1.setPriority(Thread.MIN_PRIORITY);
MULTI THREADING

t2.setPriority(Thread.MAX_PRIORITY);

t1.start();

t2.start();

Output: Thread Thread-1 Priority: 10

Thread Thread-0 Priority: 1

//4. Create a thread pool and execute multiple tasks using ExecutorService

package MultiThreading;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

class Task implements Runnable {

public void run() {

System.out.println(Thread.currentThread().getName() + " is executing task");

public static void main(String[] args) {

ExecutorService executor = Executors.newFixedThreadPool(3);

for (int i = 0; i < 5; i++) {

executor.submit(new Task());

executor.shutdown();

Output: pool-1-thread-3 is executing task

//5. Create multiple threads and join them

package MultiThreading;
MULTI THREADING

class JoinExample extends Thread {

public void run() {

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

public static void main(String[] args) throws InterruptedException {

JoinExample t1 = new JoinExample();

JoinExample t2 = new JoinExample();

t1.start();

t2.start();

t1.join();

t2.join();

System.out.println("All threads are finished.");

Output: All threads are finished.

//6. Demonstrate a deadlock condition:

public class ThreadInterruptDemo {

public static void main(String[] args) throws InterruptedException {

MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();

thread1.start();

thread2.start();

Thread.sleep(500);

thread1.interrupt();

thread2.interrupt();

}
MULTI THREADING

Output:

//7. Create multiple threads and interrupt them:

class MyThread extends Thread {


public void run() {
while (!isInterrupted()) {
System.out.println(Thread.currentThread().getName() + " is running");
}
System.out.println(Thread.currentThread().getName() + " was interrupted");
}
}

public class ThreadInterruptDemo {


public static void main(String[] args) throws InterruptedException {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();

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

class MyThread extends Thread {

private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

public void run() {

threadLocal.set(threadLocal.get() + 1);

System.out.println(Thread.currentThread().getName() + " ThreadLocal value: " +


threadLocal.get());

public class ThreadLocalDemo {

public static void main(String[] args) {

MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();

thread1.start();

thread2.start();

Output: Thread-0 ThreadLocal value: 1

Thread-1 ThreadLocal value: 1

//9. Wait for threads to complete using CountDownLatch:

import java.util.concurrent.CountDownLatch;

class MyThread extends Thread {

private CountDownLatch latch;

public MyThread(CountDownLatch latch) {

this.latch = latch;

}
MULTI THREADING

public void run() {

try {

System.out.println(Thread.currentThread().getName() + " is running");

} finally {

latch.countDown();

public class CountDownLatchDemo {

public static void main(String[] args) throws InterruptedException {

CountDownLatch latch = new CountDownLatch(2);

MyThread thread1 = new MyThread(latch);

MyThread thread2 = new MyThread(latch);

thread1.start();

thread2.start();

latch.await();

System.out.println("Both threads have completed");

Output: Thread-0 is running

Thread-1 is running

Both threads have completed

//10. Demonstrate thread priorities in Java:

class MyThread extends Thread {

public void run() {


MULTI THREADING

System.out.println(Thread.currentThread().getName() + " with priority: " +


Thread.currentThread().getPriority());

public class ThreadPriorityExample {

public static void main(String[] args) {

MyThread thread1 = new MyThread();

thread1.setPriority(Thread.MIN_PRIORITY);

thread1.start();

MyThread thread2 = new MyThread();

thread2.setPriority(Thread.MAX_PRIORITY);

thread2.start();

Output: Thread-0 with priority: 1

Thread-1 with priority: 10

//11. Create multiple threads and use thread groups:

class MyThread extends Thread {

public void run() {

System.out.println(Thread.currentThread().getName() + " in thread group: " +


getThreadGroup().getName());

public class ThreadGroupDemo {

public static void main(String[] args) {

ThreadGroup group = new ThreadGroup("MyGroup");


MULTI THREADING

MyThread thread1 = new MyThread();

thread1.setThreadGroup(group);

thread1.start();

MyThread thread2 = new MyThread();

thread2.setThreadGroup(group);

thread2.start();

Output: Thread-0 in thread group: MyGroup

Thread-1 in thread group: MyGroup

//12. Thread communication using wait() and notify() methods:

class Producer implements Runnable {

private final Object lock;

public Producer(Object lock) {

this.lock = lock;

@Override

public void run() {

synchronized (lock) {

System.out.println("Producer: Producing item...");

lock.notify(); // Notify the consumer

}
MULTI THREADING

class Consumer implements Runnable {

private final Object lock;

public Consumer(Object lock) {

this.lock = lock;

@Override

public void run() {

synchronized (lock) {

try {

System.out.println("Consumer: Waiting for item...");

lock.wait(); // Wait for the producer

} catch (InterruptedException e) {

e.printStackTrace();

System.out.println("Consumer: Consumed item!");

public class WaitNotifyDemo {

public static void main(String[] args) throws InterruptedException {

Object lock = new Object();

Thread producer = new Thread(new Producer(lock));

Thread consumer = new Thread(new Consumer(lock));

consumer.start();
MULTI THREADING

producer.start();

consumer.join();

producer.join();

Output: Consumer: Waiting for item...

Producer: Producing item...

Consumer: Consumed item!

//13. Create multiple threads and use thread-local variables:

class MyThread extends Thread {

private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(() -> 0);

public void run() {

threadLocal.set(threadLocal.get() + 1);

System.out.println(Thread.currentThread().getName() + " ThreadLocal value: " +


threadLocal.get());

public class ThreadLocalDemo {

public static void main(String[] args) {

MyThread thread1 = new MyThread();

MyThread thread2 = new MyThread();

thread1.start();

thread2.start();

}
MULTI THREADING

Output: Thread-0 ThreadLocal value: 1

Thread-1 ThreadLocal value: 1

//14. Thread communication using volatile keyword:

class SharedResource {

private volatile boolean flag = false;

public void toggleFlag() {

flag = !flag;

public boolean getFlag() {

return flag;

class MyThread extends Thread {

private SharedResource resource;

public MyThread(SharedResource resource) {

this.resource = resource;

public void run() {

while (!resource.getFlag()) {

System.out.println(Thread.currentThread().getName() + " waiting for flag...");

System.out.println(Thread.currentThread().getName() + " detected flag change!");

}
MULTI THREADING

public class VolatileDemo {

public static void main(String[] args) throws InterruptedException {

SharedResource resource = new SharedResource();

MyThread thread1 = new MyThread(resource);

MyThread thread2 = new MyThread(resource);

thread1.start();

thread2.start();

Thread.sleep(2000);

resource.toggleFlag(); // Change flag to true

Output: Thread-0 waiting for flag...

Thread-1 waiting for flag...

Thread-0 detected flag change!

Thread-1 detected flag change!

//15. Create multiple threads and use Executors framework:

import java.util.concurrent.*;

public class ExecutorServiceDemo {

public static void main(String[] args) {

ExecutorService executor = Executors.newFixedThreadPool(2);

Runnable task1 = () -> System.out.println(Thread.currentThread().getName() + " is executing task


1");
MULTI THREADING

Runnable task2 = () -> System.out.println(Thread.currentThread().getName() + " is executing task


2");

executor.submit(task1);

executor.submit(task2);

executor.shutdown();

Output: pool-1-thread-1 is executing task 1

pool-1-thread-2 is executing task 2

//16. Demonstrate thread interruption in Java:

class MyThread extends Thread {

public void run() {

try {

for (int i = 0; i < 10; i++) {

if (isInterrupted()) {

System.out.println(Thread.currentThread().getName() + " was interrupted");

return;

System.out.println(Thread.currentThread().getName() + " is running");

Thread.sleep(500);

} catch (InterruptedException e) {

System.out.println(Thread.currentThread().getName() + " interrupted during sleep");

}
MULTI THREADING

public class ThreadInterruptDemo {

public static void main(String[] args) throws InterruptedException {

MyThread thread = new MyThread();

thread.start();

Thread.sleep(2000);

thread.interrupt();

Output: Thread-0 is running

Thread-1 is running

Thread-0 was interrupted

Thread-1 was interrupted

//17. Create multiple threads and use Callable and Future:

import java.util.concurrent.*;

class MyCallable implements Callable<Integer> {

@Override

public Integer call() {

return 100;

public class CallableFutureDemo {

public static void main(String[] args) throws ExecutionException, InterruptedException {

ExecutorService executor = Executors.newFixedThreadPool(2);

Callable<Integer> task = new MyCallable();

Future<Integer> future = executor.submit(task);

System.out.println("Result from Callable: " + future.get());


MULTI THREADING

executor.shutdown();

Output: Result from Callable: 100

//18. Thread communication using BlockingQueue:

import java.util.concurrent.*;

class Producer implements Runnable {

private BlockingQueue<Integer> queue;

public Producer(BlockingQueue<Integer> queue) {

this.queue = queue;

@Override

public void run() {

try {

queue.put(1);

System.out.println("Produced item 1");

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

class Consumer implements Runnable {

private BlockingQueue<Integer> queue;


MULTI THREADING

public Consumer(BlockingQueue<Integer> queue) {

this.queue = queue;

@Override

public void run() {

try {

Integer item = queue.take();

System.out.println("Consumed item " + item);

} catch (InterruptedException e) {

Thread.currentThread().interrupt();

public class BlockingQueueDemo {

public static void main(String[] args) throws InterruptedException {

BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);

Thread producer = new Thread(new Producer(queue));

Thread consumer = new Thread(new Consumer(queue));

producer.start();

consumer.start();

producer.join();

consumer.join();

Output: Produced item 1


MULTI THREADING

Consumed item 1

//19. Create multiple threads and use Phaser:

import java.util.concurrent.*;

public class PhaserDemo {

public static void main(String[] args) {

Phaser phaser = new Phaser(1); // Register main thread

Runnable task = () -> {

System.out.println(Thread.currentThread().getName() + " is starting");

phaser.arriveAndAwaitAdvance(); // Wait for other threads

System.out.println(Thread.currentThread().getName() + " is completed");

};

for (int i = 0; i < 3; i++) {

new Thread(task).start();

phaser.register(); // Register each new thread

phaser.arriveAndDeregister(); // Main thread arrives

Output: Thread-0 is starting

Thread-1 is starting

Thread-2 is starting

All threads reached barrier

Thread-0 is completed

Thread-1 is completed

Thread-2 is completed
MULTI THREADING

//20. Thread communication using CyclicBarrier:

import java.util.concurrent.*;

class Task implements Runnable {

private CyclicBarrier barrier;

public Task(CyclicBarrier barrier) {

this.barrier = barrier;

@Override

public void run() {

try {

System.out.println(Thread.currentThread().getName() + " is ready");

barrier.await(); // Wait for all threads to reach barrier

System.out.println(Thread.currentThread().getName() + " is executing after barrier");

} catch (InterruptedException | BrokenBarrierException e) {

e.printStackTrace();

public class CyclicBarrierDemo {

public static void main(String[] args) {

CyclicBarrier barrier = new CyclicBarrier(3, () -> System.out.println("All threads reached barrier"));

for (int i = 0; i < 3; i++) {

new Thread(new Task(barrier)).start();

}
MULTI THREADING

Output: Thread-0 is ready

Thread-1 is ready

Thread-2 is ready

All threads reached barrier

Thread-0 is executing after barrier

Thread-1 is executing after barrier

Thread-2 is executing after barrier

//21. Create multiple threads and use Semaphore:

import java.util.concurrent.*;

class SemaphoreTask implements Runnable {

private Semaphore semaphore;

public SemaphoreTask(Semaphore semaphore) {

this.semaphore = semaphore;

@Override

public void run() {

try {

semaphore.acquire();

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

Thread.sleep(2000);

semaphore.release();

} catch (InterruptedException e) {

e.printStackTrace();

}
MULTI THREADING

public class SemaphoreDemo {

public static void main(String[] args) throws InterruptedException {

Semaphore semaphore = new Semaphore(2); // Two permits available

for (int i = 0; i < 5; i++) {

new Thread(new SemaphoreTask(semaphore)).start();

Output: Thread-0 is executing

Thread-1 is executing

Thread-2 is executing

Thread-3 is executing

Thread-4 is executing

//22. Thread communication using Exchanger:

import java.util.concurrent.*;

class ExchangerTask implements Runnable {

private Exchanger<String> exchanger;

public ExchangerTask(Exchanger<String> exchanger) {

this.exchanger = exchanger;

@Override

public void run() {


MULTI THREADING

try {

String message = exchanger.exchange("Hello from " + Thread.currentThread().getName());

System.out.println(Thread.currentThread().getName() + " received: " + message);

} catch (InterruptedException e) {

e.printStackTrace();

public class ExchangerDemo {

public static void main(String[] args) throws InterruptedException {

Exchanger<String> exchanger = new Exchanger<>();

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

new Thread(new ExchangerTask(exchanger)).start();

Output:

Thread-0 received: Hello from Thread-1

Thread-1 received: Hello from Thread-0

//23. Create multiple threads and use CompletionService:

import java.util.concurrent.*;

class Task implements Callable<Integer> {

@Override

public Integer call() throws Exception {

return 100;

}
MULTI THREADING

public class CompletionServiceDemo {

public static void main(String[] args) throws InterruptedException, ExecutionException {

ExecutorService executor = Executors.newFixedThreadPool(2);

CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);

completionService.submit(new Task());

completionService.submit(new Task());

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

System.out.println("Result: " + completionService.take().get());

executor.shutdown();

Output: Result: 100

Result: 100

//24. Thread communication using TransferQueue:

import java.util.concurrent.*;

class TransferQueueTask implements Runnable {

private TransferQueue<Integer> queue;

public TransferQueueTask(TransferQueue<Integer> queue) {

this.queue = queue;

}
MULTI THREADING

@Override

public void run() {

try {

Integer item = queue.take();

System.out.println(Thread.currentThread().getName() + " consumed: " + item);

} catch (InterruptedException e) {

e.printStackTrace();

public class TransferQueueDemo {

public static void main(String[] args) throws InterruptedException {

TransferQueue<Integer> queue = new LinkedTransferQueue<>();

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

new Thread(new TransferQueueTask(queue)).start();

queue.transfer(1);

Output: Thread-0 consumed: 1

Thread-1 consumed: 1

//25. Create multiple threads and use ScheduledExecutorService:

import java.util.concurrent.*;

public class ScheduledExecutorServiceDemo {

public static void main(String[] args) {


MULTI THREADING

ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

executor.scheduleAtFixedRate(() -> System.out.println("Task executed at: " +


System.currentTimeMillis()), 0, 1, TimeUnit.SECONDS);

Output: Task executed at: <timestamp>

Task executed at: <timestamp>

Task executed at: <timestamp>

...

//26. Thread communication using Lock and Condition:

import java.util.concurrent.locks.*;

class LockConditionTask implements Runnable {

private Lock lock;

private Condition condition;

public LockConditionTask(Lock lock, Condition condition) {

this.lock = lock;

this.condition = condition;

@Override

public void run() {

lock.lock();

try {

System.out.println(Thread.currentThread().getName() + " is waiting");

condition.await(); // Wait for notification

System.out.println(Thread.currentThread().getName() + " is notified");


MULTI THREADING

} catch (InterruptedException e) {

e.printStackTrace();

} finally {

lock.unlock();

public class LockConditionDemo {

public static void main(String[] args) throws InterruptedException {

Lock lock = new ReentrantLock();

Condition condition = lock.newCondition();

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

new Thread(new LockConditionTask(lock, condition)).start();

Thread.sleep(1000); // Simulate some work

lock.lock();

try {

System.out.println("Main thread notifying all threads");

condition.signalAll(); // Notify all waiting threads

} finally {

lock.unlock();

Output: Thread-0 is waiting


MULTI THREADING

Thread-1 is waiting

Main thread notifying all threads

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

// Calling methods from the interfaces


shape.draw(); // Drawable method
shape.resize(); // Resizable method
}
}
Output: Drawing the shape.
Resizing the shape.
2. Write a program to demonstrate interface implementation by creating objects of the shape class
and invoking interface methods.
public class InterfaceDemo {
public static void main(String[] args) {
Shape shape = new Shape(); // Create an object of the Shape class

// Calling methods from the interfaces


shape.draw(); // Drawable method
shape.resize(); // Resizable method
}
}

Output: Drawing the shape.

Resizing the shape.

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

// Calling methods from the interfaces


shape.draw(); // Drawable method
shape.resize(); // Resizable method
}
}
Output: Drawing the shape.
Resizing the shape.
4. Write a program to demonstrate interface implementation by creating objects of the and fish
classes and invoking interface methods
public class InterfaceDemo2 {
public static void main(String[] args) {
Bird bird = new Bird(); // Create an object of the Bird class
Interface

Fish fish = new Fish(); // Create an object of the Fish class

// Calling methods from the interfaces


bird.fly(); // Flyable method
fish.swim(); // Swimable method
}
}

Output: The bird is flying.

The fish is swimming.

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();
}

class Number implements Comparable, Cloneable {


int value;

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

class Person implements Comparable, Cloneable {


String name;

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;
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Number num1 = new Number(5);
Number num2 = new Number(10);
System.out.println("Comparison of num1 and num2: " + num1.compareTo(num2));

Person person1 = new Person("Alice");


Person person2 = new Person("Bob");
System.out.println("Comparison of person1 and person2: " + person1.compareTo(person2));

// Cloning
Number clonedNum = (Number) num1.clone();
Person clonedPerson = (Person) person1.clone();
System.out.println("Cloned Number: " + clonedNum);
System.out.println("Cloned Person: " + clonedPerson);
}
}

Output: Comparison of num1 and num2: -1

Comparison of person1 and person2: -1


Interface

Cloned Number: Number: 5

Cloned Person: Person: Alice

6. Write a program to demonstrate interface implementation by creating objects of the number


and person classes and invoking interface methods.
public class InterfaceDemo {
public static void main(String[] args) {
Number num1 = new Number(5);
Number num2 = new Number(10);
System.out.println("Comparison of num1 and num2: " + num1.compareTo(num2));

Person person1 = new Person("Alice");


Person person2 = new Person("Bob");
System.out.println("Comparison of person1 and person2: " + person1.compareTo(person2));

// Cloning
Number clonedNum = (Number) num1.clone();
Person clonedPerson = (Person) person1.clone();
System.out.println("Cloned Number: " + clonedNum);
System.out.println("Cloned Person: " + clonedPerson);
}
}

Output: Comparison of num1 and num2: -1

Comparison of person1 and person2: -1

Cloned Number: Number: 5

Cloned Person: Person: Alice

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);
}

class ArrayList implements List {


Interface

java.util.ArrayList<Object> list = new java.util.ArrayList<>();

@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);
}
}

class HashSet implements Set {


java.util.HashSet<Object> set = new java.util.HashSet<>();

@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);
}
}

Output: ArrayList contains 'Item1': true

ArrayList contains 'Item1' after removal: false

HashSet contains 'ItemA': true

HashSet contains 'ItemA' after removal: false

8. Write a program to demonstrate interface implementation by creating objects of the array list
and hash set classes and invoking interface methods.
Interface

public class ListSetDemo {


public static void main(String[] args) {
List arrayList = new ArrayList();
arrayList.add("Item1");
arrayList.add("Item2");
System.out.println("ArrayList contains 'Item1': " + arrayList.contains("Item1"));
arrayList.remove("Item1");
System.out.println("ArrayList contains 'Item1' after removal: " + arrayList.contains("Item1"));

Set hashSet = new HashSet();


hashSet.add("ItemA");
hashSet.add("ItemB");
System.out.println("HashSet contains 'ItemA': " + hashSet.contains("ItemA"));
hashSet.remove("ItemA");
System.out.println("HashSet contains 'ItemA' after removal: " + hashSet.contains("ItemA"));
}
}

Output: ArrayList contains 'Item1': true

ArrayList contains 'Item1' after removal: false

HashSet contains 'ItemA': true

HashSet contains 'ItemA' after removal: false

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();
}

class Printer implements Printable {


@Override
public void print() {
System.out.println("Printing document...");
}
}

class Scanner implements Scannable {


@Override
public void scan() {
System.out.println("Scanning document...");
Interface

}
}

Output: Printing document...

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();

Scanner scanner = new Scanner();


scanner.scan();
}
}

Output: Printing document...

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);
}

class List implements Sortable, Searchable {


java.util.ArrayList<Object> list = new java.util.ArrayList<>();

@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

public void add(Object obj) {


list.add(obj);
}
}

class Dictionary implements Searchable {


java.util.HashMap<String, String> map = new java.util.HashMap<>();

@Override
public boolean search(Object obj) {
return map.containsValue(obj);
}

public void add(String key, String value) {


map.put(key, value);
}
}

Output: List sorted: [Item1, Item2]

Item 'Item1' found in list: true

Value 'value1' found in dictionary: true

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"));

Dictionary dictionary = new Dictionary();


dictionary.add("key1", "value1");
System.out.println("Value 'value1' found in dictionary: " + dictionary.search("value1"));
}
}

Output: List sorted: [Item1, Item2]

Item 'Item1' found in list: true

Value 'value1' found in dictionary: true

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();
}

class File implements Serializable {


@Override
public void serialize() {
System.out.println("File serialized.");
}
}

class Database implements Deserializable {


@Override
public void deserialize() {
System.out.println("Database deserialized.");
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Serializable file = new File();
Deserializable database = new Database();

file.serialize();
database.deserialize();
}
}

Output: File serialized.

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 database = new Database();


database.serialize();
Interface

database.deserialize();
}
}

Output: File serialized.

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();
}

class Encoder implements Encryptable {


@Override
public void encrypt() {
System.out.println("Encrypting data...");
}
}

class Decoder implements Decryptable {


@Override
public void decrypt() {
System.out.println("Decrypting data...");
}
}

Output: Encrypting data...

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 decoder = new Decoder();


Interface

decoder.decrypt();
}
}

Output: Encrypting data...

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();
}

class Cheetah implements Runnable {


@Override
public void run() {
System.out.println("Cheetah is running...");
}
}

class Tortoise implements Walkable {


@Override
public void walk() {
System.out.println("Tortoise is walking...");
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Runnable cheetah = new Cheetah();
Walkable tortoise = new Tortoise();

cheetah.run();
tortoise.walk();
}
}

Output: Cheetah is running...

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 tortoise = new Tortoise();


tortoise.walk();
}
}

Output: Cheetah is running...

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();
}

class MusicPlayer implements Playable {


@Override
public void play() {
System.out.println("Playing music...");
}
}

class Recorder implements Recordable {


@Override
public void record() {
System.out.println("Recording audio...");
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Playable musicPlayer = new MusicPlayer();
Recordable recorder = new Recorder();

musicPlayer.play();
Interface

recorder.record();
}
}

Output: Playing music...

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();

Recorder recorder = new Recorder();


recorder.record();
}
}

Output: Playing music...

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();
}

class Whiteboard implements Drawable, Erasable {


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

@Override
public void erase() {
System.out.println("Erasing the whiteboard...");
}
}

class Chalkboard implements Drawable, Erasable {


Interface

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

@Override
public void erase() {
System.out.println("Erasing the chalkboard...");
}
}

Output: Drawing on the whiteboard...

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();

Chalkboard chalkboard = new Chalkboard();


chalkboard.draw();
chalkboard.erase();
}
}

Output: Drawing on the whiteboard...

Erasing the whiteboard...

Drawing on the chalkboard...

Erasing the chalkboard...

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();
}

class Transmitter implements Sendable {


Interface

@Override
public void send() {
System.out.println("Transmitter sending data...");
}
}

class Receiver implements Receivable {


@Override
public void receive() {
System.out.println("Receiver receiving data...");
}
}

Output: Transmitter sending data...

Receiver receiving 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();

Receiver receiver = new Receiver();


receiver.receive();
}
}

Output: Transmitter sending data...

Receiver receiving data...

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();
}

class EncryptionAlgorithm implements Encryptable {


@Override
public void encrypt() {
System.out.println("Encrypting data using algorithm...");
Interface

}
}

class DecryptionAlgorithm implements Decryptable {


@Override
public void decrypt() {
System.out.println("Decrypting data using algorithm...");
}
}

Output: Encrypting data using encryption algorithm...

Decrypting data using decryption algorithm...


Inheritance

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;

// Constructor for Vehicle class


public Vehicle(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
}

// Subclass Car
class Car extends Vehicle {
String color;
int mileage;

// Constructor for Car class


public Car(String make, String model, int year, String color, int mileage) {
super(make, model, year); // Call the constructor of Vehicle
this.color = color;
this.mileage = mileage;
}

// Method to display car details


public void displayCarDetails() {
System.out.println("Car Details: Make - " + make + ", Model - " + model + ", Year - " + year +
", Color - " + color + ", Mileage - " + mileage);
}
}

public class Main {


public static void main(String[] args) {
// Create object of Car
Car car = new Car("Toyota", "Camry", 2022, "Blue", 15000);

// Access properties and display car details


car.displayCarDetails();
}
}
Inheritance

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

public class Main {


public static void main(String[] args) {
// Create object of Car
Car car = new Car("Toyota", "Corolla", 2021, "Red", 12000);

// Access properties and display car details


car.displayCarDetails();
}
}

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;

// Constructor for Shape class


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

// Abstract methods for area and perimeter


abstract double area();
abstract double perimeter();
}

// Subclass Circle
class Circle extends Shape {
double radius;

// Constructor for Circle class


public Circle(String color, double radius) {
super(color);
this.radius = radius;
}

// Override area method for Circle


@Override
Inheritance

public double area() {


return Math.PI * radius * radius;
}

// Override perimeter method for Circle


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

// Subclass Rectangle
class Rectangle extends Shape {
double length;
double width;

// Constructor for Rectangle class


public Rectangle(String color, double length, double width) {
super(color);
this.length = length;
this.width = width;
}

// Override area method for Rectangle


@Override
public double area() {
return length * width;
}

// Override perimeter method for Rectangle


@Override
public double perimeter() {
return 2 * (length + width);
}
}

public class Main {


public static void main(String[] args) {
// Create object of Circle
Circle circle = new Circle("Red", 5);
System.out.println("Circle Area: " + circle.area());
System.out.println("Circle Perimeter: " + circle.perimeter());

// Create object of Rectangle


Inheritance

Rectangle rectangle = new Rectangle("Blue", 6, 8);


System.out.println("Rectangle Area: " + rectangle.area());
System.out.println("Rectangle Perimeter: " + rectangle.perimeter());
}
}

Output: Circle Area: 78.53981633974483

Circle Perimeter: 31.41592653589793

Rectangle Area: 48.0

Rectangle Perimeter: 28.0

4. Write a program to demonstrate inheritance by creating objects of derived classes and invoking
base class methods.
// Reusing Shape, Circle, and Rectangle classes

public class Main {


public static void main(String[] args) {
// Create object of Circle
Circle circle = new Circle("Green", 7);
System.out.println("Circle Area: " + circle.area());
System.out.println("Circle Perimeter: " + circle.perimeter());

// Create object of Rectangle


Rectangle rectangle = new Rectangle("Yellow", 10, 5);
System.out.println("Rectangle Area: " + rectangle.area());
System.out.println("Rectangle Perimeter: " + rectangle.perimeter());
}
}

Output: Circle Area: 153.93804002589985

Circle Perimeter: 43.982297150257104

Rectangle Area: 50.0

Rectangle Perimeter: 30.0

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;

// Constructor for Animal class


public Animal(String name, int age) {
Inheritance

this.name = name;
this.age = age;
}
}

// Subclass Dog
class Dog extends Animal {
String breed;
String color;

// Constructor for Dog class


public Dog(String name, int age, String breed, String color) {
super(name, age); // Call the constructor of Animal
this.breed = breed;
this.color = color;
}

// Method to display dog details


public void displayDogDetails() {
System.out.println("Dog Details: Name - " + name + ", Age - " + age + ", Breed - " + breed + ",
Color - " + color);
}
}

// Subclass Cat
class Cat extends Animal {
String breed;
String color;

// Constructor for Cat class


public Cat(String name, int age, String breed, String color) {
super(name, age); // Call the constructor of Animal
this.breed = breed;
this.color = color;
}

// Method to display cat details


public void displayCatDetails() {
System.out.println("Cat Details: Name - " + name + ", Age - " + age + ", Breed - " + breed + ",
Color - " + color);
}
}

public class Main {


Inheritance

public static void main(String[] args) {


// Create object of Dog
Dog dog = new Dog("Buddy", 3, "Golden Retriever", "Golden");
dog.displayDogDetails();

// Create object of Cat


Cat cat = new Cat("Mittens", 2, "Siamese", "White");
cat.displayCatDetails();
}
}

Output: Dog Details: Name - Buddy, Age - 3, Breed - Golden Retriever, Color - Golden

Cat Details: Name - Mittens, Age - 2, Breed - Siamese, Color – White

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;

public Animal(String name, int age) {


this.name = name;
this.age = age;
}
}

// Subclass Dog
class Dog extends Animal {
String breed;

public Dog(String name, int age, String breed) {


super(name, age);
this.breed = breed;
}

public void displayDetails() {


System.out.println("Dog Details: Name - " + name + ", Age - " + age + ", Breed - " + breed);
}
}

// Subclass Cat
class Cat extends Animal {
String color;
Inheritance

public Cat(String name, int age, String color) {


super(name, age);
this.color = color;
}

public void displayDetails() {


System.out.println("Cat Details: Name - " + name + ", Age - " + age + ", Color - " + color);
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog("Buddy", 3, "Golden Retriever");
dog.displayDetails();
Cat cat = new Cat("Whiskers", 2, "White");
cat.displayDetails();
}
}

Output: Dog Details: Name - Buddy, Age - 3, Breed - Golden Retriever

Cat Details: Name - Whiskers, Age - 2, Color – White

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;

public Employee(String name, int id, double salary) {

this.name = name;

this.id = id;

this.salary = salary;

class Manager extends Employee {


Inheritance

String department;

String designation;

public Manager(String name, int id, double salary, String department, String designation) {

super(name, id, salary);

this.department = department;

this.designation = designation;

public void displayDetails() {

System.out.println("Manager Details: Name - " + name + ", ID - " + id + ", Salary - " + salary + ",
Department - " + department + ", Designation - " + designation);

public class Main {

public static void main(String[] args) {

Manager manager = new Manager("Alice", 101, 90000, "HR", "Senior Manager");

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.

public class Main {

public static void main(String[] args) {

Employee employee = new Employee("John", 102, 50000);

System.out.println("Employee Details: Name - " + employee.name + ", ID - " + employee.id + ",


Salary - " + employee.salary);
Inheritance

Manager manager = new Manager("Alice", 101, 90000, "HR", "Senior Manager");

manager.displayDetails();

Output: Employee Details: Name - John, ID - 102, Salary - 50000.0

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;

public Person(String name, int age) {

this.name = name;

this.age = age;

class Student extends Person {

int rollNumber;

public Student(String name, int age, int rollNumber) {

super(name, age);

this.rollNumber = rollNumber;

public void displayDetails() {


Inheritance

System.out.println("Student Details: Name - " + name + ", Age - " + age + ", Roll Number - " +
rollNumber);

class Teacher extends Person {

String subject;

public Teacher(String name, int age, String subject) {

super(name, age);

this.subject = subject;

public void displayDetails() {

System.out.println("Teacher Details: Name - " + name + ", Age - " + age + ", Subject - " + subject);

public class Main {

public static void main(String[] args) {

Student student = new Student("Tom", 20, 101);

student.displayDetails();

Teacher teacher = new Teacher("Dr. Smith", 45, "Mathematics");

teacher.displayDetails();

Output: Student Details: Name - Tom, Age - 20, Roll Number - 101

Teacher Details: Name - Dr. Smith, Age - 45, Subject – Mathematics


Inheritance

10. Write a program to demonstrate inheritance by creating objects of derived classes and accessing
properties.

public class Main {

public static void main(String[] args) {

Student student = new Student("Alice", 18, 102);

student.displayDetails();

Teacher teacher = new Teacher("Mr. Brown", 40, "History");

teacher.displayDetails();

Output: Student Details: Name - Alice, Age - 18, Roll Number - 102

Teacher Details: Name - Mr. Brown, Age - 40, Subject – History

11. Create a base class "BankAccount" with properties (account number, balance) and subclasses
"SavingsAccount" and "CurrentAccount".

class BankAccount {

String accountNumber;

double balance;

public BankAccount(String accountNumber, double balance) {

this.accountNumber = accountNumber;

this.balance = balance;

class SavingsAccount extends BankAccount {

double interestRate;

public SavingsAccount(String accountNumber, double balance, double interestRate) {

super(accountNumber, balance);
Inheritance

this.interestRate = interestRate;

public void displayDetails() {

System.out.println("Savings Account - Account Number: " + accountNumber + ", Balance: " +


balance + ", Interest Rate: " + interestRate);

class CurrentAccount extends BankAccount {

double overdraftLimit;

public CurrentAccount(String accountNumber, double balance, double overdraftLimit) {

super(accountNumber, balance);

this.overdraftLimit = overdraftLimit;

public void displayDetails() {

System.out.println("Current Account - Account Number: " + accountNumber + ", Balance: " +


balance + ", Overdraft Limit: " + overdraftLimit);

public class Main {

public static void main(String[] args) {

SavingsAccount savings = new SavingsAccount("SA123", 10000, 0.04);

savings.displayDetails();

CurrentAccount current = new CurrentAccount("CA456", 5000, 2000);

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.

public class Main {

public static void main(String[] args) {

SavingsAccount savings = new SavingsAccount("SA789", 12000, 0.03);

savings.displayDetails();

CurrentAccount current = new CurrentAccount("CA321", 8000, 3000);

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;

public Shape(String type, String color) {

this.type = type;

this.color = color;

class Triangle extends Shape {


Inheritance

double base;

double height;

public Triangle(String type, String color, double base, double height) {

super(type, color);

this.base = base;

this.height = height;

public void displayDetails() {

System.out.println("Triangle Details: Type - " + type + ", Color - " + color + ", Base - " + base + ",
Height - " + height);

public class Main {

public static void main(String[] args) {

Triangle triangle = new Triangle("Equilateral", "Red", 5, 8);

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.

public class Main {

public static void main(String[] args) {

Shape shape = new Shape("Polygon", "Blue");

Triangle triangle = new Triangle("Isosceles", "Green", 6, 10);

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;

public Vehicle(String make, String model, int year) {

this.make = make;

this.model = model;

this.year = year;

class Truck extends Vehicle {

double capacity;

double mileage;

public Truck(String make, String model, int year, double capacity, double mileage) {

super(make, model, year);

this.capacity = capacity;

this.mileage = mileage;

public void displayDetails() {


Inheritance

System.out.println("Truck Details: Make - " + make + ", Model - " + model + ", Year - " + year + ",
Capacity - " + capacity + ", Mileage - " + mileage);

public class Main {

public static void main(String[] args) {

Truck truck = new Truck("Ford", "F150", 2022, 1.5, 12);

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.

public class Main {

public static void main(String[] args) {

Truck truck = new Truck("Chevrolet", "Silverado", 2023, 2.0, 10);

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;

public Fruit(String name, String color) {

this.name = name;

this.color = color;
Inheritance

class Apple extends Fruit {

String taste;

double size;

public Apple(String name, String color, String taste, double size) {

super(name, color);

this.taste = taste;

this.size = size;

public void displayDetails() {

System.out.println("Apple Details: Name - " + name + ", Color - " + color + ", Taste - " + taste + ", Size
- " + size);

class Banana extends Fruit {

String taste;

double size;

public Banana(String name, String color, String taste, double size) {

super(name, color);

this.taste = taste;

this.size = size;

}
Inheritance

public void displayDetails() {

System.out.println("Banana Details: Name - " + name + ", Color - " + color + ", Taste - " + taste + ",
Size - " + size);

public class Main {

public static void main(String[] args) {

Apple apple = new Apple("Apple", "Red", "Sweet", 4.5);

apple.displayDetails();

Banana banana = new Banana("Banana", "Yellow", "Sweet", 6.0);

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.

public class Main {

public static void main(String[] args) {

Apple apple = new Apple("Apple", "Green", "Sour", 5.0);

apple.displayDetails();

Banana banana = new Banana("Banana", "Yellow", "Sweet", 7.0);

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;

public Animal(String name, String type) {

this.name = name;

this.type = type;

class Dog extends Animal {

String breed;

String color;

public Dog(String name, String type, String breed, String color) {

super(name, type);

this.breed = breed;

this.color = color;

public void displayDetails() {

System.out.println("Dog Details: Name - " + name + ", Type - " + type + ", Breed - " + breed + ", Color
- " + color);

}
Inheritance

class Cat extends Animal {

String breed;

String color;

public Cat(String name, String type, String breed, String color) {

super(name, type);

this.breed = breed;

this.color = color;

public void displayDetails() {

System.out.println("Cat Details: Name - " + name + ", Type - " + type + ", Breed - " + breed + ", Color
- " + color);

public class Main {

public static void main(String[] args) {

Dog dog = new Dog("Buddy", "Mammal", "Golden Retriever", "Golden");

dog.displayDetails();

Cat cat = new Cat("Whiskers", "Mammal", "Persian", "White");

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

public class Main {

public static void main(String[] args) {

Dog dog = new Dog("Rex", "Mammal", "Bulldog", "Brown");

dog.displayDetails();

Cat cat = new Cat("Luna", "Mammal", "Siamese", "Grey");

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;

public Person(String name, int age) {

this.name = name;

this.age = age;

class Employee extends Person {

int id;

double salary;

public Employee(String name, int age, int id, double salary) {

super(name, age);
Inheritance

this.id = id;

this.salary = salary;

public void displayDetails() {

System.out.println("Employee Details: Name - " + name + ", Age - " + age + ", ID - " + id + ", Salary - "
+ salary);

public class Main {

public static void main(String[] args) {

Employee employee = new Employee("Alice", 30, 101, 50000);

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.

public class Main {

public static void main(String[] args) {

Person person = new Person("John", 25);

System.out.println("Person Details: Name - " + person.name + ", Age - " + person.age);

Employee employee = new Employee("Jane", 28, 102, 60000);

employee.displayDetails();

Output: Person Details: Name - John, Age - 25


Inheritance

Employee Details: Name - Jane, Age - 28, ID - 102, Salary - 60000.0

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;

public Shape(String type, String color) {

this.type = type;

this.color = color;

class Rectangle extends Shape {

double length;

double width;

public Rectangle(String type, String color, double length, double width) {

super(type, color);

this.length = length;

this.width = width;

public void displayDetails() {

System.out.println("Rectangle Details: Type - " + type + ", Color - " + color + ", Length - " + length + ",
Width - " + width);

}
Inheritance

public class Main {

public static void main(String[] args) {

Rectangle rectangle = new Rectangle("Quadrilateral", "Blue", 4, 6);

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.

public class Main {

public static void main(String[] args) {

Shape shape = new Shape("Polygon", "Green");

Rectangle rectangle = new Rectangle("Rectangle", "Red", 5, 8);

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;

public Vehicle(String make, String model, int year) {

this.make = make;

this.model = model;

this.year = year;

}
Inheritance

class Car extends Vehicle {

String color;

double mileage;

public Car(String make, String model, int year, String color, double mileage) {

super(make, model, year);

this.color = color;

this.mileage = mileage;

public void displayDetails() {

System.out.println("Car Details: Make - " + make + ", Model - " + model + ", Year - " + year + ", Color -
" + color + ", Mileage - " + mileage);

public class Main {

public static void main(String[] args) {

Car car = new Car("Toyota", "Camry", 2021, "Black", 30.5);

car.displayDetails();

Output: Car Details: Make - Toyota, Model - Camry, Year - 2021, Color - Black, Mileage - 30.5
Exception Handling

1. Write a program to handle ArrayIndexOutOfBoundsException


public class ArrayIndexOutOfBoundsExample {
public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 50; // Index out of bounds
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught: " + e);
}
}
}
Output: Exception caught: java.lang.ArrayIndexOutOfBoundsException: Index 10 out of
bounds for length 5
2. Implement a program to handle ArithmeticException (division by zero).
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.lang.ArithmeticException: / by zero

3. Write a program to handle NullPointerException.


public class NullPointerExceptionExample {
public static void main(String[] args) {
try {
String str = null;
str.length(); // Null pointer access
} catch (NullPointerException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.lang.NullPointerException

4. Implement a program to handle FileNotFoundException.


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

public class FileNotFoundExceptionExample {


Exception Handling

public static void main(String[] args) {


try {
File file = new File("nonexistentfile.txt");
Scanner scanner = new Scanner(file); // File not found
} catch (FileNotFoundException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.io.FileNotFoundException: nonexistentfile.txt (No such file or


directory)

5. Write a program to handle NumberFormatException.


public class NumberFormatExceptionExample {
public static void main(String[] args) {
try {
int num = Integer.parseInt("abc"); // Invalid number format
} catch (NumberFormatException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.lang.NumberFormatException: For input string: "abc"

6. Implement a program to handle IOException.


import java.io.IOException;

public class IOExceptionExample {


public static void main(String[] args) {
try {
throw new IOException("I/O exception occurred");
} catch (IOException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.io.IOException: I/O exception occurred

7. Write a program to handle ClassNotFoundException.


public class ClassNotFoundExceptionExample {
public static void main(String[] args) {
try {
Class.forName("NonExistentClass"); // Class not found
} catch (ClassNotFoundException e) {
Exception Handling

System.out.println("Exception caught: " + e);


}
}
}

Output: Exception caught: java.lang.ClassNotFoundException: NonExistentClass

8. Implement a program to handle StackOverflowError.


public class StackOverflowErrorExample {
public static void main(String[] args) {
try {
recursiveMethod();
} catch (StackOverflowError e) {
System.out.println("Error caught: " + e);
}
}

public static void recursiveMethod() {


recursiveMethod(); // Stack overflow
}
}

Output: Error caught: java.lang.StackOverflowError

9. Write a program to handle NegativeArraySizeException.


public class NegativeArraySizeExceptionExample {
public static void main(String[] args) {
try {
int[] arr = new int[-5]; // Negative array size
} catch (NegativeArraySizeException e) {
System.out.println("Exception caught: " + e);
}
}
}

Output: Exception caught: java.lang.NegativeArraySizeException

10. Implement a program to handle InterruptedException. public class InterruptedExceptionExample {

public static void main(String[] args) {

Thread thread = new Thread(() -> {

try {

Thread.sleep(1000); // Thread sleep

} catch (InterruptedException e) {

System.out.println("Exception caught: " + e);


Exception Handling

});

thread.start();

thread.interrupt(); // Interrupt the thread

Output: Exception caught: java.lang.InterruptedException: sleep interrupted

11.Write a program to handle ArrayStoreException.

public class ArrayStoreExceptionExample {

public static void main(String[] args) {

try {

Object[] arr = new Integer[5];

arr[0] = "String"; // Invalid type assignment

} catch (ArrayStoreException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.lang.ArrayStoreException: java.lang.String

12. Implement a program to handle IllegalStateException.

public class IllegalStateExceptionExample {

public static void main(String[] args) {

try {

throw new IllegalStateException("Illegal state encountered");

} catch (IllegalStateException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.lang.IllegalStateException: Illegal state encountered

13. Write a program to handle NoSuch Element Exception.

import java.util.*;

public class NoSuchElementExceptionExample {

public static void main(String[] args) {

try {

Scanner scanner = new Scanner(System.in);

scanner.nextLine(); // No input given

scanner.close();

} catch (NoSuchElementException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.util.NoSuchElementException

14. Implement a program to handle Unsupported OperationException.

import java.util.*;

public class UnsupportedOperationExceptionExample {

public static void main(String[] args) {

try {

List<String> list = Collections.emptyList();

list.add("Item"); // Unsupported operation

} catch (UnsupportedOperationException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.lang.UnsupportedOperationException

15. Write a program to handle Unsupported OperationException.

(same as above)

16. Implement a program to handle ConcurrentModificationException.

import java.util.*;

public class ConcurrentModificationExceptionExample {

public static void main(String[] args) {

try {

List<String> list = new ArrayList<>();

list.add("A");

list.add("B");

Iterator<String> iterator = list.iterator();

list.add("C"); // Modify list during iteration

iterator.next();

} catch (ConcurrentModificationException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.util.ConcurrentModificationException

17. Write a program to handle IllegalArgumentException.

public class IllegalArgumentExceptionExample {

public static void main(String[] args) {

try {

throw new IllegalArgumentException("Illegal argument");

} catch (IllegalArgumentException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.lang.IllegalArgumentException: Illegal argument

18. Implement a program to handle SecurityException.

public class SecurityExceptionExample {

public static void main(String[] args) {

try {

System.setSecurityManager(new SecurityManager());

System.exit(0); // Security exception thrown

} catch (SecurityException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.security.SecurityException: exit called from the security manager

19. Write a program to handle DateTimeParseException.

import java.time.LocalDate;

import java.time.format.DateTimeParseException;

public class DateTimeParseExceptionExample {

public static void main(String[] args) {

try {

LocalDate.parse("2025-01-32"); // Invalid date

} catch (DateTimeParseException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.time.format.DateTimeParseException: Text '2025-01-32' could not be


parsed at index 10

20. Implement a program to handle PatternSyntaxException.

import java.util.regex.*;

public class PatternSyntaxExceptionExample {

public static void main(String[] args) {

try {

Pattern.compile("["); // Invalid regular expression

} catch (PatternSyntaxException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.util.regex.PatternSyntaxException: Unclosed character class near index

21. Write a program to handle Missing ResourceException.

import java.util.*;

public class MissingResourceExceptionExample {

public static void main(String[] args) {

try {

ResourceBundle rb = ResourceBundle.getBundle("nonexistent");

} catch (MissingResourceException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.util.MissingResourceException: Can't find bundle for base name
nonexistent, locale en_US

22. Implement a program to handle Formatter ClosedException.

import java.util.*;

public class FormatterClosedExceptionExample {

public static void main(String[] args) {

try {

Formatter formatter = new Formatter();

formatter.close();

formatter.format("%s", "This will fail"); // Formatter closed

} catch (FormatterClosedException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.util.Formatter$FormatterClosedException

23. Write a program to handle Buffer OverflowException.

import java.nio.*;

public class BufferOverflowExceptionExample {

public static void main(String[] args) {

try {

ByteBuffer buffer = ByteBuffer.allocate(5);

buffer.put(new byte[10]); // Buffer overflow

} catch (BufferOverflowException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.nio.BufferOverflowException

24. Implement a program to handle Buffer UnderflowException.

import java.nio.*;

public class BufferUnderflowExceptionExample {

public static void main(String[] args) {

try {

ByteBuffer buffer = ByteBuffer.allocate(5);

buffer.get(new byte[10]); // Buffer underflow

} catch (BufferUnderflowException e) {

System.out.println("Exception caught: " + e);

Output: Exception caught: java.nio.BufferUnderflowException

25. Write a program to handle DateTimeException.

import java.time.*;

public class DateTimeExceptionExample {

public static void main(String[] args) {

try {

LocalTime time = LocalTime.of(25, 0); // Invalid hour

} catch (DateTimeException e) {

System.out.println("Exception caught: " + e);

}
Exception Handling

Output: Exception caught: java.time.DateTimeException: Invalid value for HourOfDay (valid values 0 -
23): 25
Collection:

1. Demonstrate ArrayList by adding, removing, and iterating over elements:


import java.util.ArrayList;

public class ArrayListDemo {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();

// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Cherry");

// Iterating over elements


System.out.println("ArrayList:");
for (String fruit : list) {
System.out.println(fruit);
}

// Removing elements
list.remove("Banana");

// Iterating after removal


System.out.println("\nAfter removal:");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
Output: ArrayList:
Apple
Banana
Cherry

After removal:
Apple
Cherry
//2. Demonstrate LinkedList by adding, removing, and iterating over elements:
import java.util.LinkedList;

public class LinkedListDemo {


public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();

// Adding elements
Collection:

list.add("Apple");
list.add("Banana");
list.add("Cherry");

// Iterating over elements


System.out.println("LinkedList:");
for (String fruit : list) {
System.out.println(fruit);
}

// Removing elements
list.remove("Banana");

// Iterating after removal


System.out.println("\nAfter removal:");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
Output: LinkedList:
Apple
Banana
Cherry

After removal:
Apple
Cherry
//3. Demonstrate HashSet by adding, removing, and iterating over elements:
import java.util.HashSet;

public class HashSetDemo {


public static void main(String[] args) {
HashSet<String> set = new HashSet<>();

// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");

// Iterating over elements


System.out.println("HashSet:");
for (String fruit : set) {
System.out.println(fruit);
Collection:

// Removing elements
set.remove("Banana");

// Iterating after removal


System.out.println("\nAfter removal:");
for (String fruit : set) {
System.out.println(fruit);
}
}
}
Output: HashSet:
Apple
Banana
Cherry

After removal:
Apple
Cherry
//4. Demonstrate TreeSet by adding, removing, and iterating over elements:
import java.util.TreeSet;

public class TreeSetDemo {


public static void main(String[] args) {
TreeSet<String> set = new TreeSet<>();

// Adding elements
set.add("Apple");
set.add("Banana");
set.add("Cherry");

// Iterating over elements


System.out.println("TreeSet:");
for (String fruit : set) {
System.out.println(fruit);
}

// Removing elements
set.remove("Banana");

// Iterating after removal


System.out.println("\nAfter removal:");
for (String fruit : set) {
Collection:

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;

public class HashMapDemo {


public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();

// Adding key-value pairs


map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");

// 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;

public class TreeMapDemo {


public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();

// Adding key-value pairs


map.put(1, "Apple");
map.put(2, "Banana");
Collection:

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;

public class LinkedHashMapDemo {


public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();

// Adding key-value pairs


map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");

// 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;

public class QueueDemo {


public static void main(String[] args) {
Queue<String> queue = new LinkedList<>();
Collection:

// Adding elements
queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");

// Iterating over elements


System.out.println("Queue:");
for (String fruit : queue) {
System.out.println(fruit);
}

// Removing elements
queue.poll();

// Iterating after removal


System.out.println("\nAfter removal:");
for (String fruit : queue) {
System.out.println(fruit);
}
}
}
Output: Queue:
Apple
Banana
Cherry

After removal:
Banana
Cherry
//9. Demonstrate PriorityQueue by adding, removing, and iterating over elements:
import java.util.PriorityQueue;

public class PriorityQueueDemo {


public static void main(String[] args) {
PriorityQueue<String> queue = new PriorityQueue<>();

// Adding elements
queue.add("Apple");
queue.add("Banana");
queue.add("Cherry");

// Iterating over elements


System.out.println("PriorityQueue:");
while (!queue.isEmpty()) {
Collection:

System.out.println(queue.poll()); // Removing and printing elements in priority order


}
}
}
Output: PriorityQueue:
Apple
Banana
Cherry
//10. Demonstrate Stack by adding, removing, and iterating over elements:
import java.util.Stack;

public class StackDemo {


public static void main(String[] args) {
Stack<String> stack = new Stack<>();

// Adding elements
stack.push("Apple");
stack.push("Banana");
stack.push("Cherry");

// Iterating over elements


System.out.println("Stack:");
while (!stack.isEmpty()) {
System.out.println(stack.pop()); // Removing and printing elements in LIFO order
}
}
}
Output: Stack:
Cherry
Banana
Apple
//11. Demonstrate ArrayDeque by adding, removing, and iterating over elements:
import java.util.ArrayDeque;

public class ArrayDequeDemo {


public static void main(String[] args) {
ArrayDeque<String> deque = new ArrayDeque<>();

// Adding elements
deque.add("Apple");
deque.add("Banana");
deque.add("Cherry");

// Iterating over elements


Collection:

System.out.println("ArrayDeque:");
for (String fruit : deque) {
System.out.println(fruit);
}

// Removing elements
deque.removeFirst();

// Iterating after removal


System.out.println("\nAfter removal:");
for (String fruit : deque) {
System.out.println(fruit);
}
}
}
Output: ArrayDeque:
Apple
Banana
Cherry
After removal:
Banana
Cherry
//12. Demonstrate EnumSet by adding, removing, and iterating over elements:
import java.util.EnumSet;

enum Fruit { APPLE, BANANA, CHERRY }

public class EnumSetDemo {


public static void main(String[] args) {
EnumSet<Fruit> set = EnumSet.of(Fruit.APPLE, Fruit.BANANA);

// Iterating over elements


System.out.println("EnumSet:");
for (Fruit fruit : set) {
System.out.println(fruit);
}

// Adding an element
set.add(Fruit.CHERRY);

// Iterating after adding


System.out.println("\nAfter adding CHERRY:");
for (Fruit fruit : set) {
System.out.println(fruit);
Collection:

// Removing an element
set.remove(Fruit.BANANA);

// Iterating after removal


System.out.println("\nAfter removing BANANA:");
for (Fruit fruit : set) {
System.out.println(fruit);
}
}
}
Output: EnumSet:
APPLE
BANANA
After adding CHERRY:
APPLE
BANANA
CHERRY
After removing BANANA:
APPLE
CHERRY
//13. Demonstrate BitSet by adding, removing, and iterating over elements:
import java.util.BitSet;

public class BitSetDemo {


public static void main(String[] args) {
BitSet bitSet = new BitSet();

// Adding elements
bitSet.set(0);
bitSet.set(2);
bitSet.set(4);

// Iterating over elements


System.out.println("BitSet:");
for (int i = 0; i < bitSet.length(); i++) {
if (bitSet.get(i)) {
System.out.println("Bit " + i + " is set");
}
}

// Removing an element
bitSet.clear(2);
Collection:

// Iterating after removal


System.out.println("\nAfter removal:");
for (int i = 0; i < bitSet.length(); i++) {
if (bitSet.get(i)) {
System.out.println("Bit " + i + " is set");
}
}
}
}
Output: BitSet:
Bit 0 is set
Bit 2 is set
Bit 4 is set
After removal:
Bit 0 is set
Bit 4 is set
//14. Demonstrate Hashtable by adding and retrieving key-value pairs:
import java.util.Hashtable;

public class HashtableDemo {


public static void main(String[] args) {
Hashtable<Integer, String> table = new Hashtable<>();

// Adding key-value pairs


table.put(1, "Apple");
table.put(2, "Banana");
table.put(3, "Cherry");
//Retrieving

output: Hashtable:
Key 1: Apple
Key 2: Banana
Key 3: Cherry
//15. Multiple thread and use Executors framework
import java.util.Properties;

public class PropertiesDemo {


public static void main(String[] args) {
// Creating a Properties object
Properties properties = new Properties();

// Adding key-value pairs to Properties


properties.setProperty("username", "john_doe");
Collection:

properties.setProperty("password", "12345");
properties.setProperty("email", "[email protected]");

// Retrieving values using keys


String username = properties.getProperty("username");
String password = properties.getProperty("password");
String email = properties.getProperty("email");

// Displaying the properties


System.out.println("Username: " + username);
System.out.println("Password: " + password);
System.out.println("Email: " + email);
}
}
Output: Username: john_doe
Password: 12345
Email: [email protected]
//16. Implement a program to demonstrate Vector by adding, removing, and iterating over
elements.
import java.util.Vector;

public class VectorDemo {


public static void main(String[] args) {
// Creating a Vector
Vector<String> vector = new Vector<>();

// Adding elements to the Vector


vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");

// Displaying elements
System.out.println("Original Vector: " + vector);

// Removing an element from the Vector


vector.remove("Banana");

// Displaying Vector after removal


System.out.println("After removing Banana: " + vector);

// Iterating over elements using for-each loop


System.out.println("Iterating over Vector:");
for (String item : vector) {
System.out.println(item);
Collection:

}
}
}
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;

public class EnumerationDemo {


public static void main(String[] args) {
// Creating a Vector
Vector<String> vector = new Vector<>();
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");

// Creating an Enumeration for the Vector


Enumeration<String> enumeration = vector.elements();

// Iterating over elements using Enumeration


System.out.println("Iterating over Vector using Enumeration:");
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}
}
}
Output: Iterating over Vector using Enumeration:
Apple
Banana
Cherry
//18. Implement a program to demonstrate Listiterator by iterating over elements of a list.
import java.util.ArrayList;
import java.util.ListIterator;

public class ListIteratorDemo {


public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
Collection:

list.add("Cherry");

// Creating a ListIterator
ListIterator<String> listIterator = list.listIterator();

// Iterating forward using ListIterator


System.out.println("Iterating forward:");
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}

// Iterating backward using ListIterator


System.out.println("Iterating backward:");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}
Output: Iterating forward:
Apple
Banana
Cherry
Iterating backward:
Cherry
Banana
Apple
//19. Write a program to demonstrate Iterator by iterating over elements of a collection
import java.util.ArrayList;
import java.util.Iterator;

public class IteratorDemo {


public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");

// Creating an Iterator for the ArrayList


Iterator<String> iterator = list.iterator();

// Iterating over elements using Iterator


System.out.println("Iterating over ArrayList using Iterator:");
while (iterator.hasNext()) {
Collection:

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;

public class ArrayBlockingQueueDemo {


public static void main(String[] args) {
// Creating an ArrayBlockingQueue with capacity 3
ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(3);

// Adding elements to the queue


try {
queue.put("Apple");
queue.put("Banana");
queue.put("Cherry");

System.out.println("Queue after adding elements: " + queue);

// Removing elements from the queue


String removedElement = queue.take();
System.out.println("Removed Element: " + removedElement);

System.out.println("Queue after removal: " + queue);

// Iterating over elements in the queue


System.out.println("Iterating over Queue:");
for (String item : queue) {
System.out.println(item);
}
} 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]
Collection:

Iterating over Queue:


Banana
Cherry
//21. Write a program to demonstrate LinkedBlockingQueue by adding, removing, and iterating
over elements.
import java.util.concurrent.LinkedBlockingQueue;

public class LinkedBlockingQueueDemo {


public static void main(String[] args) {
// Creating a LinkedBlockingQueue
LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();

try {
// Adding elements to the queue
queue.put("Apple");
queue.put("Banana");
queue.put("Cherry");

// Displaying the queue after adding elements


System.out.println("Queue after adding elements: " + queue);

// Removing an element from the queue


String removedElement = queue.take();
System.out.println("Removed Element: " + removedElement);

// Displaying the queue after removal


System.out.println("Queue after removal: " + queue);

// Iterating over elements in the queue


System.out.println("Iterating over Queue:");
for (String item : queue) {
System.out.println(item);
}

} 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;

public class PriorityBlockingQueueDemo {


public static void main(String[] args) {
// Creating a PriorityBlockingQueue with natural ordering
PriorityBlockingQueue<String> queue = new PriorityBlockingQueue<>();

// Adding elements to the queue


queue.put("Apple");
queue.put("Banana");
queue.put("Cherry");

// Displaying the queue


System.out.println("Queue after adding elements: " + queue);

// Removing elements from the queue (elements will be removed in priority order)
try {
String removedElement = queue.take();
System.out.println("Removed Element: " + removedElement);

// Displaying the queue after removal


System.out.println("Queue after removal: " + queue);

// Iterating over elements in the queue


System.out.println("Iterating over Queue:");
for (String item : queue) {
System.out.println(item);
}
} 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
Cherry
//23. Write a program to demonstrate Synchronous Queue by adding and removing elements.
import java.util.concurrent.SynchronousQueue;
Collection:

public class SynchronousQueueDemo {


public static void main(String[] args) {
// Creating a SynchronousQueue
SynchronousQueue<String> queue = new SynchronousQueue<>();

// Thread to add an element to the queue


Thread producer = new Thread(() -> {
try {
System.out.println("Producer: Adding element...");
queue.put("Apple");
System.out.println("Producer: Element added");
} catch (InterruptedException e) {
System.out.println("Producer interrupted");
}
});

// Thread to remove an element from the queue


Thread consumer = new Thread(() -> {
try {
System.out.println("Consumer: Waiting to take element...");
String item = queue.take();
System.out.println("Consumer: Element taken: " + item);
} catch (InterruptedException e) {
System.out.println("Consumer interrupted");
}
});

// Start the threads


consumer.start();
producer.start();

// Wait for the threads to finish


try {
producer.join();
consumer.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
Output: Consumer: Waiting to take element...
Producer: Adding element...
Producer: Element added
Collection:

Consumer: Element taken: Apple


//24. Implement a program to demonstrate DelayQueue by adding and retrieving elements.
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

class DelayedElement implements Delayed {


private String name;
private long delayTime;
private long expiryTime;

public DelayedElement(String name, long delayTime) {


this.name = name;
this.delayTime = delayTime;
this.expiryTime = System.currentTimeMillis() + delayTime;
}

@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;
}

public String getName() {


return name;
}
}

public class DelayQueueDemo {


public static void main(String[] args) throws InterruptedException {
// Creating a DelayQueue
DelayQueue<DelayedElement> queue = new DelayQueue<>();
Collection:

// Adding delayed elements to the queue


queue.put(new DelayedElement("Apple", 3000));
queue.put(new DelayedElement("Banana", 5000));
queue.put(new DelayedElement("Cherry", 1000));

// Retrieving elements from the queue


while (!queue.isEmpty()) {
DelayedElement element = queue.take(); // takes the element when delay expires
System.out.println("Retrieved element: " + element.getName());
}
}
}
Output: Retrieved element: Cherry
Retrieved element: Apple
Retrieved element: Banana
//25. Write a program to demonstrate ConcurrentLinkedQueue by adding, removing, and
iterating over elements.
import java.util.concurrent.ConcurrentLinkedQueue;

public class ConcurrentLinkedQueueDemo {


public static void main(String[] args) {
// Creating a ConcurrentLinkedQueue
ConcurrentLinkedQueue<String> queue = new ConcurrentLinkedQueue<>();

// Adding elements to the queue


queue.offer("Apple");
queue.offer("Banana");
queue.offer("Cherry");

// Displaying the queue after adding elements


System.out.println("Queue after adding elements: " + queue);

// Removing an element from the queue


String removedElement = queue.poll();
System.out.println("Removed Element: " + removedElement);

// Displaying the queue after removal


System.out.println("Queue after removal: " + queue);

// Iterating over elements in the queue


System.out.println("Iterating over Queue:");
for (String item : queue) {
System.out.println(item);
}
Collection:

}
}
Output: Queue after adding elements: [Apple, Banana, Cherry]
Removed Element: Apple
Queue after removal: [Banana, Cherry]
Iterating over Queue:
Banana
Cherry

You might also like