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

Java@Programs

Uploaded by

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

Java@Programs

Uploaded by

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

Java@Programs

This is a copy of a conversation between ChatGPT & Anonymous.

Here is a categorized list of 150+ Java programs ranging from basic to intermediate levels:

1. Basics of Java Programming

1. Print "Hello, World!"


2. Add two numbers
3. Check if a number is even or odd
4. Find the maximum of three numbers
5. Swap two numbers without using a third variable
6. Find the ASCII value of a character
7. Check if a number is positive, negative, or zero
8. Multiply two floating-point numbers
9. Convert Fahrenheit to Celsius
10. Print the sum of n natural numbers

2. Control Statements

11. Check if a number is prime


12. Print all prime numbers in a range
13. Check if a number is a palindrome
14. Check if a number is an Armstrong number
15. Find the factorial of a number
16. Generate a multiplication table for a number
17. Count digits in a number
18. Reverse a number
19. Calculate the sum of digits of a number
20. Check if a year is a leap year

3. Loops

21. Print Fibonacci series up to n terms


22. Print patterns (e.g., pyramid, reverse pyramid)
23. Calculate the power of a number using a loop
24. Print all factors of a number
25. Print the sum of even and odd numbers in a range
26. Find GCD of two numbers
27. Find LCM of two numbers
28. Print the first n prime numbers

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/250
29. Check if a number is perfect
30. Calculate the sum of squares of first n natural numbers

4. Arrays

31. Find the largest and smallest elements in an array


32. Sort an array using bubble sort
33. Find the second largest element in an array
34. Search for an element in an array
35. Count occurrences of an element in an array
36. Merge two arrays
37. Find duplicates in an array
38. Reverse an array
39. Find the sum of array elements
40. Remove duplicate elements from an array

5. Strings

41. Check if a string is a palindrome


42. Count vowels and consonants in a string
43. Reverse a string without using built-in methods
44. Check if two strings are anagrams
45. Find the length of a string
46. Convert a string to uppercase and lowercase
47. Replace characters in a string
48. Count the number of words in a string
49. Extract a substring from a string
50. Sort an array of strings

6. Object-Oriented Programming

51. Create a class and an object


52. Implement a parameterized constructor
53. Demonstrate method overloading
54. Demonstrate inheritance with method overriding
55. Implement a simple calculator using classes and objects
56. Create a class to represent a bank account
57. Demonstrate the use of static variables and methods
58. Create a program using abstract classes
59. Implement multiple inheritance using interfaces
60. Create and use inner classes

7. Exception Handling

61. Handle divide-by-zero exception


Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/250
62. Handle array index out-of-bound exception
63. Use multiple catch blocks
64. Demonstrate the use of the `finally` block
65. Throw and catch a custom exception
66. Handle `NumberFormatException`
67. Handle `NullPointerException`
68. Write a program with nested try-catch blocks
69. Demonstrate the `throws` keyword
70. Create a program with a custom checked exception

8. File Handling

71. Read data from a file


72. Write data to a file
73. Append data to a file
74. Count the number of lines in a file
75. Copy the contents of one file to another
76. Delete a file
77. Find a word in a file
78. Serialize and deserialize an object
79. Demonstrate RandomAccessFile class
80. Read a file using BufferedReader

9. Collections

81. Create and use an ArrayList


82. Demonstrate the use of HashMap
83. Implement a stack using Java Collections
84. Create and use a LinkedList
85. Implement a queue using Java Collections
86. Sort a list using Collections.sort()
87. Use a TreeMap to store data
88. Find the frequency of elements in a list
89. Iterate over a HashSet
90. Create a priority queue

10. Recursion

91. Find the factorial of a number using recursion


92. Print Fibonacci series using recursion
93. Reverse a string using recursion
94. Find the GCD of two numbers using recursion
95. Solve the Tower of Hanoi problem
96. Check if a string is a palindrome using recursion
97. Calculate the sum of digits of a number using recursion

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/250
98. Generate permutations of a string
99. Solve a maze using recursion
100. Count subsets with a given sum using recursion

11. Searching and Sorting

101. Implement binary search


102. Implement linear search
103. Implement selection sort
104. Implement insertion sort
105. Implement quicksort
106. Implement mergesort
107. Implement heap sort
108. Find the k-th smallest element in an array
109. Find the missing number in an array
110. Sort an array of 0s, 1s, and 2s

12. Advanced Topics

111. Implement a simple multithreading program


112. Demonstrate synchronization in multithreading
113. Implement producer-consumer problem
114. Demonstrate inter-thread communication
115. Create a program using lambda expressions
116. Demonstrate the use of Stream API
117. Perform matrix addition
118. Perform matrix multiplication
119. Create a simple game (e.g., tic-tac-toe)
120. Implement a simple chat application using sockets

13. Miscellaneous

121. Convert decimal to binary


122. Convert binary to decimal
123. Check if a number is a power of 2
124. Generate random numbers
125. Demonstrate the use of enum
126. Find the frequency of characters in a string
127. Implement a stopwatch program
128. Solve N-Queens problem
129. Demonstrate the use of Java Reflection API
130. Create a basic calculator GUI using Swing

14. Real-World Scenarios

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/250
131. Create a login system
132. Implement a student management system
133. Create a library management system
134. Develop a simple billing system
135. Create a basic e-commerce system
136. Develop a simple ticket booking system
137. Create a personal expense tracker
138. Implement a weather app (fetch data using APIs)
139. Create a contact management system
140. Build a basic blogging application

15. Debugging and Optimization

141. Debug a program with logical errors


142. Optimize a sorting algorithm
143. Identify and fix memory leaks
144. Analyze time complexity of an algorithm
145. Create unit tests using JUnit
146. Write a program with command-line arguments
147. Implement lazy initialization
148. Demonstrate the use of the Singleton design pattern
149. Use the Factory design pattern
150. Demonstrate dependency injection

Let me know which specific topics or programs you'd like detailed explanations or examples for!

Here are Java programs for basic topics:

1. Print "Hello, World!"

java

public class HelloWorld {


public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

2. Add Two Numbers

java

import java.util.Scanner;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/250
public class AddTwoNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
int sum = num1 + num2;
System.out.println("Sum: " + sum);
}
}

3. Check If a Number Is Even or Odd

java

import java.util.Scanner;

public class EvenOrOdd {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}

4. Find Maximum of Three Numbers

java

import java.util.Scanner;

public class MaxOfThree {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();

int max = Math.max(num1, Math.max(num2, num3));


System.out.println("Maximum: " + max);
}
}

5. Swap Two Numbers Without Using a Third Variable

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/250
java

import java.util.Scanner;

public class SwapNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int a = scanner.nextInt();
System.out.print("Enter second number: ");
int b = scanner.nextInt();

System.out.println("Before Swap: a = " + a + ", b = " + b);


a = a + b;
b = a - b;
a = a - b;
System.out.println("After Swap: a = " + a + ", b = " + b);
}
}

6. Find the ASCII Value of a Character

java

import java.util.Scanner;

public class AsciiValue {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a character: ");
char ch = scanner.next().charAt(0);
int ascii = (int) ch;
System.out.println("ASCII value of '" + ch + "' is: " + ascii);
}
}

7. Check If a Number Is Positive, Negative, or Zero

java

import java.util.Scanner;

public class NumberCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

if (num > 0) {
System.out.println("The number is positive.");
} else if (num < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 7/250
}
}

8. Multiply Two Floating-Point Numbers

java

import java.util.Scanner;

public class MultiplyFloats {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first floating-point number: ");
float num1 = scanner.nextFloat();
System.out.print("Enter second floating-point number: ");
float num2 = scanner.nextFloat();

float result = num1 * num2;


System.out.println("Product: " + result);
}
}

9. Convert Fahrenheit to Celsius

java

import java.util.Scanner;

public class TemperatureConversion {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit: ");
double fahrenheit = scanner.nextDouble();

double celsius = (fahrenheit - 32) * 5 / 9;


System.out.println("Temperature in Celsius: " + celsius);
}
}

10. Print the Sum of n Natural Numbers

java

import java.util.Scanner;

public class SumOfNaturalNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();

int sum = n * (n + 1) / 2;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 8/250
System.out.println("Sum of first " + n + " natural numbers: " + sum);
}
}

These programs cover the basics of Java and help you understand input, output, control statements,
and simple operations. Let me know if you’d like further explanations or programs!

Here are the next set of basic Java programs:

11. Check if a Number Is Prime

java

import java.util.Scanner;

public class PrimeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

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

12. Print All Prime Numbers in a Range

java

import java.util.Scanner;

public class PrimeInRange {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the start of the range: ");
int start = scanner.nextInt();
System.out.print("Enter the end of the range: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/250
int end = scanner.nextInt();

for (int num = start; num <= end; num++) {


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.print(num + " ");
}
}
}
}

13. Check if a Number Is a Palindrome

java

import java.util.Scanner;

public class PalindromeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int original = num;
int reversed = 0;

while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

if (original == reversed) {
System.out.println(original + " is a palindrome.");
} else {
System.out.println(original + " is not a palindrome.");
}
}
}

14. Check if a Number Is an Armstrong Number

java

import java.util.Scanner;

public class ArmstrongCheck {


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 10/250
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int original = num;
int sum = 0;

while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, 3);
num /= 10;
}

if (original == sum) {
System.out.println(original + " is an Armstrong number.");
} else {
System.out.println(original + " is not an Armstrong number.");
}
}
}

15. Find the Factorial of a Number

java

import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
long factorial = 1;

for (int i = 1; i <= num; i++) {


factorial *= i;
}

System.out.println("Factorial of " + num + " is: " + factorial);


}
}

16. Generate a Multiplication Table for a Number

java

import java.util.Scanner;

public class MultiplicationTable {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

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


System.out.println(num + " x " + i + " = " + (num * i));
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/250
}
}

17. Count Digits in a Number

java

import java.util.Scanner;

public class CountDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int count = 0;

while (num != 0) {
num /= 10;
count++;
}

System.out.println("Number of digits: " + count);


}
}

18. Reverse a Number

java

import java.util.Scanner;

public class ReverseNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int reversed = 0;

while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

System.out.println("Reversed number: " + reversed);


}
}

19. Calculate the Sum of Digits of a Number

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/250
java

import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int sum = 0;

while (num != 0) {
int digit = num % 10;
sum += digit;
num /= 10;
}

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


}
}

20. Check if a Year Is a Leap Year

java

import java.util.Scanner;

public class LeapYearCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {


System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}

Let me know if you want programs for the next set or detailed explanations!

Here is the next set of basic Java programs:

21. Calculate Power of a Number

java

import java.util.Scanner;

public class PowerCalculation {


Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 13/250
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base: ");
int base = scanner.nextInt();
System.out.print("Enter the exponent: ");
int exponent = scanner.nextInt();

long result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}

System.out.println(base + "^" + exponent + " = " + result);


}
}

22. Find GCD of Two Numbers

java

import java.util.Scanner;

public class GCD {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();

while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}

System.out.println("GCD is: " + num1);


}
}

23. Find LCM of Two Numbers

java

import java.util.Scanner;

public class LCM {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();

int gcd = num1;


int temp = num2;

while (temp != 0) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 14/250
int remainder = gcd % temp;
gcd = temp;
temp = remainder;
}

int lcm = (num1 * num2) / gcd;


System.out.println("LCM is: " + lcm);
}
}

24. Print Fibonacci Series up to n Terms

java

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 n = scanner.nextInt();

int first = 0, second = 1;


System.out.print("Fibonacci Series: " + first + " " + second);

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


int next = first + second;
System.out.print(" " + next);
first = second;
second = next;
}
}
}

25. Find the Largest and Smallest Numbers in an Array

java

import java.util.Scanner;

public class MinMaxArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 15/250
System.out.println("Largest number: " + max);
System.out.println("Smallest number: " + min);
}
}

26. Count Vowels and Consonants in a String

java

import java.util.Scanner;

public class VowelConsonantCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine().toLowerCase();

int vowels = 0, consonants = 0;


for (char ch : str.toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
if ("aeiou".indexOf(ch) != -1) vowels++;
else consonants++;
}
}

System.out.println("Number of vowels: " + vowels);


System.out.println("Number of consonants: " + consonants);
}
}

27. Reverse a String

java

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


}
}

28. Check if a String Is a Palindrome

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/250
java

import java.util.Scanner;

public class PalindromeString {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

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

29. Sort an Array in Ascending Order

java

import java.util.Arrays;
import java.util.Scanner;

public class SortArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

Arrays.sort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
}

30. Calculate the Sum and Average of Elements in an Array

java

import java.util.Scanner;

public class ArraySumAverage {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int n = scanner.nextInt();
int[] arr = new int[n];

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 17/250
System.out.println("Enter the elements of the array: ");
int sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
sum += arr[i];
}

double average = (double) sum / n;


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

Let me know if you'd like to continue with more programs!

Here’s the next set of basic Java programs:

31. Find the Second Largest Element in an Array

java

import java.util.Scanner;

public class SecondLargest {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

int largest = Integer.MIN_VALUE;


int secondLargest = Integer.MIN_VALUE;

for (int num : arr) {


if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}

if (secondLargest == Integer.MIN_VALUE) {
System.out.println("No second largest element found.");
} else {
System.out.println("Second largest element: " + secondLargest);
}
}
}

32. Remove Duplicates from an Array


Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 18/250
java

import java.util.Arrays;
import java.util.Scanner;

public class RemoveDuplicates {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

Arrays.sort(arr);
System.out.print("Array after removing duplicates: ");

System.out.print(arr[0] + " ");


for (int i = 1; i < n; i++) {
if (arr[i] != arr[i - 1]) {
System.out.print(arr[i] + " ");
}
}
}
}

33. Count Occurrences of Each Element in an Array

java

import java.util.HashMap;
import java.util.Scanner;

public class ElementOccurrences {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

HashMap<Integer, Integer> occurrences = new HashMap<>();


for (int num : arr) {
occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
}

System.out.println("Occurrences of each element: ");


for (int key : occurrences.keySet()) {
System.out.println(key + " appears " + occurrences.get(key) + " times.");
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/250
34. Merge Two Arrays

java

import java.util.Scanner;

public class MergeArrays {


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

System.out.print("Enter the size of the first array: ");


int n1 = scanner.nextInt();
int[] arr1 = new int[n1];
System.out.println("Enter the elements of the first array: ");
for (int i = 0; i < n1; i++) {
arr1[i] = scanner.nextInt();
}

System.out.print("Enter the size of the second array: ");


int n2 = scanner.nextInt();
int[] arr2 = new int[n2];
System.out.println("Enter the elements of the second array: ");
for (int i = 0; i < n2; i++) {
arr2[i] = scanner.nextInt();
}

int[] merged = new int[n1 + n2];


System.arraycopy(arr1, 0, merged, 0, n1);
System.arraycopy(arr2, 0, merged, n1, n2);

System.out.println("Merged array: ");


for (int num : merged) {
System.out.print(num + " ");
}
}
}

35. Find the Transpose of a Matrix

java

import java.util.Scanner;

public class MatrixTranspose {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();

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


System.out.println("Enter the elements of the matrix: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}

System.out.println("Transpose of the matrix: ");


for (int j = 0; j < cols; j++) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 20/250
for (int i = 0; i < rows; i++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

36. Find the Sum of Rows and Columns in a Matrix

java

import java.util.Scanner;

public class MatrixSum {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
System.out.print("Enter the number of columns: ");
int cols = scanner.nextInt();

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


System.out.println("Enter the elements of the matrix: ");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = scanner.nextInt();
}
}

System.out.println("Sum of each row: ");


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

System.out.println("Sum of each column: ");


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

37. Check if a Number Is Perfect

java

import java.util.Scanner;

public class PerfectNumber {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 21/250
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int sum = 0;

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


if (num % i == 0) {
sum += i;
}
}

if (sum == num) {
System.out.println(num + " is a perfect number.");
} else {
System.out.println(num + " is not a perfect number.");
}
}
}

Let me know if you'd like to continue with more programs!

Here’s the next set of Java programs:

38. Find All Prime Numbers in a Given Range

java

import java.util.Scanner;

public class PrimeNumbersInRange {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the lower bound: ");
int low = scanner.nextInt();
System.out.print("Enter the upper bound: ");
int high = scanner.nextInt();

System.out.println("Prime numbers between " + low + " and " + high + ":");
for (int num = low; num <= high; num++) {
if (isPrime(num)) {
System.out.print(num + " ");
}
}
}

public static boolean isPrime(int num) {


if (num <= 1) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) return false;
}
return true;
}
}

39. Check if a Number Is an Armstrong Number

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/250
java

import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int originalNum = num;


int sum = 0;

while (num > 0) {


int digit = num % 10;
sum += Math.pow(digit, 3);
num /= 10;
}

if (sum == originalNum) {
System.out.println(originalNum + " is an Armstrong number.");
} else {
System.out.println(originalNum + " is not an Armstrong number.");
}
}
}

40. Check if a Number Is a Strong Number

java

import java.util.Scanner;

public class StrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int originalNum = num;


int sum = 0;

while (num > 0) {


int digit = num % 10;
sum += factorial(digit);
num /= 10;
}

if (sum == originalNum) {
System.out.println(originalNum + " is a strong number.");
} else {
System.out.println(originalNum + " is not a strong number.");
}
}

public static int factorial(int n) {


int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/250
}
}

41. Print Floyd's Triangle

java

import java.util.Scanner;

public class FloydsTriangle {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();

int num = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num + " ");
num++;
}
System.out.println();
}
}
}

42. Generate Pascal's Triangle

java

import java.util.Scanner;

public class PascalsTriangle {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();

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


for (int j = 0; j <= rows - i; j++) {
System.out.print(" ");
}
int num = 1;
for (int j = 0; j <= i; j++) {
System.out.print(num + " ");
num = num * (i - j) / (j + 1);
}
System.out.println();
}
}
}

43. Find the Sum of Digits of a Number

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/250
java

import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}

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


}
}

44. Reverse a Number

java

import java.util.Scanner;

public class ReverseNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int reversed = 0;
while (num > 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

System.out.println("Reversed number: " + reversed);


}
}

45. Check if a Number Is a Perfect Square

java

import java.util.Scanner;

public class PerfectSquare {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int sqrt = (int) Math.sqrt(num);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 25/250
if (sqrt * sqrt == num) {
System.out.println(num + " is a perfect square.");
} else {
System.out.println(num + " is not a perfect square.");
}
}
}

46. Calculate the Factorial of a Number Using Recursion

java

import java.util.Scanner;

public class FactorialRecursion {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

System.out.println("Factorial of " + num + " is: " + factorial(num));


}

public static int factorial(int n) {


if (n == 0) return 1;
return n * factorial(n - 1);
}
}

47. Check if a Number Is a Palindrome

java

import java.util.Scanner;

public class PalindromeNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int originalNum = num;


int reversed = 0;

while (num > 0) {


int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}

if (originalNum == reversed) {
System.out.println(originalNum + " is a palindrome.");
} else {
System.out.println(originalNum + " is not a palindrome.");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 26/250
}
}

Let me know if you'd like me to continue with more programs!

Here’s the next set of Java programs:

48. Count the Number of Vowels and Consonants in a String

java

import java.util.Scanner;

public class VowelConsonantCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

int vowels = 0, consonants = 0;


str = str.toLowerCase();

for (char ch : str.toCharArray()) {


if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}

System.out.println("Number of vowels: " + vowels);


System.out.println("Number of consonants: " + consonants);
}
}

49. Find the Largest and Smallest Elements in an Array

java

import java.util.Scanner;

public class LargestSmallestInArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 27/250
int largest = arr[0], smallest = arr[0];

for (int num : arr) {


if (num > largest) largest = num;
if (num < smallest) smallest = num;
}

System.out.println("Largest element: " + largest);


System.out.println("Smallest element: " + smallest);
}
}

50. Calculate the Power of a Number Using Recursion

java

import java.util.Scanner;

public class PowerRecursion {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base: ");
int base = scanner.nextInt();
System.out.print("Enter the exponent: ");
int exponent = scanner.nextInt();

System.out.println(base + "^" + exponent + " = " + power(base, exponent));


}

public static int power(int base, int exp) {


if (exp == 0) return 1;
return base * power(base, exp - 1);
}
}

51. Check if Two Strings Are Anagrams

java

import java.util.Arrays;
import java.util.Scanner;

public class AnagramCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine();

if (areAnagrams(str1, str2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 28/250
public static boolean areAnagrams(String str1, String str2) {
char[] arr1 = str1.replaceAll("\\s", "").toLowerCase().toCharArray();
char[] arr2 = str2.replaceAll("\\s", "").toLowerCase().toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return Arrays.equals(arr1, arr2);
}
}

52. Count Words in a String

java

import java.util.Scanner;

public class WordCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

String[] words = str.trim().split("\\s+");


System.out.println("Number of words: " + words.length);
}
}

53. Reverse Each Word in a String

java

import java.util.Scanner;

public class ReverseWords {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

String[] words = str.split(" ");


StringBuilder reversedString = new StringBuilder();

for (String word : words) {


StringBuilder reversedWord = new StringBuilder(word);
reversedString.append(reversedWord.reverse()).append(" ");
}

System.out.println("Reversed words: " + reversedString.toString().trim());


}
}

54. Check if a String Is a Palindrome

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 29/250
java

import java.util.Scanner;

public class PalindromeString {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

String reversed = new StringBuilder(str).reverse().toString();


if (str.equalsIgnoreCase(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}

55. Find the GCD of Two Numbers

java

import java.util.Scanner;

public class GCD {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();

System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd(num1, num
2));
}

public static int gcd(int a, int b) {


if (b == 0) return a;
return gcd(b, a % b);
}
}

56. Find the LCM of Two Numbers

java

import java.util.Scanner;

public class LCM {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 30/250
int lcm = (num1 * num2) / gcd(num1, num2);
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
}

public static int gcd(int a, int b) {


if (b == 0) return a;
return gcd(b, a % b);
}
}

Let me know if you'd like me to continue!

Here’s the next set of Java programs:

57. Convert Decimal to Binary

java

import java.util.Scanner;

public class DecimalToBinary {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();

String binary = Integer.toBinaryString(decimal);


System.out.println("Binary representation: " + binary);
}
}

58. Convert Binary to Decimal

java

import java.util.Scanner;

public class BinaryToDecimal {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a binary number: ");
String binary = scanner.nextLine();

int decimal = Integer.parseInt(binary, 2);


System.out.println("Decimal representation: " + decimal);
}
}

59. Convert Decimal to Octal


Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 31/250
java

import java.util.Scanner;

public class DecimalToOctal {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();

String octal = Integer.toOctalString(decimal);


System.out.println("Octal representation: " + octal);
}
}

60. Convert Octal to Decimal

java

import java.util.Scanner;

public class OctalToDecimal {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an octal number: ");
String octal = scanner.nextLine();

int decimal = Integer.parseInt(octal, 8);


System.out.println("Decimal representation: " + decimal);
}
}

61. Convert Decimal to Hexadecimal

java

import java.util.Scanner;

public class DecimalToHexadecimal {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int decimal = scanner.nextInt();

String hex = Integer.toHexString(decimal);


System.out.println("Hexadecimal representation: " + hex.toUpperCase());
}
}

62. Convert Hexadecimal to Decimal

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 32/250
java

import java.util.Scanner;

public class HexadecimalToDecimal {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a hexadecimal number: ");
String hex = scanner.nextLine();

int decimal = Integer.parseInt(hex, 16);


System.out.println("Decimal representation: " + decimal);
}
}

63. Print Fibonacci Series Using Recursion

java

import java.util.Scanner;

public class FibonacciRecursion {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int terms = scanner.nextInt();

System.out.println("Fibonacci series:");
for (int i = 0; i < terms; i++) {
System.out.print(fibonacci(i) + " ");
}
}

public static int fibonacci(int n) {


if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

64. Calculate Sum of Natural Numbers Using Recursion

java

import java.util.Scanner;

public class SumOfNaturalNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int sum = sumOfNaturalNumbers(num);


System.out.println("Sum of first " + num + " natural numbers is: " + sum);
}

public static int sumOfNaturalNumbers(int n) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 33/250
if (n == 1) return 1;
return n + sumOfNaturalNumbers(n - 1);
}
}

65. Calculate Factorial Using Iterative Method

java

import java.util.Scanner;

public class FactorialIterative {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}

System.out.println("Factorial of " + num + " is: " + factorial);


}
}

66. Reverse an Array

java

import java.util.Scanner;

public class ReverseArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

System.out.println("Reversed array:");
for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

67. Sort an Array Using Bubble Sort

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 34/250
java

import java.util.Scanner;

public class BubbleSort {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

for (int i = 0; i < n - 1; i++) {


for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}

Let me know if you'd like me to continue with more programs!

Here’s the next set of Java programs:

68. Check if an Array is Sorted

java

import java.util.Scanner;

public class ArraySortedCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

boolean isSorted = true;


for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 35/250
isSorted = false;
break;
}
}

if (isSorted) {
System.out.println("The array is sorted.");
} else {
System.out.println("The array is not sorted.");
}
}
}

69. Find the Second Largest Element in an Array

java

import java.util.Scanner;

public class SecondLargestElement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE;

for (int num : arr) {


if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}

if (secondLargest == Integer.MIN_VALUE) {
System.out.println("No second largest element found.");
} else {
System.out.println("The second largest element is: " + secondLargest);
}
}
}

70. Find the Maximum Sum of Subarray Using Kadane’s Algorithm

java

import java.util.Scanner;

public class MaximumSubarraySum {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 36/250
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

int maxSoFar = arr[0], maxEndingHere = arr[0];

for (int i = 1; i < n; i++) {


maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}

System.out.println("Maximum sum of subarray: " + maxSoFar);


}
}

71. Merge Two Sorted Arrays

java

import java.util.Arrays;

public class MergeSortedArrays {


public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
int[] mergedArray = 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]) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
}
}

while (i < arr1.length) {


mergedArray[k++] = arr1[i++];
}

while (j < arr2.length) {


mergedArray[k++] = arr2[j++];
}

System.out.println("Merged array: " + Arrays.toString(mergedArray));


}
}

72. Rotate an Array to the Right by k Steps

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 37/250
java

import java.util.Arrays;
import java.util.Scanner;

public class RotateArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

System.out.print("Enter the number of steps to rotate: ");


int k = scanner.nextInt();
k = k % n;

rotate(arr, k);
System.out.println("Array after rotation: " + Arrays.toString(arr));
}

public static void rotate(int[] arr, int k) {


reverse(arr, 0, arr.length - 1);
reverse(arr, 0, k - 1);
reverse(arr, k, arr.length - 1);
}

public static void reverse(int[] arr, int start, int end) {


while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
}

73. Count the Frequency of Elements in an Array

java

import java.util.HashMap;
import java.util.Scanner;

public class FrequencyCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

HashMap<Integer, Integer> frequencyMap = new HashMap<>();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 38/250
for (int num : arr) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}

System.out.println("Element frequencies:");
for (int key : frequencyMap.keySet()) {
System.out.println(key + ": " + frequencyMap.get(key));
}
}
}

74. Find the First Repeating Element in an Array

java

import java.util.HashSet;
import java.util.Scanner;

public class FirstRepeatingElement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

HashSet<Integer> set = new HashSet<>();


int repeating = -1;

for (int i = n - 1; i >= 0; i--) {


if (set.contains(arr[i])) {
repeating = arr[i];
} else {
set.add(arr[i]);
}
}

if (repeating != -1) {
System.out.println("First repeating element: " + repeating);
} else {
System.out.println("No repeating elements found.");
}
}
}

Let me know if you'd like more programs!

Here’s the next set of Java programs:

75. Find the Union of Two Arrays

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 39/250
java

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class UnionOfArrays {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the first array: ");
int n1 = scanner.nextInt();
int[] arr1 = new int[n1];

System.out.println("Enter the elements of the first array:");


for (int i = 0; i < n1; i++) {
arr1[i] = scanner.nextInt();
}

System.out.print("Enter the size of the second array: ");


int n2 = scanner.nextInt();
int[] arr2 = new int[n2];

System.out.println("Enter the elements of the second array:");


for (int i = 0; i < n2; i++) {
arr2[i] = scanner.nextInt();
}

Set<Integer> unionSet = new HashSet<>();


for (int num : arr1) {
unionSet.add(num);
}

for (int num : arr2) {


unionSet.add(num);
}

System.out.println("Union of the two arrays: " + unionSet);


}
}

76. Find the Intersection of Two Arrays

java

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class IntersectionOfArrays {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the first array: ");
int n1 = scanner.nextInt();
int[] arr1 = new int[n1];

System.out.println("Enter the elements of the first array:");


for (int i = 0; i < n1; i++) {
arr1[i] = scanner.nextInt();
}

System.out.print("Enter the size of the second array: ");


int n2 = scanner.nextInt();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 40/250
int[] arr2 = new int[n2];

System.out.println("Enter the elements of the second array:");


for (int i = 0; i < n2; i++) {
arr2[i] = scanner.nextInt();
}

Set<Integer> intersectionSet = new HashSet<>();


Set<Integer> arr1Set = new HashSet<>();

for (int num : arr1) {


arr1Set.add(num);
}

for (int num : arr2) {


if (arr1Set.contains(num)) {
intersectionSet.add(num);
}
}

System.out.println("Intersection of the two arrays: " + intersectionSet);


}
}

77. Remove Duplicates from an Array

java

import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class RemoveDuplicates {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of 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();
}

Set<Integer> uniqueSet = new HashSet<>();


for (int num : arr) {
uniqueSet.add(num);
}

System.out.println("Array without duplicates: " + uniqueSet);


}
}

78. Check if a String is a Palindrome

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 41/250
java

import java.util.Scanner;

public class PalindromeString {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

String reversedStr = new StringBuilder(str).reverse().toString();

if (str.equals(reversedStr)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}

79. Reverse a String

java

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 reversedStr = new StringBuilder(str).reverse().toString();


System.out.println("Reversed string: " + reversedStr);
}
}

80. Count the Number of Vowels and Consonants in a String

java

import java.util.Scanner;

public class VowelConsonantCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

int vowels = 0, consonants = 0;


for (char ch : str.toLowerCase().toCharArray()) {
if (Character.isLetter(ch)) {
if ("aeiou".indexOf(ch) != -1) {
vowels++;
} else {
consonants++;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 42/250
}
}
}

System.out.println("Number of vowels: " + vowels);


System.out.println("Number of consonants: " + consonants);
}
}

81. Check if a Number is Prime

java

import java.util.Scanner;

public class PrimeNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

boolean isPrime = num > 1;


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

82. Check if a Number is Armstrong

java

import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int originalNum = num, sum = 0, digits = String.valueOf(num).length();

while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, digits);
num /= 10;
}

if (sum == originalNum) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 43/250
System.out.println(originalNum + " is an Armstrong number.");
} else {
System.out.println(originalNum + " is not an Armstrong number.");
}
}
}

83. Print the Prime Numbers Between Two Numbers

java

import java.util.Scanner;

public class PrimeNumbersInRange {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the start number: ");
int start = scanner.nextInt();
System.out.print("Enter the end number: ");
int end = scanner.nextInt();

System.out.println("Prime numbers between " + start + " and " + end + ":");
for (int num = start; num <= end; num++) {
if (num > 1) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
}
}
}

Let me know if you'd like to continue with more programs!

Here’s the continuation to complete up to 100 Java programs:

84. Generate Fibonacci Sequence

java

import java.util.Scanner;

public class FibonacciSequence {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = scanner.nextInt();
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 44/250
int first = 0, second = 1;
System.out.print("Fibonacci sequence: " + first + " " + second + " ");

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


int next = first + second;
System.out.print(next + " ");
first = second;
second = next;
}
}
}

85. Calculate Factorial of a Number

java

import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}

System.out.println("Factorial of " + num + " is: " + factorial);


}
}

86. Check if a Number is Even or Odd

java

import java.util.Scanner;

public class EvenOdd {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

if (num % 2 == 0) {
System.out.println(num + " is an even number.");
} else {
System.out.println(num + " is an odd number.");
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 45/250
87. Sum of Digits of a Number

java

import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}

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


}
}

88. Reverse a Number

java

import java.util.Scanner;

public class ReverseNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}

System.out.println("Reversed number: " + reversed);


}
}

89. Convert Decimal to Binary

java

import java.util.Scanner;

public class DecimalToBinary {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a decimal number: ");
int num = scanner.nextInt();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 46/250
String binary = Integer.toBinaryString(num);
System.out.println("Binary representation: " + binary);
}
}

90. Convert Binary to Decimal

java

import java.util.Scanner;

public class BinaryToDecimal {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a binary number: ");
String binary = scanner.nextLine();

int decimal = Integer.parseInt(binary, 2);


System.out.println("Decimal representation: " + decimal);
}
}

91. Calculate Power of a Number

java

import java.util.Scanner;

public class PowerOfNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the base: ");
int base = scanner.nextInt();
System.out.print("Enter the exponent: ");
int exponent = scanner.nextInt();

long result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}

System.out.println(base + " raised to the power " + exponent + " is: " + resul
t);
}
}

92. Count the Number of Words in a String

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 47/250
java

import java.util.Scanner;

public class WordCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

String[] words = str.split("\\s+");


System.out.println("Number of words: " + words.length);
}
}

93. Print a Pyramid Pattern

java

import java.util.Scanner;

public class PyramidPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();

for (int i = 1; i <= rows; i++) {


for (int j = i; j < rows; j++) {
System.out.print(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
System.out.print("*");
}
System.out.println();
}
}
}

94. Print a Square Star Pattern

java

import java.util.Scanner;

public class SquareStarPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the square: ");
int size = scanner.nextInt();

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


for (int j = 0; j < size; j++) {
System.out.print("* ");
}
System.out.println();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 48/250
}
}
}

95. Count the Number of Uppercase and Lowercase Characters

java

import java.util.Scanner;

public class UpperLowerCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

int upperCount = 0, lowerCount = 0;

for (char ch : str.toCharArray()) {


if (Character.isUpperCase(ch)) {
upperCount++;
} else if (Character.isLowerCase(ch)) {
lowerCount++;
}
}

System.out.println("Uppercase letters: " + upperCount);


System.out.println("Lowercase letters: " + lowerCount);
}
}

96. Find the Length of a String Without Using length() Method

java

import java.util.Scanner;

public class StringLength {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

int length = 0;
for (char ch : str.toCharArray()) {
length++;
}

System.out.println("Length of the string: " + length);


}
}

97. Swap Two Numbers Without Using a Temporary Variable

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 49/250
java

import java.util.Scanner;

public class SwapNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter the second number: ");
int num2 = scanner.nextInt();

num1 = num1 + num2;


num2 = num1 - num2;
num1 = num1 - num2;

System.out.println("After swapping: num1 = " + num1 + ", num2 = " + num2);


}
}

98. Find GCD (Greatest Common Divisor) of Two Numbers

java

import java.util.Scanner;

public class GCD {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int a = scanner.nextInt();
System.out.print("Enter the second number: ");
int b = scanner.nextInt();

while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}

System.out.println("GCD is: " + a);


}
}

99. Find LCM (Least Common Multiple) of Two Numbers

java

import java.util.Scanner;

public class LCM {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int a = scanner.nextInt();
System.out.print("Enter the second number: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 50/250
int b = scanner.nextInt();

int gcd = gcd(a, b);


int lcm = (a * b) / gcd;

System.out.println("LCM is: " + lcm);


}

public static int gcd(int a, int b) {


while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}

100. Check if a String is a Substring of Another String

java

import java.util.Scanner;

public class SubstringCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the main string: ");
String mainStr = scanner.nextLine();
System.out.print("Enter the substring: ");
String subStr = scanner.nextLine();

if (mainStr.contains(subStr)) {
System.out.println(subStr + " is a substring of " + mainStr);
} else {
System.out.println(subStr + " is not a substring of " + mainStr);
}
}
}

This completes the list of 100 Java programs from basic to intermediate level! Let me know if you'd
like any further assistance or more examples!

Here are the next 25 different types of Java programs for you:

101. Check if a Number is Prime

java

import java.util.Scanner;

public class PrimeNumber {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 51/250
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

boolean isPrime = true;


for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime && num > 1) {


System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}

102. Find the Largest of Three Numbers

java

import java.util.Scanner;

public class LargestNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();

int largest = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2
: num3);
System.out.println("The largest number is: " + largest);
}
}

103. Print the Prime Numbers Up to N

java

import java.util.Scanner;

public class PrimeNumbersUpToN {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

System.out.println("Prime numbers up to " + n + ":");


for (int i = 2; i <= n; i++) {
boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(i); j++) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 52/250
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i + " ");
}
}
}
}

104. Calculate Simple Interest

java

import java.util.Scanner;

public class SimpleInterest {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter rate of interest: ");
double rate = scanner.nextDouble();
System.out.print("Enter time in years: ");
double time = scanner.nextDouble();

double interest = (principal * rate * time) / 100;


System.out.println("Simple Interest is: " + interest);
}
}

105. Calculate Compound Interest

java

import java.util.Scanner;

public class CompoundInterest {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter rate of interest: ");
double rate = scanner.nextDouble();
System.out.print("Enter time in years: ");
double time = scanner.nextDouble();
System.out.print("Enter number of times interest applied per year: ");
int n = scanner.nextInt();

double compoundInterest = principal * Math.pow(1 + rate / (100 * n), n * time) -


principal;
System.out.println("Compound Interest is: " + compoundInterest);
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 53/250
106. Print Multiplication Table

java

import java.util.Scanner;

public class MultiplicationTable {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

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


System.out.println(num + " * " + i + " = " + (num * i));
}
}
}

107. Convert Celsius to Fahrenheit

java

import java.util.Scanner;

public class CelsiusToFahrenheit {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature in Celsius: ");
double celsius = scanner.nextDouble();

double fahrenheit = (celsius * 9/5) + 32;


System.out.println("Temperature in Fahrenheit: " + fahrenheit);
}
}

108. Convert Fahrenheit to Celsius

java

import java.util.Scanner;

public class FahrenheitToCelsius {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit: ");
double fahrenheit = scanner.nextDouble();

double celsius = (fahrenheit - 32) * 5/9;


System.out.println("Temperature in Celsius: " + celsius);
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 54/250
109. Find the Length of the String Using Recursion

java

public class StringLengthRecursive {


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

public static int length(String str) {


if (str.isEmpty()) {
return 0;
} else {
return 1 + length(str.substring(1));
}
}
}

110. Check Palindrome Using Recursion

java

public class PalindromeRecursive {


public static void main(String[] args) {
String str = "madam";
if (isPalindrome(str, 0, str.length() - 1)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}

public static boolean isPalindrome(String str, int start, int end) {


if (start >= end) {
return true;
}
if (str.charAt(start) != str.charAt(end)) {
return false;
}
return isPalindrome(str, start + 1, end - 1);
}
}

111. Sum of First N Natural Numbers Using Recursion

java

public class SumNaturalNumbers {


public static void main(String[] args) {
int n = 5;
System.out.println("Sum of first " + n + " natural numbers: " + sum(n));
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 55/250
public static int sum(int n) {
if (n == 0) {
return 0;
}
return n + sum(n - 1);
}
}

112. Reverse a String Using Recursion

java

public class ReverseStringRecursive {


public static void main(String[] args) {
String str = "Hello";
System.out.println("Reversed String: " + reverse(str));
}

public static String reverse(String str) {


if (str.isEmpty()) {
return str;
}
return reverse(str.substring(1)) + str.charAt(0);
}
}

113. Merge Two Arrays

java

public class MergeArrays {


public static void main(String[] args) {
int[] arr1 = {1, 2, 3};
int[] arr2 = {4, 5, 6};

int[] mergedArr = new int[arr1.length + arr2.length];

System.arraycopy(arr1, 0, mergedArr, 0, arr1.length);


System.arraycopy(arr2, 0, mergedArr, arr1.length, arr2.length);

System.out.println("Merged Array: ");


for (int i : mergedArr) {
System.out.print(i + " ");
}
}
}

114. Sort an Array Using Bubble Sort

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 56/250
java

import java.util.Arrays;

public class BubbleSort {


public static void main(String[] args) {
int[] arr = {64, 34, 25, 12, 22, 11, 90};

for (int i = 0; i < arr.length - 1; i++) {


for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

System.out.println("Sorted Array: " + Arrays.toString(arr));


}
}

115. Sort an Array Using Selection Sort

java

import java.util.Arrays;

public class SelectionSort {


public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};

for (int i = 0; i < arr.length - 1; i++) {


int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}

System.out.println("Sorted Array: " + Arrays.toString(arr));


}
}

116. Sort an Array Using Insertion Sort

java

import java.util.Arrays;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 57/250
public class InsertionSort {
public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6};

for (int i = 1; i < arr.length; i++) {


int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}

System.out.println("Sorted Array: " + Arrays.toString(arr));


}
}

117. Linear Search

java

public class LinearSearch {


public static void main(String[] args) {
int[] arr = {12, 34, 45, 23, 56};
int target = 23;
boolean found = false;

for (int i = 0; i < arr.length; i++) {


if (arr[i] == target) {
found = true;
break;
}
}

if (found) {
System.out.println("Element found");
} else {
System.out.println("Element not found");
}
}
}

118. Binary Search

java

public class BinarySearch {


public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
int target = 30;

int result = binarySearch(arr, target);

if (result == -1) {
System.out.println("Element not found");
} else {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 58/250
System.out.println("Element found at index: " + result);
}
}

public static int binarySearch(int[] arr, int target) {


int left = 0, right = arr.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

return -1;
}
}

119. Check if a Number is Armstrong

java

import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int originalNum = num;
int sum = 0;
int digits = (int) Math.log10(num) + 1;

while (num > 0) {


int digit = num % 10;
sum += Math.pow(digit, digits);
num /= 10;
}

if (sum == originalNum) {
System.out.println(originalNum + " is an Armstrong number.");
} else {
System.out.println(originalNum + " is not an Armstrong number.");
}
}
}

120. Count Vowels and Consonants in a String

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 59/250
java

import java.util.Scanner;

public class VowelsConsonantsCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();

int vowels = 0, consonants = 0;


for (char ch : str.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}

System.out.println("Vowels: " + vowels);


System.out.println("Consonants: " + consonants);
}
}

This completes the next set of 25 Java programs! Let me know if you'd like more or if you need
further assistance!

Here are Java programs focused on control statements (if-else, switch, loops):

121. Check Even or Odd Using If-Else

java

import java.util.Scanner;

public class EvenOdd {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}

122. Find the Maximum of Three Numbers Using If-Else

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 60/250
java

import java.util.Scanner;

public class MaximumNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();

if (num1 >= num2 && num1 >= num3) {


System.out.println(num1 + " is the largest.");
} else if (num2 >= num1 && num2 >= num3) {
System.out.println(num2 + " is the largest.");
} else {
System.out.println(num3 + " is the largest.");
}
}
}

123. Check Leap Year Using If-Else

java

import java.util.Scanner;

public class LeapYear {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter year: ");
int year = scanner.nextInt();

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {


System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
}
}

124. Switch Case Example (Day of the Week)

java

import java.util.Scanner;

public class DayOfWeek {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number between 1 and 7: ");
int day = scanner.nextInt();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 61/250
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
case 7: System.out.println("Sunday"); break;
default: System.out.println("Invalid input.");
}
}
}

125. Switch Case Example (Grades)

java

import java.util.Scanner;

public class GradeEvaluation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter grade (A, B, C, D, F): ");
char grade = scanner.next().charAt(0);

switch (grade) {
case 'A': System.out.println("Excellent"); break;
case 'B': System.out.println("Good"); break;
case 'C': System.out.println("Average"); break;
case 'D': System.out.println("Pass"); break;
case 'F': System.out.println("Fail"); break;
default: System.out.println("Invalid grade.");
}
}
}

126. Find Factorial Using While Loop

java

import java.util.Scanner;

public class FactorialWhile {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int factorial = 1;

while (num > 0) {


factorial *= num;
num--;
}

System.out.println("Factorial is: " + factorial);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 62/250
}
}

127. Find Factorial Using For Loop

java

import java.util.Scanner;

public class FactorialFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int factorial = 1;

for (int i = 1; i <= num; i++) {


factorial *= i;
}

System.out.println("Factorial is: " + factorial);


}
}

128. Print Multiplication Table Using For Loop

java

import java.util.Scanner;

public class MultiplicationTable {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

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


System.out.println(num + " * " + i + " = " + (num * i));
}
}
}

129. Sum of Natural Numbers Using For Loop

java

import java.util.Scanner;

public class SumNaturalNumbersFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 63/250
int num = scanner.nextInt();
int sum = 0;

for (int i = 1; i <= num; i++) {


sum += i;
}

System.out.println("Sum of first " + num + " natural numbers is: " + sum);
}
}

130. Sum of Digits Using While Loop

java

import java.util.Scanner;

public class SumDigitsWhile {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int sum = 0;

while (num > 0) {


sum += num % 10;
num /= 10;
}

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


}
}

131. Reverse a Number Using While Loop

java

import java.util.Scanner;

public class ReverseNumberWhile {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int reverse = 0;

while (num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}

System.out.println("Reversed number is: " + reverse);


}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 64/250
132. Reverse a Number Using For Loop

java

import java.util.Scanner;

public class ReverseNumberFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int reverse = 0;

for (; num != 0; num /= 10) {


reverse = reverse * 10 + num % 10;
}

System.out.println("Reversed number is: " + reverse);


}
}

133. Print Fibonacci Series Using While Loop

java

import java.util.Scanner;

public class FibonacciWhile {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int terms = scanner.nextInt();

int a = 0, b = 1;
System.out.println("Fibonacci Series: ");
while (terms > 0) {
System.out.print(a + " ");
int nextTerm = a + b;
a = b;
b = nextTerm;
terms--;
}
}
}

134. Print Fibonacci Series Using For Loop

java

import java.util.Scanner;

public class FibonacciFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of terms: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 65/250
int terms = scanner.nextInt();

int a = 0, b = 1;
System.out.println("Fibonacci Series: ");
for (int i = 1; i <= terms; i++) {
System.out.print(a + " ");
int nextTerm = a + b;
a = b;
b = nextTerm;
}
}
}

135. Find GCD of Two Numbers Using For Loop

java

import java.util.Scanner;

public class GCD {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();

int gcd = 1;
for (int i = 1; i <= num1 && i <= num2; i++) {
if (num1 % i == 0 && num2 % i == 0) {
gcd = i;
}
}

System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
}
}

136. Find LCM of Two Numbers Using For Loop

java

import java.util.Scanner;

public class LCM {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();

int lcm = (num1 > num2) ? num1 : num2;


while (true) {
if (lcm % num1 == 0 && lcm % num2 == 0) {
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
break;
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 66/250
lcm++;
}
}
}

137. Print Multiplication Table Using Do-While Loop

java

import java.util.Scanner;

public class MultiplicationTableDoWhile {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int i = 1;

do {
System.out.println(num + " * " + i + " = " + (num * i));
i++;
} while (i <= 10);
}
}

138. Count Down from 10 Using While Loop

java

public class Countdown {


public static void main(String[] args) {
int num = 10;
while (num > 0) {
System.out.println(num);
num--;
}
}
}

139. Check if a Number is Prime Using For Loop

java

import java.util.Scanner;

public class PrimeNumberFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
boolean isPrime = true;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 67/250
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime && num > 1) {


System.out.println(num + " is prime.");
} else {
System.out.println(num + " is not prime.");
}
}
}

These are the next set of Java programs related to control statements. Let me know if you'd like
more!

Here are more Java programs using control statements:

140. Sum of Prime Numbers up to N

java

import java.util.Scanner;

public class SumOfPrimes {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int limit = scanner.nextInt();
int sum = 0;

for (int num = 2; num <= limit; num++) {


boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
sum += num;
}
}

System.out.println("Sum of prime numbers up to " + limit + " is: " + sum);


}
}

141. Count Digits in a Number Using While Loop

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 68/250
java

import java.util.Scanner;

public class CountDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int count = 0;

while (num != 0) {
num /= 10;
count++;
}

System.out.println("Number of digits is: " + count);


}
}

142. Check for Armstrong Number

java

import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int originalNum = num;
int sum = 0;

while (num != 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}

if (sum == originalNum) {
System.out.println(originalNum + " is an Armstrong number.");
} else {
System.out.println(originalNum + " is not an Armstrong number.");
}
}
}

143. Palindrome Number Using While Loop

java

import java.util.Scanner;

public class PalindromeNumber {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 69/250
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int originalNum = num;
int reverse = 0;

while (num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}

if (originalNum == reverse) {
System.out.println(originalNum + " is a palindrome.");
} else {
System.out.println(originalNum + " is not a palindrome.");
}
}
}

144. Sum of Elements in an Array Using For Loop

java

import java.util.Scanner;

public class ArraySum {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
int sum = 0;

System.out.println("Enter the elements: ");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
sum += arr[i];
}

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


}
}

145. Find Maximum Element in an Array Using For Loop

java

import java.util.Scanner;

public class ArrayMax {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter the elements: ");


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 70/250
arr[i] = scanner.nextInt();
}

int max = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}

System.out.println("Maximum element is: " + max);


}
}

146. Reverse an Array Using For Loop

java

import java.util.Scanner;

public class ReverseArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter the elements: ");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Reversed array: ");


for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

147. Count Occurrences of an Element in an Array

java

import java.util.Scanner;

public class CountOccurrences {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter the elements: ");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.print("Enter the element to count: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 71/250
int element = scanner.nextInt();
int count = 0;

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


if (arr[i] == element) {
count++;
}
}

System.out.println("Occurrences of " + element + " are: " + count);


}
}

148. Print Prime Numbers Up to N Using For Loop

java

import java.util.Scanner;

public class PrintPrimes {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int limit = scanner.nextInt();

System.out.println("Prime numbers up to " + limit + ":");


for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
}
}

149. Print Triangle Pattern Using For Loop

java

import java.util.Scanner;

public class TrianglePattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 72/250
}
}
}

150. Print Inverted Triangle Pattern Using For Loop

java

import java.util.Scanner;

public class InvertedTrianglePattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();

for (int i = rows; i >= 1; i--) {


for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}

These programs cover a variety of control statements such as loops, if-else, and switch-case. Let me
know if you'd like additional programs!

Here are Java programs focused on loops:

151. Print Numbers from 1 to N Using While Loop

java

import java.util.Scanner;

public class NumbersUsingWhile {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

int i = 1;
while (i <= n) {
System.out.print(i + " ");
i++;
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 73/250
152. Print Even Numbers from 1 to N Using For Loop

java

import java.util.Scanner;

public class EvenNumbersUsingFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

System.out.println("Even numbers from 1 to " + n + ":");


for (int i = 2; i <= n; i += 2) {
System.out.print(i + " ");
}
}
}

153. Print Odd Numbers from 1 to N Using For Loop

java

import java.util.Scanner;

public class OddNumbersUsingFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

System.out.println("Odd numbers from 1 to " + n + ":");


for (int i = 1; i <= n; i += 2) {
System.out.print(i + " ");
}
}
}

154. Print Multiplication Table of a Given Number

java

import java.util.Scanner;

public class MultiplicationTable {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();

System.out.println("Multiplication Table of " + num + ":");


for (int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 74/250
}
}

155. Find Factorial of a Number Using For Loop

java

import java.util.Scanner;

public class FactorialUsingFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int factorial = 1;

for (int i = 1; i <= num; i++) {


factorial *= i;
}

System.out.println("Factorial of " + num + " is: " + factorial);


}
}

156. Sum of First N Natural Numbers Using While Loop

java

import java.util.Scanner;

public class SumNaturalNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
int sum = 0;

int i = 1;
while (i <= n) {
sum += i;
i++;
}

System.out.println("Sum of first " + n + " natural numbers is: " + sum);


}
}

157. Sum of Odd Numbers from 1 to N Using For Loop

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 75/250
java

import java.util.Scanner;

public class SumOddNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
int sum = 0;

for (int i = 1; i <= n; i += 2) {


sum += i;
}

System.out.println("Sum of odd numbers from 1 to " + n + " is: " + sum);


}
}

158. Sum of Even Numbers from 1 to N Using For Loop

java

import java.util.Scanner;

public class SumEvenNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
int sum = 0;

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


sum += i;
}

System.out.println("Sum of even numbers from 1 to " + n + " is: " + sum);


}
}

159. Count Down from N to 1 Using While Loop

java

import java.util.Scanner;

public class CountDown {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

while (n >= 1) {
System.out.print(n + " ");
n--;
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 76/250
}
}

160. Print Fibonacci Series up to N Using For Loop

java

import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();
int a = 0, b = 1;

System.out.println("Fibonacci Series up to " + n + ":");


for (int i = 1; i <= n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}

161. Print Prime Numbers Up to N Using For Loop

java

import java.util.Scanner;

public class PrimeNumbersUsingFor {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

System.out.println("Prime numbers up to " + n + ":");


for (int num = 2; num <= n; num++) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 77/250
162. Print Multiplication Table Using While Loop

java

import java.util.Scanner;

public class MultiplicationTableWhile {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int i = 1;

while (i <= 10) {


System.out.println(num + " x " + i + " = " + (num * i));
i++;
}
}
}

163. Reverse Numbers from N to 1 Using For Loop

java

import java.util.Scanner;

public class ReverseNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = scanner.nextInt();

for (int i = n; i >= 1; i--) {


System.out.print(i + " ");
}
}
}

164. Print Star Pyramid Pattern

java

import java.util.Scanner;

public class StarPyramid {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();

for (int i = 1; i <= rows; i++) {


for (int j = rows; j > i; j--) {
System.out.print(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 78/250
System.out.print("*");
}
System.out.println();
}
}
}

165. Print Hollow Square Star Pattern

java

import java.util.Scanner;

public class HollowSquare {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the size of the square: ");
int size = scanner.nextInt();

for (int i = 1; i <= size; i++) {


for (int j = 1; j <= size; j++) {
if (i == 1 || i == size || j == 1 || j == size) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

These programs cover various loop operations, including `for`, `while`, and `do-while` loops. Let
me know if you'd like more!

Here are more Java programs focused on loops:

166. Print Floyd's Triangle

java

import java.util.Scanner;

public class FloydsTriangle {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
int number = 1;

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= i; j++) {
System.out.print(number + " ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 79/250
number++;
}
System.out.println();
}
}
}

167. Print Diamond Star Pattern

java

import java.util.Scanner;

public class DiamondPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();

// Upper half of the diamond


for (int i = 1; i <= rows; i++) {
for (int j = rows; j > i; j--) {
System.out.print(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
System.out.print("*");
}
System.out.println();
}

// Lower half of the diamond


for (int i = rows - 1; i >= 1; i--) {
for (int j = rows; j > i; j--) {
System.out.print(" ");
}
for (int j = 1; j <= (2 * i - 1); j++) {
System.out.print("*");
}
System.out.println();
}
}
}

168. Find GCD of Two Numbers Using For Loop

java

import java.util.Scanner;

public class GCD {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int gcd = 1;

for (int i = 1; i <= num1 && i <= num2; i++) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 80/250
if (num1 % i == 0 && num2 % i == 0) {
gcd = i;
}
}

System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
}
}

169. Find LCM of Two Numbers Using For Loop

java

import java.util.Scanner;

public class LCM {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int num1 = scanner.nextInt();
int num2 = scanner.nextInt();
int lcm = 1;

for (int i = 1; i <= num1 * num2; i++) {


if (i % num1 == 0 && i % num2 == 0) {
lcm = i;
break;
}
}

System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
}
}

170. Print Multiplication of Two Matrices

java

import java.util.Scanner;

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows and columns for Matrix A: ");
int rows1 = scanner.nextInt();
int cols1 = scanner.nextInt();

System.out.print("Enter number of rows and columns for Matrix B: ");


int rows2 = scanner.nextInt();
int cols2 = scanner.nextInt();

if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible.");
return;
}

int[][] matrixA = new int[rows1][cols1];


int[][] matrixB = new int[rows2][cols2];

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 81/250
int[][] result = new int[rows1][cols2];

System.out.println("Enter elements of Matrix A:");


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrixA[i][j] = scanner.nextInt();
}
}

System.out.println("Enter elements of Matrix B:");


for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrixB[i][j] = scanner.nextInt();
}
}

// Multiplying matrices
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}

// Printing result matrix


System.out.println("Result of Matrix Multiplication:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}

171. Check for Prime Number Using While Loop

java

import java.util.Scanner;

public class PrimeCheckUsingWhile {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
boolean isPrime = true;
int i = 2;

while (i <= Math.sqrt(num)) {


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

if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 82/250
}
}

172. Print Pascal's Triangle

java

import java.util.Scanner;

public class PascalsTriangle {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();

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


int num = 1;
for (int j = 0; j <= i; j++) {
System.out.print(num + " ");
num = num * (i - j) / (j + 1);
}
System.out.println();
}
}
}

173. Print Half Pyramid Star Pattern

java

import java.util.Scanner;

public class HalfPyramidPattern {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = scanner.nextInt();

for (int i = 1; i <= rows; i++) {


for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}

174. Sum of Digits of a Number Using While Loop

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 83/250
java

import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = scanner.nextInt();
int sum = 0;

while (num != 0) {
sum += num % 10;
num /= 10;
}

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


}
}

175. Reverse a String Using For Loop

java

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


}
}

These programs continue with more advanced usage of loops, including complex patterns and
operations like matrix multiplication, Pascal's triangle, and prime checking. Let me know if you'd like
more!

Here are Java programs focused on arrays:

176. Find the Largest Element in an Array

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 84/250
java

import java.util.Scanner;

public class LargestElement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int largest = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}

System.out.println("Largest element: " + largest);


}
}

177. Find the Smallest Element in an Array

java

import java.util.Scanner;

public class SmallestElement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int smallest = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}

System.out.println("Smallest element: " + smallest);


}
}

178. Reverse an Array

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 85/250
java

import java.util.Scanner;

public class ReverseArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Reversed array:");
for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

179. Sum of Elements in an Array

java

import java.util.Scanner;

public class SumOfArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
int sum = 0;

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
sum += arr[i];
}

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


}
}

180. Average of Elements in an Array

java

import java.util.Scanner;

public class AverageOfArray {


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 86/250
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
int sum = 0;

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
sum += arr[i];
}

double average = (double) sum / n;


System.out.println("Average of elements: " + average);
}
}

181. Count Even and Odd Numbers in an Array

java

import java.util.Scanner;

public class EvenOddCount {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
int evenCount = 0, oddCount = 0;

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
if (arr[i] % 2 == 0) {
evenCount++;
} else {
oddCount++;
}
}

System.out.println("Even numbers count: " + evenCount);


System.out.println("Odd numbers count: " + oddCount);
}
}

182. Find the Second Largest Element in an Array

java

import java.util.Scanner;

public class SecondLargestElement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 87/250
System.out.println("Enter elements of the array:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int largest = arr[0];


int secondLargest = Integer.MIN_VALUE;

for (int i = 1; i < n; i++) {


if (arr[i] > largest) {
secondLargest = largest;
largest = arr[i];
} else if (arr[i] > secondLargest && arr[i] != largest) {
secondLargest = arr[i];
}
}

System.out.println("Second largest element: " + secondLargest);


}
}

183. Merge Two Arrays

java

import java.util.Scanner;

public class MergeArrays {


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

System.out.print("Enter number of elements in array 1: ");


int n1 = scanner.nextInt();
int[] arr1 = new int[n1];
System.out.println("Enter elements of array 1:");
for (int i = 0; i < n1; i++) {
arr1[i] = scanner.nextInt();
}

System.out.print("Enter number of elements in array 2: ");


int n2 = scanner.nextInt();
int[] arr2 = new int[n2];
System.out.println("Enter elements of array 2:");
for (int i = 0; i < n2; i++) {
arr2[i] = scanner.nextInt();
}

int[] mergedArray = new int[n1 + n2];


for (int i = 0; i < n1; i++) {
mergedArray[i] = arr1[i];
}
for (int i = 0; i < n2; i++) {
mergedArray[n1 + i] = arr2[i];
}

System.out.println("Merged array:");
for (int i = 0; i < mergedArray.length; i++) {
System.out.print(mergedArray[i] + " ");
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 88/250
184. Sort an Array in Ascending Order

java

import java.util.Scanner;

public class SortArrayAscending {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

for (int i = 0; i < n - 1; i++) {


for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

System.out.println("Sorted array in ascending order:");


for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}

185. Check if an Array is Sorted

java

import java.util.Scanner;

public class CheckArraySorted {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];
boolean isSorted = true;

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

for (int i = 1; i < n; i++) {


if (arr[i] < arr[i - 1]) {
isSorted = false;
break;
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 89/250
if (isSorted) {
System.out.println("Array is sorted.");
} else {
System.out.println("Array is not sorted.");
}
}
}

These programs cover various basic to intermediate concepts involving arrays. If you'd like to
explore more, feel free to ask!

Here are more Java programs focusing on arrays:

186. Find the Frequency of Each Element in an Array

java

import java.util.Scanner;
import java.util.HashMap;

public class FrequencyOfElements {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

HashMap<Integer, Integer> frequency = new HashMap<>();


for (int i = 0; i < n; i++) {
frequency.put(arr[i], frequency.getOrDefault(arr[i], 0) + 1);
}

System.out.println("Element frequencies:");
for (int key : frequency.keySet()) {
System.out.println(key + ": " + frequency.get(key));
}
}
}

187. Rotate an Array by n Positions

java

import java.util.Scanner;

public class RotateArray {


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 90/250
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.print("Enter number of positions to rotate: ");


int k = scanner.nextInt();
k = k % n; // To handle if k > n

System.out.println("Array after rotating " + k + " positions:");


for (int i = k; i < n; i++) {
System.out.print(arr[i] + " ");
}
for (int i = 0; i < k; i++) {
System.out.print(arr[i] + " ");
}
}
}

188. Remove Duplicates from an Array

java

import java.util.Scanner;
import java.util.HashSet;

public class RemoveDuplicates {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

HashSet<Integer> set = new HashSet<>();


System.out.println("Array after removing duplicates:");
for (int i = 0; i < n; i++) {
if (!set.contains(arr[i])) {
System.out.print(arr[i] + " ");
set.add(arr[i]);
}
}
}
}

189. Find the Missing Number in an Array

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 91/250
java

import java.util.Scanner;

public class MissingNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements (n-1): ");
int n = scanner.nextInt();
int[] arr = new int[n];
int totalSum = n * (n + 1) / 2; // Sum of numbers from 1 to n

System.out.println("Enter elements of the array:");


int sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
sum += arr[i];
}

int missingNumber = totalSum - sum;


System.out.println("Missing number: " + missingNumber);
}
}

190. Find the Intersection of Two Arrays

java

import java.util.Scanner;
import java.util.HashSet;

public class ArrayIntersection {


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

System.out.print("Enter the number of elements in array 1: ");


int n1 = scanner.nextInt();
int[] arr1 = new int[n1];

System.out.println("Enter elements of array 1:");


for (int i = 0; i < n1; i++) {
arr1[i] = scanner.nextInt();
}

System.out.print("Enter the number of elements in array 2: ");


int n2 = scanner.nextInt();
int[] arr2 = new int[n2];

System.out.println("Enter elements of array 2:");


for (int i = 0; i < n2; i++) {
arr2[i] = scanner.nextInt();
}

HashSet<Integer> set = new HashSet<>();


System.out.println("Intersection of two arrays:");
for (int i = 0; i < n1; i++) {
set.add(arr1[i]);
}

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


if (set.contains(arr2[i])) {
System.out.print(arr2[i] + " ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 92/250
set.remove(arr2[i]); // To avoid duplicates
}
}
}
}

191. Find the Union of Two Arrays

java

import java.util.Scanner;
import java.util.HashSet;

public class ArrayUnion {


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

System.out.print("Enter the number of elements in array 1: ");


int n1 = scanner.nextInt();
int[] arr1 = new int[n1];

System.out.println("Enter elements of array 1:");


for (int i = 0; i < n1; i++) {
arr1[i] = scanner.nextInt();
}

System.out.print("Enter the number of elements in array 2: ");


int n2 = scanner.nextInt();
int[] arr2 = new int[n2];

System.out.println("Enter elements of array 2:");


for (int i = 0; i < n2; i++) {
arr2[i] = scanner.nextInt();
}

HashSet<Integer> set = new HashSet<>();


System.out.println("Union of two arrays:");
for (int i = 0; i < n1; i++) {
set.add(arr1[i]);
}

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


set.add(arr2[i]);
}

for (int element : set) {


System.out.print(element + " ");
}
}
}

192. Find the Kth Largest Element in an Array

java

import java.util.Scanner;
import java.util.Arrays;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 93/250
public class KthLargestElement {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.print("Enter value of k: ");


int k = scanner.nextInt();

Arrays.sort(arr);
System.out.println(k + "th largest element: " + arr[n - k]);
}
}

193. Find the Duplicate Elements in an Array

java

import java.util.Scanner;
import java.util.HashSet;

public class FindDuplicates {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

HashSet<Integer> set = new HashSet<>();


System.out.println("Duplicate elements in the array:");
for (int i = 0; i < n; i++) {
if (!set.add(arr[i])) {
System.out.print(arr[i] + " ");
}
}
}
}

194. Shift Zeros to End of Array

java

import java.util.Scanner;

public class ShiftZerosToEnd {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 94/250
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
arr[count++] = arr[i];
}
}

while (count < n) {


arr[count++] = 0;
}

System.out.println("Array after shifting zeros to end:");


for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}

These programs focus on various aspects of arrays like frequency, rotation, duplicates, and unions.
Let me know if you'd like to continue with more topics or need further assistance!

Here are more Java programs focusing on arrays:

195. Merge Two Sorted Arrays

java

import java.util.Scanner;

public class MergeSortedArrays {


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

System.out.print("Enter the number of elements in array 1: ");


int n1 = scanner.nextInt();
int[] arr1 = new int[n1];

System.out.println("Enter elements of array 1:");


for (int i = 0; i < n1; i++) {
arr1[i] = scanner.nextInt();
}

System.out.print("Enter the number of elements in array 2: ");


int n2 = scanner.nextInt();
int[] arr2 = new int[n2];

System.out.println("Enter elements of array 2:");


for (int i = 0; i < n2; i++) {
arr2[i] = scanner.nextInt();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 95/250
}

int[] mergedArray = new int[n1 + n2];


int i = 0, j = 0, k = 0;

while (i < n1 && j < n2) {


if (arr1[i] < arr2[j]) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
}
}

while (i < n1) {


mergedArray[k++] = arr1[i++];
}

while (j < n2) {


mergedArray[k++] = arr2[j++];
}

System.out.println("Merged sorted array:");


for (int element : mergedArray) {
System.out.print(element + " ");
}
}
}

196. Find the Maximum Product of Two Numbers in an Array

java

import java.util.Scanner;

public class MaxProductOfTwo {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int maxProduct = Integer.MIN_VALUE;


for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int product = arr[i] * arr[j];
if (product > maxProduct) {
maxProduct = product;
}
}
}

System.out.println("Maximum product of two numbers: " + maxProduct);


}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 96/250
197. Find the Second Largest Element in an Array

java

import java.util.Scanner;

public class SecondLargestElement {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

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

System.out.println("Second largest element: " + secondLargest);


}
}

198. Reverse an Array

java

import java.util.Scanner;

public class ReverseArray {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.println("Array before reversing:");


for (int element : arr) {
System.out.print(element + " ");
}

int start = 0, end = n - 1;


while (start < end) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 97/250
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}

System.out.println("\nArray after reversing:");


for (int element : arr) {
System.out.print(element + " ");
}
}
}

199. Check if an Array is Palindrome

java

import java.util.Scanner;

public class PalindromeArray {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int start = 0, end = n - 1;


boolean isPalindrome = true;
while (start < end) {
if (arr[start] != arr[end]) {
isPalindrome = false;
break;
}
start++;
end--;
}

if (isPalindrome) {
System.out.println("The array is a palindrome.");
} else {
System.out.println("The array is not a palindrome.");
}
}
}

200. Count the Occurrences of an Element in an Array

java

import java.util.Scanner;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 98/250
public class CountOccurrences {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.print("Enter the element to count: ");


int element = scanner.nextInt();

int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == element) {
count++;
}
}

System.out.println("The element " + element + " appears " + count + " times.");
}
}

These programs cover a wide range of operations on arrays, such as merging arrays, reversing,
checking for palindromes, and counting occurrences. Let me know if you'd like to continue with
more topics or need further assistance!

Here are more Java programs focusing on arrays and other key topics:

201. Sort an Array in Ascending Order

java

import java.util.Scanner;
import java.util.Arrays;

public class SortArray {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

Arrays.sort(arr);
System.out.println("Sorted array in ascending order:");
for (int element : arr) {
System.out.print(element + " ");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 99/250
}
}

202. Find the Sum of All Elements in an Array

java

import java.util.Scanner;

public class SumOfArray {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}

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


}
}

203. Find the Smallest Element in an Array

java

import java.util.Scanner;

public class SmallestElement {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int smallest = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] < smallest) {
smallest = arr[i];
}
}

System.out.println("Smallest element: " + smallest);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 100/250
}
}

204. Find the Largest Element in an Array

java

import java.util.Scanner;

public class LargestElement {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int largest = arr[0];


for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
}

System.out.println("Largest element: " + largest);


}
}

205. Count Positive and Negative Numbers in an Array

java

import java.util.Scanner;

public class CountPositiveNegative {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int positiveCount = 0, negativeCount = 0;

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


if (arr[i] > 0) {
positiveCount++;
} else if (arr[i] < 0) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 101/250
negativeCount++;
}
}

System.out.println("Positive numbers: " + positiveCount);


System.out.println("Negative numbers: " + negativeCount);
}
}

206. Find the Element with Maximum Occurrence in an Array

java

import java.util.Scanner;
import java.util.HashMap;

public class MaxOccurrenceElement {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

HashMap<Integer, Integer> map = new HashMap<>();


for (int i = 0; i < n; i++) {
map.put(arr[i], map.getOrDefault(arr[i], 0) + 1);
}

int maxCount = 0;
int maxElement = arr[0];
for (int key : map.keySet()) {
if (map.get(key) > maxCount) {
maxCount = map.get(key);
maxElement = key;
}
}

System.out.println("Element with maximum occurrence: " + maxElement);


}
}

207. Shift Elements in an Array to Left

java

import java.util.Scanner;

public class ShiftElementsLeft {


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

System.out.print("Enter the number of elements: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 102/250
int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int temp = arr[0];


for (int i = 0; i < n - 1; i++) {
arr[i] = arr[i + 1];
}
arr[n - 1] = temp;

System.out.println("Array after shifting left:");


for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}

208. Shift Elements in an Array to Right

java

import java.util.Scanner;

public class ShiftElementsRight {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int temp = arr[n - 1];


for (int i = n - 1; i > 0; i--) {
arr[i] = arr[i - 1];
}
arr[0] = temp;

System.out.println("Array after shifting right:");


for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}

209. Find the Missing Number in a Sorted Array

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 103/250
java

import java.util.Scanner;

public class MissingNumberSorted {


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

System.out.print("Enter the number of elements (n-1): ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

int totalSum = (n + 1) * (n + 2) / 2; // Sum of 1 to n+1


int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}

int missingNumber = totalSum - sum;


System.out.println("Missing number: " + missingNumber);
}
}

210. Check if an Array is Sorted

java

import java.util.Scanner;

public class CheckSortedArray {


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

System.out.print("Enter the number of elements: ");


int n = scanner.nextInt();
int[] arr = new int[n];

System.out.println("Enter elements of the array:");


for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

boolean isSorted = true;


for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
isSorted = false;
break;
}
}

if (isSorted) {
System.out.println("The array is sorted.");
} else {
System.out.println("The array is not sorted.");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 104/250
}
}

These programs cover additional array operations like sorting, shifting elements, finding missing
numbers, and checking if an array is sorted. Let me know if you'd like to continue with more
programs or if you need assistance on other topics!

Here are Java programs focusing on String operations:

211. Reverse a String

java

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 input = scanner.nextLine();

String reversed = new StringBuilder(input).reverse().toString();

System.out.println("Reversed string: " + reversed);


}
}

212. Check if a String is Palindrome

java

import java.util.Scanner;

public class PalindromeString {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String reversed = new StringBuilder(input).reverse().toString();

if (input.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 105/250
213. Count the Number of Vowels in a String

java

import java.util.Scanner;

public class CountVowels {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

int count = 0;
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
}
}

System.out.println("Number of vowels: " + count);


}
}

214. Remove All White Spaces from a String

java

import java.util.Scanner;

public class RemoveWhitespace {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String result = input.replaceAll("\\s", "");

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


}
}

215. Count the Number of Words in a String

java

import java.util.Scanner;

public class CountWords {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 106/250
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String[] words = input.split("\\s+");


System.out.println("Number of words: " + words.length);
}
}

216. Convert a String to Uppercase

java

import java.util.Scanner;

public class StringToUppercase {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String result = input.toUpperCase();


System.out.println("String in uppercase: " + result);
}
}

217. Convert a String to Lowercase

java

import java.util.Scanner;

public class StringToLowercase {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String result = input.toLowerCase();


System.out.println("String in lowercase: " + result);
}
}

218. Check if Two Strings are Anagrams

java

import java.util.Scanner;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 107/250
public class AnagramStrings {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

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


String str1 = scanner.nextLine();

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


String str2 = scanner.nextLine();

str1 = str1.replaceAll("\\s", "").toLowerCase();


str2 = str2.replaceAll("\\s", "").toLowerCase();

char[] str1Arr = str1.toCharArray();


char[] str2Arr = str2.toCharArray();

java.util.Arrays.sort(str1Arr);
java.util.Arrays.sort(str2Arr);

if (java.util.Arrays.equals(str1Arr, str2Arr)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
}

219. Find the First Non-Repeated Character in a String

java

import java.util.Scanner;
import java.util.HashMap;

public class FirstNonRepeatedCharacter {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

HashMap<Character, Integer> charCount = new HashMap<>();

for (char ch : input.toCharArray()) {


charCount.put(ch, charCount.getOrDefault(ch, 0) + 1);
}

for (char ch : input.toCharArray()) {


if (charCount.get(ch) == 1) {
System.out.println("First non-repeated character: " + ch);
break;
}
}
}
}

220. Replace All Occurrences of a Character in a String

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 108/250
java

import java.util.Scanner;

public class ReplaceCharacter {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the character to be replaced: ");


char oldChar = scanner.next().charAt(0);

System.out.print("Enter the new character: ");


char newChar = scanner.next().charAt(0);

String result = input.replace(oldChar, newChar);


System.out.println("Modified string: " + result);
}
}

221. Check if a String Contains Another String

java

import java.util.Scanner;

public class StringContains {


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

System.out.print("Enter the main string: ");


String mainString = scanner.nextLine();

System.out.print("Enter the string to search for: ");


String searchString = scanner.nextLine();

if (mainString.contains(searchString)) {
System.out.println("The main string contains the search string.");
} else {
System.out.println("The main string does not contain the search string.");
}
}
}

222. Concatenate Two Strings

java

import java.util.Scanner;

public class ConcatenateStrings {


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 109/250
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

String result = str1.concat(str2);


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

223. Count the Number of Occurrences of a Character in a String

java

import java.util.Scanner;

public class CountCharacterOccurrence {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the character to count: ");


char ch = scanner.next().charAt(0);

int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch) {
count++;
}
}

System.out.println("The character '" + ch + "' appears " + count + " times.");


}
}

These programs focus on string manipulation such as reversing, checking palindromes, finding
occurrences, and converting cases. Let me know if you'd like to continue with more programs or
need help with another topic!

Here are the next set of Java programs focusing on String operations:

224. Find the Length of a String

java

import java.util.Scanner;

public class StringLength {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 110/250
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String input = scanner.nextLine();

int length = input.length();


System.out.println("Length of the string: " + length);
}
}

225. Extract Substring from a String

java

import java.util.Scanner;

public class SubstringExample {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the starting index: ");


int start = scanner.nextInt();

System.out.print("Enter the ending index: ");


int end = scanner.nextInt();

String substring = input.substring(start, end);


System.out.println("Extracted substring: " + substring);
}
}

226. Check if a String Starts with a Given Prefix

java

import java.util.Scanner;

public class StringStartsWith {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the prefix to check: ");


String prefix = scanner.nextLine();

if (input.startsWith(prefix)) {
System.out.println("The string starts with the given prefix.");
} else {
System.out.println("The string does not start with the given prefix.");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 111/250
}
}

227. Check if a String Ends with a Given Suffix

java

import java.util.Scanner;

public class StringEndsWith {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the suffix to check: ");


String suffix = scanner.nextLine();

if (input.endsWith(suffix)) {
System.out.println("The string ends with the given suffix.");
} else {
System.out.println("The string does not end with the given suffix.");
}
}
}

228. Replace All Occurrences of a Substring in a String

java

import java.util.Scanner;

public class ReplaceSubstring {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the substring to replace: ");


String oldSubstring = scanner.nextLine();

System.out.print("Enter the new substring: ");


String newSubstring = scanner.nextLine();

String result = input.replace(oldSubstring, newSubstring);


System.out.println("Modified string: " + result);
}
}

229. Split a String into an Array of Words

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 112/250
java

import java.util.Scanner;

public class SplitString {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String[] words = input.split("\\s+");


System.out.println("Array of words:");
for (String word : words) {
System.out.println(word);
}
}
}

230. Join an Array of Strings into a Single String

java

import java.util.Scanner;

public class JoinStrings {


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

System.out.print("Enter the number of words: ");


int n = scanner.nextInt();
scanner.nextLine(); // Consume the newline character

String[] words = new String[n];

System.out.println("Enter the words:");


for (int i = 0; i < n; i++) {
words[i] = scanner.nextLine();
}

String result = String.join(" ", words);


System.out.println("Joined string: " + result);
}
}

231. Remove All Non-Alphanumeric Characters from a String

java

import java.util.Scanner;

public class RemoveNonAlphanumeric {


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

System.out.print("Enter a string: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 113/250
String input = scanner.nextLine();

String result = input.replaceAll("[^a-zA-Z0-9]", "");


System.out.println("String after removing non-alphanumeric characters: " + resul
t);
}
}

232. Convert a String to Character Array

java

import java.util.Scanner;

public class StringToCharArray {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

char[] charArray = input.toCharArray();


System.out.println("Character array:");
for (char ch : charArray) {
System.out.println(ch);
}
}
}

233. Convert Character Array to String

java

import java.util.Scanner;

public class CharArrayToString {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

char[] charArray = input.toCharArray();


String result = new String(charArray);
System.out.println("String from character array: " + result);
}
}

234. Compare Two Strings Lexicographically

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 114/250
java

import java.util.Scanner;

public class CompareStrings {


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

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

int comparison = str1.compareTo(str2);

if (comparison == 0) {
System.out.println("The strings are equal.");
} else if (comparison < 0) {
System.out.println("The first string is lexicographically smaller.");
} else {
System.out.println("The first string is lexicographically larger.");
}
}
}

235. Convert String to Integer

java

import java.util.Scanner;

public class StringToInt {


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

System.out.print("Enter a string representing a number: ");


String input = scanner.nextLine();

try {
int number = Integer.parseInt(input);
System.out.println("Converted number: " + number);
} catch (NumberFormatException e) {
System.out.println("Invalid number format.");
}
}
}

236. Convert Integer to String

java

import java.util.Scanner;

public class IntToString {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 115/250
Scanner scanner = new Scanner(System.in);

System.out.print("Enter an integer: ");


int number = scanner.nextInt();

String result = String.valueOf(number);


System.out.println("Converted string: " + result);
}
}

237. Remove a Specific Character from a String

java

import java.util.Scanner;

public class RemoveCharacter {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the character to remove: ");


char ch = scanner.next().charAt(0);

String result = input.replace(Character.toString(ch), "");


System.out.println("String after removal: " + result);
}
}

238. Check if a String Contains Only Digits

java

import java.util.Scanner;

public class StringIsDigit {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

if (input.matches("[0-9]+")) {
System.out.println("The string contains only digits.");
} else {
System.out.println("The string contains non-digit characters.");
}
}
}

239. Find the Index of First Occurrence of a Character in a String

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 116/250
java

import java.util.Scanner;

public class FindFirstOccurrence {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the character to find: ");


char ch = scanner.next().charAt(0);

int index = input.indexOf(ch);


if (index != -1) {
System.out.println("First occurrence of character '" + ch + "' is at index:
" + index);
} else {
System.out.println("Character not found in the string.");
}
}
}

These programs continue to cover a variety of String operations such as converting, comparing,
checking, removing characters, and substring extraction. Let me know if you'd like to proceed
further or need additional explanations!

Here are more Java programs focusing on String manipulation and other concepts:

240. Check if a String is a Palindrome

java

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 input = scanner.nextLine();

String reversed = new StringBuilder(input).reverse().toString();

if (input.equals(reversed)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 117/250
241. Count the Occurrences of a Character in a String

java

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 input = scanner.nextLine();

System.out.print("Enter the character to count: ");


char ch = scanner.next().charAt(0);

int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch) {
count++;
}
}

System.out.println("Character '" + ch + "' appears " + count + " times.");


}
}

242. Convert a String to Lowercase

java

import java.util.Scanner;

public class StringToLower {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String result = input.toLowerCase();


System.out.println("String in lowercase: " + result);
}
}

243. Convert a String to Uppercase

java

import java.util.Scanner;

public class StringToUpper {


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 118/250
System.out.print("Enter a string: ");
String input = scanner.nextLine();

String result = input.toUpperCase();


System.out.println("String in uppercase: " + result);
}
}

244. Remove Extra Spaces from a String

java

import java.util.Scanner;

public class RemoveExtraSpaces {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String result = input.replaceAll("\\s+", " ").trim();


System.out.println("String after removing extra spaces: " + result);
}
}

245. Count the Number of Words in a String

java

import java.util.Scanner;

public class WordCount {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String[] words = input.split("\\s+");


System.out.println("Number of words: " + words.length);
}
}

246. Reverse a String Without Using Built-in Methods

java

import java.util.Scanner;

public class ReverseString {


public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 119/250
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String reversed = "";


for (int i = input.length() - 1; i >= 0; i--) {
reversed += input.charAt(i);
}

System.out.println("Reversed string: " + reversed);


}
}

247. Check if Two Strings are Anagrams

java

import java.util.Arrays;
import java.util.Scanner;

public class AnagramCheck {


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

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

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

248. Remove All White Spaces from a String

java

import java.util.Scanner;

public class RemoveSpaces {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 120/250
String result = input.replaceAll("\\s", "");
System.out.println("String after removing all spaces: " + result);
}
}

249. Compare Two Strings (Case Insensitive)

java

import java.util.Scanner;

public class CompareStringsIgnoreCase {


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

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

if (str1.equalsIgnoreCase(str2)) {
System.out.println("The strings are equal (case insensitive).");
} else {
System.out.println("The strings are not equal.");
}
}
}

250. Find the Index of Last Occurrence of a Character in a String

java

import java.util.Scanner;

public class LastOccurrence {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the character to find: ");


char ch = scanner.next().charAt(0);

int index = input.lastIndexOf(ch);


if (index != -1) {
System.out.println("Last occurrence of character '" + ch + "' is at index: "
+ index);
} else {
System.out.println("Character not found in the string.");
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 121/250
These programs explore String manipulation topics such as palindrome checking, word counting,
string comparison, removing spaces, reversing strings, and more. Let me know if you'd like more
programs or need explanations on any specific topic!

Here are the next set of Java programs on String Manipulation and related topics:

251. Count Vowels and Consonants in a String

java

import java.util.Scanner;

public class CountVowelsConsonants {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine().toLowerCase();

int vowels = 0, consonants = 0;

for (int i = 0; i < input.length(); i++) {


char ch = input.charAt(i);
if (ch >= 'a' && ch <= 'z') {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowels++;
} else {
consonants++;
}
}
}

System.out.println("Vowels: " + vowels);


System.out.println("Consonants: " + consonants);
}
}

252. Remove Duplicates from a String

java

import java.util.Scanner;

public class RemoveDuplicates {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

StringBuilder result = new StringBuilder();


for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (result.toString().indexOf(ch) == -1) {
result.append(ch);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 122/250
}
}

System.out.println("String after removing duplicates: " + result);


}
}

253. Convert String to ASCII Values

java

import java.util.Scanner;

public class StringToASCII {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.println("ASCII values:");
for (int i = 0; i < input.length(); i++) {
System.out.println(input.charAt(i) + ": " + (int) input.charAt(i));
}
}
}

254. Check if a String Contains a Substring

java

import java.util.Scanner;

public class ContainsSubstring {


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

System.out.print("Enter the main string: ");


String mainStr = scanner.nextLine();

System.out.print("Enter the substring to check: ");


String subStr = scanner.nextLine();

if (mainStr.contains(subStr)) {
System.out.println("The main string contains the substring.");
} else {
System.out.println("The main string does not contain the substring.");
}
}
}

255. Concatenate Two Strings

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 123/250
java

import java.util.Scanner;

public class ConcatenateStrings {


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

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

String result = str1 + str2;


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

256. Find the First Non-Repeated Character in a String

java

import java.util.Scanner;

public class FirstNonRepeatedCharacter {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

for (int i = 0; i < input.length(); i++) {


char ch = input.charAt(i);
if (input.indexOf(ch) == input.lastIndexOf(ch)) {
System.out.println("First non-repeated character: " + ch);
break;
}
}
}
}

257. Reverse Each Word in a String

java

import java.util.Scanner;

public class ReverseEachWord {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 124/250
StringBuilder result = new StringBuilder();

for (String word : words) {


result.append(new StringBuilder(word).reverse()).append(" ");
}

System.out.println("String after reversing each word: " + result.toString().trim


());
}
}

258. Count the Number of Palindromic Words in a String

java

import java.util.Scanner;

public class PalindromicWordsCount {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

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


int count = 0;

for (String word : words) {


String reversed = new StringBuilder(word).reverse().toString();
if (word.equals(reversed)) {
count++;
}
}

System.out.println("Number of palindromic words: " + count);


}
}

259. Check if a String is a Rotated Version of Another String

java

import java.util.Scanner;

public class StringRotation {


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

System.out.print("Enter the first string: ");


String str1 = scanner.nextLine();

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

if (str1.length() == str2.length() && (str1 + str1).contains(str2)) {


System.out.println("The second string is a rotated version of the first stri
ng.");
} else {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 125/250
System.out.println("The second string is not a rotated version of the first
string.");
}
}
}

260. Convert a String to Title Case

java

import java.util.Scanner;

public class TitleCase {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

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


StringBuilder result = new StringBuilder();

for (String word : words) {


result.append(word.substring(0, 1).toUpperCase())
.append(word.substring(1).toLowerCase())
.append(" ");
}

System.out.println("Title case: " + result.toString().trim());


}
}

261. Check if a String is Empty or Null

java

import java.util.Scanner;

public class CheckEmptyOrNull {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

if (input == null || input.isEmpty()) {


System.out.println("The string is either empty or null.");
} else {
System.out.println("The string is not empty.");
}
}
}

262. Extract Digits from a String


Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 126/250
java

import java.util.Scanner;

public class ExtractDigits {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

String digits = input.replaceAll("[^0-9]", "");


System.out.println("Extracted digits: " + digits);
}
}

263. Remove a Specific Word from a String

java

import java.util.Scanner;

public class RemoveWord {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

System.out.print("Enter the word to remove: ");


String wordToRemove = scanner.nextLine();

String result = input.replaceAll("\\b" + wordToRemove + "\\b", "");


System.out.println("String after removing the word: " + result);
}
}

264. Check if String Contains Only Alphabets

java

import java.util.Scanner;

public class OnlyAlphabets {


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

System.out.print("Enter a string: ");


String input = scanner.nextLine();

if (input.matches("[a-zA-Z]+")) {
System.out.println("The string contains only alphabets.");
} else {
System.out.println("The string contains non-alphabet characters.");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 127/250
}
}

These additional programs provide more practice with String manipulation, such as handling
spaces, counting vowels and consonants, removing duplicates, and more. If you'd like further
programs or clarifications, feel free to ask!

Here are Java programs focusing on Object-Oriented Programming (OOP) concepts:

265. Implement a Simple Class with Constructor

java

class Person {
String name;
int age;

// Constructor to initialize the object


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

// Method to display the values


void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class ConstructorExample {


public static void main(String[] args) {
Person person = new Person("John", 25);
person.display();
}
}

266. Implement Method Overloading

java

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

// Method to add three integers (method overloading)


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 128/250
public class MethodOverloadingExample {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum of two numbers: " + calc.add(10, 20));
System.out.println("Sum of three numbers: " + calc.add(10, 20, 30));
}
}

267. Demonstrate Method Overriding

java

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

class Dog extends Animal {


// Overriding the sound method
@Override
void sound() {
System.out.println("Dog barks");
}
}

public class MethodOverridingExample {


public static void main(String[] args) {
Animal animal = new Animal();
animal.sound();

Dog dog = new Dog();


dog.sound();
}
}

268. Example of Inheritance

java

class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}

class Car extends Vehicle {


void move() {
System.out.println("Car is moving");
}
}

public class InheritanceExample {


public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.move();

Car car = new Car();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 129/250
car.move();
}
}

269. Constructor Chaining in Java

java

class A {
A() {
System.out.println("Class A constructor");
}
}

class B extends A {
B() {
super(); // Calling class A constructor
System.out.println("Class B constructor");
}
}

public class ConstructorChainingExample {


public static void main(String[] args) {
B obj = new B(); // This will call constructor of A and then B
}
}

270. Implementing Interfaces

java

interface Animal {
void sound(); // abstract method
}

class Cat implements Animal {


@Override
public void sound() {
System.out.println("Cat meows");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Animal animal = new Cat();
animal.sound();
}
}

271. Abstract Class Example

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 130/250
java

abstract class Shape {


abstract void draw(); // Abstract method

void display() {
System.out.println("Shape displayed");
}
}

class Circle extends Shape {


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

public class AbstractClassExample {


public static void main(String[] args) {
Shape shape = new Circle();
shape.draw();
shape.display();
}
}

272. Static Keyword Example

java

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

Counter() {
count++;
System.out.println("Count: " + count);
}

static void displayCount() {


System.out.println("Total count: " + count);
}
}

public class StaticExample {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

Counter.displayCount();
}
}

273. Encapsulation Example

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 131/250
java

class Person {
private String name; // private field

// Getter method
public String getName() {
return name;
}

// Setter method
public void setName(String name) {
this.name = name;
}
}

public class EncapsulationExample {


public static void main(String[] args) {
Person person = new Person();
person.setName("Alice");
System.out.println("Person's name: " + person.getName());
}
}

274. Demonstrate Polymorphism

java

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

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("Cat meows");
}
}

public class PolymorphismExample {


public static void main(String[] args) {
Animal animal;

animal = new Dog();


animal.sound(); // Dog's sound

animal = new Cat();


animal.sound(); // Cat's sound
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 132/250
275. Final Keyword Example

java

class FinalExample {
final int CONSTANT_VALUE = 10; // Final variable

void display() {
System.out.println("Constant Value: " + CONSTANT_VALUE);
}
}

public class FinalKeywordExample {


public static void main(String[] args) {
FinalExample example = new FinalExample();
example.display();
}
}

These programs cover key OOP concepts such as:

Constructor and method overloading


Inheritance and method overriding
Interfaces and abstract classes
Encapsulation and static keyword
Polymorphism and final keyword

If you'd like more examples or further explanations on any concept, feel free to ask!

Here are additional Object-Oriented Programming (OOP) programs:

276. Constructor with Parameters

java

class Book {
String title;
String author;

// Constructor with parameters


Book(String title, String author) {
this.title = title;
this.author = author;
}

void display() {
System.out.println("Book Title: " + title + ", Author: " + author);
}
}

public class ConstructorWithParameters {


public static void main(String[] args) {
Book book = new Book("The Great Gatsby", "F. Scott Fitzgerald");
book.display();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 133/250
}
}

277. Implementing Multiple Interfaces

java

interface Animal {
void sound();
}

interface Movable {
void move();
}

class Dog implements Animal, Movable {


public void sound() {
System.out.println("Dog barks");
}

public void move() {


System.out.println("Dog runs");
}
}

public class MultipleInterfaces {


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

278. Super Keyword Example

java

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

class Dog extends Animal {


@Override
void sound() {
super.sound(); // Calls parent class method
System.out.println("Dog barks");
}
}

public class SuperKeywordExample {


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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 134/250
}
}

279. Instanceof Keyword Example

java

class Animal {
}

class Dog extends Animal {


}

public class InstanceofExample {


public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();

System.out.println(animal instanceof Animal); // true


System.out.println(dog instanceof Animal); // true
System.out.println(animal instanceof Dog); // false
}
}

280. Method Returning Object

java

class Person {
String name;

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

// Method returning an object


Person createPerson(String name) {
return new Person(name);
}

void display() {
System.out.println("Person's Name: " + name);
}
}

public class ReturnObjectExample {


public static void main(String[] args) {
Person person1 = new Person("Alice");
person1.display();

Person person2 = person1.createPerson("Bob");


person2.display();
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 135/250
281. Nested Classes

java

class OuterClass {
private String outerVar = "Outer Class Variable";

class InnerClass {
void display() {
System.out.println(outerVar); // Accessing outer class variable
}
}
}

public class NestedClassExample {


public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.display();
}
}

282. Static Nested Class

java

class OuterClass {
static int outerVar = 10;

static class InnerClass {


void display() {
System.out.println("Outer Class Static Variable: " + outerVar);
}
}
}

public class StaticNestedClassExample {


public static void main(String[] args) {
OuterClass.InnerClass inner = new OuterClass.InnerClass();
inner.display();
}
}

283. StringBuilder Class

java

public class StringBuilderExample {


public static void main(String[] args) {
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World!");
System.out.println("StringBuilder Output: " + sb);

sb.insert(5, " Java");


System.out.println("After Insertion: " + sb);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 136/250
sb.replace(0, 5, "Hi");
System.out.println("After Replacement: " + sb);

sb.delete(3, 7);
System.out.println("After Deletion: " + sb);
}
}

284. Creating a Simple Bank Account Class

java

class BankAccount {
private double balance;

BankAccount(double initialBalance) {
this.balance = initialBalance;
}

void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("Deposited: " + amount);
}
}

void withdraw(double amount) {


if (amount <= balance && amount > 0) {
balance -= amount;
System.out.println("Withdrew: " + amount);
} else {
System.out.println("Insufficient balance.");
}
}

void displayBalance() {
System.out.println("Balance: " + balance);
}
}

public class BankAccountExample {


public static void main(String[] args) {
BankAccount account = new BankAccount(500);
account.deposit(200);
account.withdraw(100);
account.displayBalance();
}
}

285. Singleton Pattern Example

java

class Singleton {
private static Singleton instance;

private Singleton() { }

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 137/250
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}

void showMessage() {
System.out.println("Singleton instance accessed!");
}
}

public class SingletonPatternExample {


public static void main(String[] args) {
Singleton singleton = Singleton.getInstance();
singleton.showMessage();
}
}

286. Factory Design Pattern Example

java

interface Animal {
void sound();
}

class Dog implements Animal {


@Override
public void sound() {
System.out.println("Dog barks");
}
}

class Cat implements Animal {


@Override
public void sound() {
System.out.println("Cat meows");
}
}

class AnimalFactory {
public Animal createAnimal(String type) {
if (type.equalsIgnoreCase("Dog")) {
return new Dog();
} else if (type.equalsIgnoreCase("Cat")) {
return new Cat();
}
return null;
}
}

public class FactoryPatternExample {


public static void main(String[] args) {
AnimalFactory factory = new AnimalFactory();

Animal dog = factory.createAnimal("Dog");


dog.sound();

Animal cat = factory.createAnimal("Cat");


cat.sound();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 138/250
}
}

These programs showcase various OOP principles like:

Constructor with parameters


Multiple interfaces and inheritance
`super` and `instanceof` keywords
Factory design pattern, Singleton pattern
Nested classes, static nested classes
Working with `StringBuilder` and creating a simple bank account class

Feel free to ask if you'd like more examples on specific OOP topics or concepts!

Here are additional Object-Oriented Programming (OOP) programs:

287. Cloneable Interface Example

java

class Book implements Cloneable {


String title;
String author;

Book(String title, String author) {


this.title = title;
this.author = author;
}

// Overriding clone() method


public Object clone() throws CloneNotSupportedException {
return super.clone();
}

void display() {
System.out.println("Book Title: " + title + ", Author: " + author);
}
}

public class CloneableExample {


public static void main(String[] args) {
try {
Book originalBook = new Book("Java Programming", "John Doe");
originalBook.display();

// Cloning the original book


Book clonedBook = (Book) originalBook.clone();
clonedBook.display();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 139/250
288. Overloading and Overriding Example

java

class Shape {
void area() {
System.out.println("Calculating area");
}
}

class Circle extends Shape {


@Override
void area() {
System.out.println("Area of Circle: πr²");
}

// Overloaded method
void area(double radius) {
System.out.println("Area of Circle with radius " + radius + ": " + (3.14 * radiu
s * radius));
}
}

public class OverloadingAndOverriding {


public static void main(String[] args) {
Shape shape = new Shape();
shape.area();

Circle circle = new Circle();


circle.area();
circle.area(5.0);
}
}

289. Aggregation Example

java

class Engine {
void start() {
System.out.println("Engine started");
}
}

class Car {
Engine engine;

Car(Engine engine) {
this.engine = engine;
}

void drive() {
engine.start();
System.out.println("Car is driving");
}
}

public class AggregationExample {


public static void main(String[] args) {
Engine engine = new Engine();
Car car = new Car(engine);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 140/250
car.drive();
}
}

290. Composition Example

java

class Wheel {
void rotate() {
System.out.println("Wheel is rotating");
}
}

class Car {
private Wheel wheel;

Car() {
this.wheel = new Wheel(); // Car has a Wheel (Composition)
}

void drive() {
wheel.rotate();
System.out.println("Car is driving");
}
}

public class CompositionExample {


public static void main(String[] args) {
Car car = new Car();
car.drive();
}
}

291. Superclass Constructor Calling from Subclass

java

class Animal {
Animal() {
System.out.println("Animal is created");
}
}

class Dog extends Animal {


Dog() {
// Calling the superclass constructor
super();
System.out.println("Dog is created");
}
}

public class SuperConstructorExample {


public static void main(String[] args) {
Dog dog = new Dog();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 141/250
}
}

292. Object Class Methods (equals(), hashCode(), toString())

java

class Person {
String name;
int age;

Person(String name, int age) {


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

@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return age == person.age && name.equals(person.name);
}

@Override
public int hashCode() {
return name.hashCode() + age;
}

@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}

public class ObjectClassMethods {


public static void main(String[] args) {
Person p1 = new Person("John", 25);
Person p2 = new Person("John", 25);

System.out.println(p1.equals(p2)); // true
System.out.println(p1.hashCode());
System.out.println(p1.toString());
}
}

293. Final Class Example

java

final class FinalClass {


void display() {
System.out.println("This is a final class");
}
}

// The following code will give a compilation error:


// class SubClass extends FinalClass {}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 142/250
public class FinalClassExample {
public static void main(String[] args) {
FinalClass obj = new FinalClass();
obj.display();
}
}

294. Abstract Class and Concrete Method Example

java

abstract class Animal {


abstract void sound(); // Abstract method

// Concrete method
void breathe() {
System.out.println("Animal breathes");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

public class AbstractClassConcreteMethod {


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

295. Wrapper Classes Example

java

public class WrapperClassExample {


public static void main(String[] args) {
int num = 100;

// Converting primitive to wrapper class


Integer integerObj = Integer.valueOf(num);

// Unboxing: Wrapper class to primitive


int unboxed = integerObj.intValue();

System.out.println("Wrapper Object: " + integerObj);


System.out.println("Unboxed value: " + unboxed);
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 143/250
296. Recursive Method Example

java

class Factorial {
int calculateFactorial(int n) {
if (n == 0)
return 1;
else
return n * calculateFactorial(n - 1);
}
}

public class RecursiveMethodExample {


public static void main(String[] args) {
Factorial factorial = new Factorial();
System.out.println("Factorial of 5: " + factorial.calculateFactorial(5));
}
}

These programs further demonstrate the power of OOP in Java by:

Showing cloneable interface and overloading and overriding methods


Exploring aggregation and composition relationships
Using the `super` keyword, `equals()`, `hashCode()`, and `toString()` methods from the
`Object` class
Using final and abstract classes and methods
Demonstrating wrapper classes, recursion, and the final class concept

If you need more examples or further explanations on any specific concept, feel free to ask!

Here are the next set of Object-Oriented Programming (OOP) programs:

297. Method Chaining Example

java

class Person {
private String name;
private int age;

// Chaining methods to set properties


Person setName(String name) {
this.name = name;
return this;
}

Person setAge(int age) {


this.age = age;
return this;
}

void display() {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 144/250
System.out.println("Name: " + name + ", Age: " + age);
}
}

public class MethodChainingExample {


public static void main(String[] args) {
Person person = new Person();
person.setName("Alice").setAge(25).display();
}
}

298. Static Method Example

java

class MathOperations {
static int square(int number) {
return number * number;
}
}

public class StaticMethodExample {


public static void main(String[] args) {
int result = MathOperations.square(5);
System.out.println("Square of 5: " + result);
}
}

299. Inner Class and Outer Class Communication

java

class Outer {
private int outerValue = 10;

class Inner {
void display() {
System.out.println("Outer class value: " + outerValue);
}
}
}

public class InnerOuterCommunication {


public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
}
}

300. Method Overriding with `super` Example

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 145/250
java

class Vehicle {
void displayInfo() {
System.out.println("This is a vehicle");
}
}

class Car extends Vehicle {


@Override
void displayInfo() {
super.displayInfo(); // Calling the parent class method
System.out.println("This is a car");
}
}

public class MethodOverridingSuper {


public static void main(String[] args) {
Car car = new Car();
car.displayInfo();
}
}

301. Class with Final Method Example

java

class Animal {
final void speak() {
System.out.println("Animal speaks");
}
}

class Dog extends Animal {


// Cannot override the speak method because it's final in the parent class
// void speak() {
// System.out.println("Dog barks");
// }
}

public class FinalMethodExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.speak(); // Calls the parent class method
}
}

302. Multiple Inheritance via Interfaces Example

java

interface Animal {
void sound();
}

interface Movement {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 146/250
void move();
}

class Dog implements Animal, Movement {


@Override
public void sound() {
System.out.println("Dog barks");
}

@Override
public void move() {
System.out.println("Dog runs");
}
}

public class MultipleInheritanceExample {


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

303. Abstract Class with Multiple Concrete Methods

java

abstract class Shape {


abstract void draw();

void displayMessage() {
System.out.println("Shape is being drawn");
}
}

class Circle extends Shape {


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

public class AbstractWithConcreteMethods {


public static void main(String[] args) {
Circle circle = new Circle();
circle.displayMessage();
circle.draw();
}
}

304. Default Methods in Interfaces Example

java

interface Shape {
default void displayShape() {
System.out.println("Displaying Shape");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 147/250
}

class Circle implements Shape {


void draw() {
System.out.println("Drawing a Circle");
}
}

public class DefaultMethodsInInterface {


public static void main(String[] args) {
Circle circle = new Circle();
circle.displayShape(); // Calls the default method from the interface
circle.draw();
}
}

305. Method Overloading with Different Data Types

java

class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}

String add(String a, String b) {


return a + b;
}
}

public class MethodOverloadingDifferentDataTypes {


public static void main(String[] args) {
Calculator calc = new Calculator();

System.out.println("Sum of Integers: " + calc.add(5, 10));


System.out.println("Sum of Doubles: " + calc.add(5.5, 10.5));
System.out.println("Concatenation of Strings: " + calc.add("Hello, ", "Worl
d!"));
}
}

306. StringBuffer Class Example

java

public class StringBufferExample {


public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
sb.insert(5, " Java");
sb.replace(6, 10, "Programming");
sb.delete(0, 5);

System.out.println("StringBuffer Output: " + sb);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 148/250
}
}

307. Anonymous Class Example

java

interface Animal {
void sound();
}

public class AnonymousClassExample {


public static void main(String[] args) {
Animal dog = new Animal() {
@Override
public void sound() {
System.out.println("Dog barks");
}
};
dog.sound();
}
}

These programs showcase:

Method chaining and static methods


Inner class and method overriding with `super`
Final methods and final classes
Multiple inheritance through interfaces and abstract classes
Default methods in interfaces
Method overloading with various data types
StringBuffer and anonymous classes

If you need further details or more examples, feel free to ask!

Here are some Exception Handling programs in Java, demonstrating different types of exceptions
and how to handle them.

308. Basic Exception Handling (Try-Catch) Example

java

public class BasicExceptionHandling {


public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 149/250
}
}

309. Multiple Catch Blocks Example

java

public class MultipleCatchBlocks {


public static void main(String[] args) {
try {
int[] arr = new int[5];
arr[10] = 30; // ArrayIndexOutOfBoundsException

int result = 10 / 0; // ArithmeticException


} catch (ArithmeticException e) {
System.out.println("Arithmetic Error: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bounds: " + e.getMessage());
} catch (Exception e) {
System.out.println("General Exception: " + e.getMessage());
}
}
}

310. Try-Catch with Finally Block

java

public class TryCatchFinally {


public static void main(String[] args) {
try {
int result = 10 / 2;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("This block always executes");
}
}
}

311. Nested Try-Catch Example

java

public class NestedTryCatch {


public static void main(String[] args) {
try {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Inner Catch: Arithmetic Exception");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 150/250
throw new Exception("New Exception from inner catch");
}
} catch (Exception e) {
System.out.println("Outer Catch: " + e.getMessage());
}
}
}

312. Throw Statement Example

java

public class ThrowStatementExample {


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Age must be 18 or older");
} else {
System.out.println("Age is valid");
}
}

public static void main(String[] args) {


try {
checkAge(15); // Throws exception
} catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

313. Throws Keyword Example

java

class CustomException extends Exception {


CustomException(String message) {
super(message);
}
}

public class ThrowsKeywordExample {


static void validateAge(int age) throws CustomException {
if (age < 18) {
throw new CustomException("Age must be 18 or older");
} else {
System.out.println("Age is valid");
}
}

public static void main(String[] args) {


try {
validateAge(16); // Throws custom exception
} catch (CustomException e) {
System.out.println("Caught Exception: " + e.getMessage());
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 151/250
}
}

314. Catching Multiple Exceptions with Multi-Catch

java

public class MultiCatchExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException
String str = null;
System.out.println(str.length()); // NullPointerException
} catch (ArithmeticException | NullPointerException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

315. Custom Exception Handling Example

java

class InvalidAmountException extends Exception {


InvalidAmountException(String message) {
super(message);
}
}

public class CustomExceptionHandling {


static void deposit(double amount) throws InvalidAmountException {
if (amount <= 0) {
throw new InvalidAmountException("Amount must be greater than zero");
} else {
System.out.println("Deposited amount: " + amount);
}
}

public static void main(String[] args) {


try {
deposit(-100); // Throws custom exception
} catch (InvalidAmountException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

316. Exception Handling with String Parsing

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 152/250
java

public class ExceptionHandlingWithParsing {


public static void main(String[] args) {
String str = "abc";
try {
int num = Integer.parseInt(str); // NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

317. Exception Propagation Example

java

class Parent {
void methodA() throws Exception {
throw new Exception("Exception in methodA");
}
}

class Child extends Parent {


void methodB() throws Exception {
try {
methodA(); // Propagating the exception
} catch (Exception e) {
System.out.println("Caught Exception in methodB: " + e.getMessage());
throw e;
}
}
}

public class ExceptionPropagationExample {


public static void main(String[] args) {
Child child = new Child();
try {
child.methodB();
} catch (Exception e) {
System.out.println("Caught Exception in main: " + e.getMessage());
}
}
}

318. Handling Exception in Multithreading

java

class MyThread extends Thread {


@Override
public void run() {
try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception in thread: " + e.getMessage());

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 153/250
}
}
}

public class ThreadExceptionHandling {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}

These programs cover a wide range of exception handling techniques in Java, including:

Basic try-catch blocks and finally block


Multiple catch blocks, nested try-catch
Throw and throws keywords
Custom exception handling and multi-catch
Handling number format exceptions, parsing errors, and thread exceptions

Let me know if you need more examples or explanations!

Here are additional Exception Handling programs in Java:

319. Chained Exception Example

java

class ParentException extends Exception {


ParentException(String message) {
super(message);
}
}

class ChildException extends Exception {


ChildException(String message) {
super(message);
}
}

public class ChainedExceptionExample {


public static void main(String[] args) {
try {
throw new ChildException("This is a child exception");
} catch (ChildException e) {
try {
throw new ParentException("This is a parent exception");
} catch (ParentException p) {
p.initCause(e); // Chaining the exception
System.out.println("Parent Exception: " + p.getMessage());
System.out.println("Caused by: " + p.getCause());
}
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 154/250
320. Try-With-Resources Example (Auto-closeable)

java

import java.io.*;

public class TryWithResources {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line = br.readLine();
System.out.println(line);
} catch (IOException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}

321. Handling Exception with Loggers (Using `java.util.logging`)

java

import java.util.logging.*;

public class LoggerExample {


private static final Logger logger = Logger.getLogger(LoggerExample.class.getName
());

public static void main(String[] args) {


try {
int result = 10 / 0; // ArithmeticException
} catch (ArithmeticException e) {
logger.log(Level.SEVERE, "Exception occurred: ", e);
}
}
}

322. Rethrowing Exceptions

java

class InvalidAgeException extends Exception {


InvalidAgeException(String message) {
super(message);
}
}

public class RethrowExceptionExample {


static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or older");
}
}

public static void main(String[] args) {


try {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 155/250
checkAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
throw new RuntimeException("Re-throwing the exception", e);
}
}
}

323. Exception Handling with Input/Output (I/O) Operations

java

import java.io.*;

public class IOExceptionHandling {


public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("nonexistentFile.txt");
int data = file.read();
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
}

324. Exception Handling in File Operations

java

import java.io.*;

public class FileOperationException {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, World!");
writer.close();
} catch (IOException e) {
System.out.println("IOException occurred: " + e.getMessage());
}
}
}

325. Exception Handling with Custom Message

java

class InvalidInputException extends Exception {


InvalidInputException(String message) {
super(message);
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 156/250
public class CustomMessageExceptionExample {
static void validateInput(int num) throws InvalidInputException {
if (num < 1) {
throw new InvalidInputException("Input cannot be less than 1");
} else {
System.out.println("Valid input: " + num);
}
}

public static void main(String[] args) {


try {
validateInput(0); // Throws custom exception
} catch (InvalidInputException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

326. Handling FileNotFoundException

java

import java.io.*;

public class FileNotFoundExceptionExample {


public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream("nonexistentFile.txt");
file.read();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException: " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
}

327. Exception Handling with ArrayList

java

import java.util.*;

public class ArrayListExceptionHandling {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
try {
list.add("Java");
list.add("Python");
System.out.println(list.get(5)); // IndexOutOfBoundsException
} catch (IndexOutOfBoundsException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 157/250
328. Handling NullPointerException

java

public class NullPointerExceptionHandling {


public static void main(String[] args) {
String str = null;
try {
System.out.println(str.length()); // NullPointerException
} catch (NullPointerException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

329. Handling NumberFormatException

java

public class NumberFormatExceptionExample {


public static void main(String[] args) {
String str = "abc";
try {
int num = Integer.parseInt(str); // NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

330. Try-Catch with Multiple Exceptions

java

public class MultipleExceptionHandling {


public static void main(String[] args) {
try {
String str = null;
int num = Integer.parseInt(str); // NullPointerException, NumberFormatExcep
tion
} catch (NullPointerException | NumberFormatException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
}
}

331. Custom Exception with Error Code

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 158/250
java

class InvalidAmountException extends Exception {


private int errorCode;

InvalidAmountException(String message, int errorCode) {


super(message);
this.errorCode = errorCode;
}

int getErrorCode() {
return errorCode;
}
}

public class CustomExceptionWithCode {


static void withdraw(double amount) throws InvalidAmountException {
if (amount <= 0) {
throw new InvalidAmountException("Amount must be greater than zero", 1001);
} else {
System.out.println("Withdrawn: " + amount);
}
}

public static void main(String[] args) {


try {
withdraw(-100);
} catch (InvalidAmountException e) {
System.out.println("Error Code: " + e.getErrorCode() + " - " + e.getMessage
());
}
}
}

332. Handling SQLException

java

import java.sql.*;

public class SQLExceptionExample {


public static void main(String[] args) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/t
estdb", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM nonexistentTable"); // SQLE
xception
} catch (SQLException e) {
System.out.println("SQL Error: " + e.getMessage());
}
}
}

These additional programs further demonstrate various aspects of Exception Handling, such as:

Chained exceptions
Try-with-resources
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 159/250
Rethrowing exceptions
Custom exceptions with error codes
SQL exceptions and I/O exceptions

Let me know if you need more or further clarification!

Here are Java Collections programs demonstrating the usage of various Collection classes and
interfaces.

333. Using ArrayList

java

import java.util.*;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

for (String language : list) {


System.out.println(language);
}
}
}

334. Using LinkedList

java

import java.util.*;

public class LinkedListExample {


public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.add("Java");
list.add("Python");
list.add("C++");

list.addFirst("Ruby"); // Add at the beginning


list.addLast("JavaScript"); // Add at the end

for (String language : list) {


System.out.println(language);
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 160/250
335. Using HashSet

java

import java.util.*;

public class HashSetExample {


public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C++");
set.add("Java"); // Duplicate value will be ignored

for (String language : set) {


System.out.println(language);
}
}
}

336. Using TreeSet

java

import java.util.*;

public class TreeSetExample {


public static void main(String[] args) {
TreeSet<String> set = new TreeSet<>();
set.add("Java");
set.add("Python");
set.add("C++");
set.add("Java"); // Duplicate value will be ignored

for (String language : set) {


System.out.println(language); // Sorted order
}
}
}

337. Using HashMap

java

import java.util.*;

public class HashMapExample {


public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");

for (Map.Entry<Integer, String> entry : map.entrySet()) {


System.out.println(entry.getKey() + " : " + entry.getValue());

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 161/250
}
}
}

338. Using LinkedHashMap

java

import java.util.*;

public class LinkedHashMapExample {


public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");

for (Map.Entry<Integer, String> entry : map.entrySet()) {


System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}

339. Using TreeMap

java

import java.util.*;

public class TreeMapExample {


public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");

for (Map.Entry<Integer, String> entry : map.entrySet()) {


System.out.println(entry.getKey() + " : " + entry.getValue());
}
}
}

340. Using Vector

java

import java.util.*;

public class VectorExample {


public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Java");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 162/250
vector.add("Python");
vector.add("C++");

for (String language : vector) {


System.out.println(language);
}
}
}

341. Using Stack

java

import java.util.*;

public class StackExample {


public static void main(String[] args) {
Stack<String> stack = new Stack<>();
stack.push("Java");
stack.push("Python");
stack.push("C++");

while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}

342. Using PriorityQueue

java

import java.util.*;

public class PriorityQueueExample {


public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.add(10);
pq.add(5);
pq.add(20);
pq.add(15);

while (!pq.isEmpty()) {
System.out.println(pq.poll()); // Retrieves and removes the smallest elemen
t
}
}
}

343. Using Iterator

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 163/250
java

import java.util.*;

public class IteratorExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

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


while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}

344. Using ListIterator

java

import java.util.*;

public class ListIteratorExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

ListIterator<String> listIterator = list.listIterator();


while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}

// Traversing in reverse order


while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
}
}

345. Using Collections.sort()

java

import java.util.*;

public class CollectionsSortExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 164/250
Collections.sort(list); // Sorting the list

for (String language : list) {


System.out.println(language);
}
}
}

346. Using Collections.reverse()

java

import java.util.*;

public class CollectionsReverseExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

Collections.reverse(list); // Reversing the list

for (String language : list) {


System.out.println(language);
}
}
}

347. Using Collections.max() and Collections.min()

java

import java.util.*;

public class CollectionsMaxMinExample {


public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(5);
list.add(20);
list.add(15);

System.out.println("Max: " + Collections.max(list));


System.out.println("Min: " + Collections.min(list));
}
}

348. Using Collections.swap()

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 165/250
java

import java.util.*;

public class CollectionsSwapExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

Collections.swap(list, 0, 2); // Swapping elements

for (String language : list) {


System.out.println(language);
}
}
}

349. Using Collections.fill()

java

import java.util.*;

public class CollectionsFillExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

Collections.fill(list, "Filled"); // Filling the list with a single value

for (String language : list) {


System.out.println(language);
}
}
}

350. Using Map.Entry Interface

java

import java.util.*;

public class MapEntryExample {


public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");

for (Map.Entry<Integer, String> entry : map.entrySet()) {


System.out.println(entry.getKey() + " : " + entry.getValue());
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 166/250
}
}

These programs demonstrate how to use different Java Collection classes and interfaces, including:

List, Set, Map interfaces


ArrayList, LinkedList, HashSet, TreeSet, HashMap, LinkedHashMap, and TreeMap classes
Stack, Vector, PriorityQueue
Iterator, ListIterator
Collections utility class methods

Let me know if you need more examples or clarifications!

Here are different types of programs across various Java topics that cover a wide range of
concepts, from basic to advanced:

351. Palindrome Number Check

java

import java.util.*;

public class PalindromeNumber {


public static void main(String[] args) {
int number = 121, reversed = 0, remainder, original;
original = number;

while (number != 0) {
remainder = number % 10;
reversed = reversed * 10 + remainder;
number /= 10;
}

if (original == reversed)
System.out.println(original + " is a palindrome.");
else
System.out.println(original + " is not a palindrome.");
}
}

352. Prime Number Check

java

import java.util.*;

public class PrimeNumberCheck {


public static void main(String[] args) {
int number = 29;
boolean flag = false;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 167/250
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
flag = true;
break;
}
}

if (!flag)
System.out.println(number + " is a prime number.");
else
System.out.println(number + " is not a prime number.");
}
}

353. Fibonacci Series

java

import java.util.*;

public class FibonacciSeries {


public static void main(String[] args) {
int n = 10;
int a = 0, b = 1, c;

System.out.print(a + " " + b);

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


c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
}
}

354. Factorial of a Number

java

import java.util.*;

public class Factorial {


public static void main(String[] args) {
int number = 5, factorial = 1;

for (int i = 1; i <= number; i++) {


factorial *= i;
}

System.out.println("Factorial of " + number + " is " + factorial);


}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 168/250
355. Armstrong Number Check

java

import java.util.*;

public class ArmstrongNumber {


public static void main(String[] args) {
int number = 153, sum = 0, temp, remainder, n = 0;
temp = number;

while (temp != 0) {
temp /= 10;
++n;
}

temp = number;
while (temp != 0) {
remainder = temp % 10;
sum += Math.pow(remainder, n);
temp /= 10;
}

if (sum == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}

356. Reverse a String

java

import java.util.*;

public class ReverseString {


public static void main(String[] args) {
String str = "Java";
String reversed = "";

for (int i = str.length() - 1; i >= 0; i--) {


reversed += str.charAt(i);
}

System.out.println("Reversed String: " + reversed);


}
}

357. Swap Two Numbers Using a Third Variable

java

import java.util.*;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 169/250
public class SwapNumbers {
public static void main(String[] args) {
int a = 5, b = 10;

System.out.println("Before Swap: a = " + a + ", b = " + b);

int temp = a;
a = b;
b = temp;

System.out.println("After Swap: a = " + a + ", b = " + b);


}
}

358. Swap Two Numbers Without Using a Third Variable

java

import java.util.*;

public class SwapWithoutTemp {


public static void main(String[] args) {
int a = 5, b = 10;

System.out.println("Before Swap: a = " + a + ", b = " + b);

a = a + b;
b = a - b;
a = a - b;

System.out.println("After Swap: a = " + a + ", b = " + b);


}
}

359. Count Vowels and Consonants in a String

java

import java.util.*;

public class CountVowelsConsonants {


public static void main(String[] args) {
String str = "Java Programming";
int vowels = 0, consonants = 0;

str = str.toLowerCase();

for (int i = 0; i < str.length(); i++) {


char ch = str.charAt(i);

if (ch >= 'a' && ch <= 'z') {


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
else
consonants++;
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 170/250
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
}
}

360. Sum of Natural Numbers

java

import java.util.*;

public class SumOfNaturalNumbers {


public static void main(String[] args) {
int n = 10;
int sum = 0;

for (int i = 1; i <= n; i++) {


sum += i;
}

System.out.println("Sum of first " + n + " natural numbers is " + sum);


}
}

361. Count Digits in a Number

java

import java.util.*;

public class CountDigits {


public static void main(String[] args) {
int number = 12345, count = 0;

while (number != 0) {
number /= 10;
count++;
}

System.out.println("Number of digits: " + count);


}
}

362. Sum of Digits of a Number

java

import java.util.*;

public class SumOfDigits {


public static void main(String[] args) {
int number = 12345, sum = 0;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 171/250
while (number != 0) {
sum += number % 10;
number /= 10;
}

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


}
}

363. Sum of N Numbers Using Recursion

java

import java.util.*;

public class SumUsingRecursion {


public static void main(String[] args) {
int n = 5;
System.out.println("Sum of first " + n + " numbers is " + sum(n));
}

static int sum(int n) {


if (n != 0)
return n + sum(n - 1);
else
return 0;
}
}

364. GCD of Two Numbers

java

import java.util.*;

public class GCD {


public static void main(String[] args) {
int num1 = 56, num2 = 98;
int gcd = 1;

for (int i = 1; i <= num1 && i <= num2; i++) {


if (num1 % i == 0 && num2 % i == 0)
gcd = i;
}

System.out.println("GCD of " + num1 + " and " + num2 + " is " + gcd);
}
}

365. LCM of Two Numbers

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 172/250
java

import java.util.*;

public class LCM {


public static void main(String[] args) {
int num1 = 15, num2 = 20;
int lcm = (num1 > num2) ? num1 : num2;

while (true) {
if (lcm % num1 == 0 && lcm % num2 == 0) {
System.out.println("LCM of " + num1 + " and " + num2 + " is " + lcm);
break;
}
lcm++;
}
}
}

366. Find the Largest of Three Numbers

java

import java.util.*;

public class LargestOfThree {


public static void main(String[] args) {
int num1 = 10, num2 = 20, num3 = 30;

if (num1 >=

Here are some additional different types of programs using Java Collections, covering more
advanced usage and operations:

351. Iterating through a Set using For-Each

java

import java.util.*;

public class SetIterationExample {


public static void main(String[] args) {
Set<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("C++");

for (String language : set) {


System.out.println(language);
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 173/250
352. Using ArrayList to Store Objects

java

import java.util.*;

class Person {
String name;
int age;

Person(String name, int age) {


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

@Override
public String toString() {
return name + " (" + age + " years)";
}
}

public class ArrayListObjectsExample {


public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>();
people.add(new Person("John", 25));
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 35));

for (Person person : people) {


System.out.println(person);
}
}
}

353. Using Map with Lambda Expressions

java

import java.util.*;

public class MapLambdaExample {


public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Java");
map.put(2, "Python");
map.put(3, "C++");

map.forEach((key, value) -> {


System.out.println(key + " : " + value);
});
}
}

354. Using LinkedList as a Stack

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 174/250
java

import java.util.*;

public class LinkedListStackExample {


public static void main(String[] args) {
LinkedList<String> stack = new LinkedList<>();
stack.push("Java");
stack.push("Python");
stack.push("C++");

System.out.println("Stack elements:");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}

355. Sorting a List of Custom Objects

java

import java.util.*;

class Student implements Comparable<Student> {


String name;
int grade;

Student(String name, int grade) {


this.name = name;
this.grade = grade;
}

@Override
public int compareTo(Student other) {
return this.grade - other.grade; // Sorting by grade
}

@Override
public String toString() {
return name + " (" + grade + ")";
}
}

public class SortCustomObjectsExample {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 85));
students.add(new Student("Bob", 90));
students.add(new Student("John", 80));

Collections.sort(students);

for (Student student : students) {


System.out.println(student);
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 175/250
356. Using Comparator for Custom Sorting

java

import java.util.*;

class Employee {
String name;
double salary;

Employee(String name, double salary) {


this.name = name;
this.salary = salary;
}

@Override
public String toString() {
return name + " ($" + salary + ")";
}
}

class EmployeeSalaryComparator implements Comparator<Employee> {


@Override
public int compare(Employee e1, Employee e2) {
return Double.compare(e1.salary, e2.salary); // Sorting by salary
}
}

public class ComparatorExample {


public static void main(String[] args) {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee("Alice", 70000));
employees.add(new Employee("Bob", 80000));
employees.add(new Employee("John", 60000));

Collections.sort(employees, new EmployeeSalaryComparator());

for (Employee employee : employees) {


System.out.println(employee);
}
}
}

357. Finding Maximum/Minimum in a List

java

import java.util.*;

public class MaxMinListExample {


public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 5, 50, 30);

System.out.println("Max value: " + Collections.max(list));


System.out.println("Min value: " + Collections.min(list));
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 176/250
358. Using LinkedHashSet to Maintain Insertion Order

java

import java.util.*;

public class LinkedHashSetExample {


public static void main(String[] args) {
Set<String> set = new LinkedHashSet<>();
set.add("Java");
set.add("Python");
set.add("C++");

for (String language : set) {


System.out.println(language); // Maintains insertion order
}
}
}

359. Using Collections.shuffle()

java

import java.util.*;

public class CollectionsShuffleExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

Collections.shuffle(list); // Shuffling the list randomly

for (String language : list) {


System.out.println(language);
}
}
}

360. Using Collections.swap() to Swap Two Elements

java

import java.util.*;

public class CollectionsSwapExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

Collections.swap(list, 0, 2); // Swap first and last element

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 177/250
for (String language : list) {
System.out.println(language);
}
}
}

361. Removing Duplicates Using Set

java

import java.util.*;

public class RemoveDuplicatesExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");
list.add("Java"); // Duplicate entry

Set<String> set = new HashSet<>(list); // Removing duplicates by converting to


Set

for (String language : set) {


System.out.println(language);
}
}
}

362. Using TreeSet to Store Sorted Data

java

import java.util.*;

public class TreeSetSortedExample {


public static void main(String[] args) {
Set<String> set = new TreeSet<>();
set.add("Java");
set.add("Python");
set.add("C++");
set.add("Java"); // Duplicate will be ignored

for (String language : set) {


System.out.println(language); // Sorted order
}
}
}

363. Using ArrayList with Dynamic Size

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 178/250
java

import java.util.*;

public class DynamicArrayListExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");

list.add("C++"); // Adding more elements dynamically


list.add("JavaScript");

System.out.println("Size of the list: " + list.size());


for (String language : list) {
System.out.println(language);
}
}
}

364. Copying One List to Another

java

import java.util.*;

public class ListCopyExample {


public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("Java");
list1.add("Python");

List<String> list2 = new ArrayList<>(list1); // Copying list1 to list2

for (String language : list2) {


System.out.println(language);
}
}
}

365. Using Collections.rotate()

java

import java.util.*;

public class CollectionsRotateExample {


public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

Collections.rotate(list, 1); // Rotates the list by 1 position

for (String language : list) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 179/250
System.out.println(language);
}
}
}

These programs demonstrate various functionalities of Java Collections, such as:

Sorting, Shuffling, Reversing


Copying, Removing duplicates
Working with Custom Comparators, Lambda expressions
Set, List, Map usage and different types of Collection classes

Let me know if you need more examples or specific topics!

Here are some Java File Handling programs, covering common file operations such as reading,
writing, and manipulating files:

366. Writing to a File

java

import java.io.*;

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt");
writer.write("Hello, this is a test file.");
writer.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

367. Reading from a File

java

import java.io.*;

public class ReadFromFile {


public static void main(String[] args) {
try {
FileReader reader = new FileReader("example.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 180/250
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

368. Appending Text to a File

java

import java.io.*;

public class AppendToFile {


public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("example.txt", true); // true for append
ing
writer.write("\nThis text is appended to the file.");
writer.close();
System.out.println("Successfully appended to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

369. Reading a File Line by Line

java

import java.io.*;

public class ReadLineByLine {


public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

370. Writing to a File Using BufferedWriter

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 181/250
java

import java.io.*;

public class WriteUsingBufferedWriter {


public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));
writer.write("This is written using BufferedWriter.");
writer.newLine(); // Adding a new line
writer.write("BufferedWriter is more efficient.");
writer.close();
System.out.println("Successfully wrote to the file using BufferedWriter.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

371. Copying File Contents

java

import java.io.*;

public class CopyFile {


public static void main(String[] args) {
try {
FileInputStream source = new FileInputStream("example.txt");
FileOutputStream destination = new FileOutputStream("copy_example.txt");

int byteData;
while ((byteData = source.read()) != -1) {
destination.write(byteData);
}

source.close();
destination.close();
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

372. File Existence Check

java

import java.io.*;

public class CheckFileExistence {


public static void main(String[] args) {
File file = new File("example.txt");

if (file.exists()) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 182/250
System.out.println("File exists.");
} else {
System.out.println("File does not exist.");
}
}
}

373. Deleting a File

java

import java.io.*;

public class DeleteFile {


public static void main(String[] args) {
File file = new File("example.txt");

if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}
}

374. Listing Files in a Directory

java

import java.io.*;

public class ListFilesInDirectory {


public static void main(String[] args) {
File directory = new File("path_to_directory"); // Provide the directory path
String[] files = directory.list();

if (files != null) {
for (String file : files) {
System.out.println(file);
}
} else {
System.out.println("The directory is empty or not found.");
}
}
}

375. Creating a Directory

java

import java.io.*;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 183/250
public class CreateDirectory {
public static void main(String[] args) {
File directory = new File("new_directory");

if (directory.mkdir()) {
System.out.println("Directory created successfully.");
} else {
System.out.println("Failed to create the directory.");
}
}
}

376. File Information (Size, Last Modified)

java

import java.io.*;

public class FileInfo {


public static void main(String[] args) {
File file = new File("example.txt");

if (file.exists()) {
System.out.println("File Size: " + file.length() + " bytes");
System.out.println("Last Modified: " + new java.util.Date(file.lastModified
()));
} else {
System.out.println("File not found.");
}
}
}

377. Writing Multiple Lines to a File

java

import java.io.*;

public class WriteMultipleLines {


public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt"));
writer.write("First line of text.");
writer.newLine();
writer.write("Second line of text.");
writer.newLine();
writer.write("Third line of text.");
writer.close();
System.out.println("Successfully wrote multiple lines to the file.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 184/250
378. Random Access File (Reading and Writing)

java

import java.io.*;

public class RandomAccessFileExample {


public static void main(String[] args) {
try {
RandomAccessFile file = new RandomAccessFile("example.txt", "rw");

file.writeUTF("Hello, this is a test.");


file.seek(0);
String text = file.readUTF();
System.out.println("Read from file: " + text);

file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

379. File Copy Using Buffered Streams

java

import java.io.*;

public class BufferedFileCopy {


public static void main(String[] args) {
try {
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStrea
m("example.txt"));
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputS
tream("copy_example.txt"));

int byteData;
while ((byteData = inputStream.read()) != -1) {
outputStream.write(byteData);
}

inputStream.close();
outputStream.close();
System.out.println("File copied using buffered streams.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

380. Reading a File with FileReader and BufferedReader

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 185/250
java

import java.io.*;

public class FileReaderBufferedReaderExample {


public static void main(String[] args) {
try {
FileReader reader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(reader);

String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

381. Reading File with Scanner

java

import java.io.*;
import java.util.*;

public class FileScannerExample {


public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("example.txt"));

while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}

scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

382. Writing to a File Using PrintWriter

java

import java.io.*;

public class WriteUsingPrintWriter {


public static void main(String[] args) {
try {
PrintWriter writer = new PrintWriter(new FileWriter("example.txt"));
writer.println("This is written using PrintWriter.");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 186/250
writer.println("It is easy to write formatted data.");
writer.close();
System.out.println("Successfully wrote to the file using PrintWriter.");
} catch (IOException e) {
e.printStackTrace();
}
}
}

These are some examples of common file operations in Java, such as creating, reading, writing,
copying, and deleting files, as well as working with different file handling classes like `File`,
`FileReader`, `BufferedReader`, `FileWriter`, `PrintWriter`, `RandomAccessFile`, and `Scanner`.

Let me know if you need more information or additional examples!

Here are some Java programs focused on Recursion, covering a variety of common recursive
problems:

383. Factorial of a Number

java

public class Factorial {


public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}

public static void main(String[] args) {


int number = 5;
System.out.println("Factorial of " + number + " is " + factorial(number));
}
}

384. Fibonacci Sequence

java

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) {


int number = 6;
System.out.println("Fibonacci number at position " + number + " is " + fibonacci
(number));
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 187/250
}
}

385. Sum of Natural Numbers

java

public class SumOfNaturalNumbers {


public static int sum(int n) {
if (n <= 1) {
return n;
}
return n + sum(n - 1);
}

public static void main(String[] args) {


int number = 10;
System.out.println("Sum of first " + number + " natural numbers is " + sum(numbe
r));
}
}

386. Reverse a String Using Recursion

java

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) {


String input = "hello";
System.out.println("Reversed string: " + reverse(input));
}
}

387. Power of a Number

java

public class PowerOfNumber {


public static int power(int base, int exp) {
if (exp == 0) {
return 1;
}
return base * power(base, exp - 1);
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 188/250
public static void main(String[] args) {
int base = 2, exp = 3;
System.out.println("Power: " + base + "^" + exp + " = " + power(base, exp));
}
}

388. Palindrome Check Using Recursion

java

public class Palindrome {


public static boolean isPalindrome(String str, int start, int end) {
if (start >= end) {
return true;
}
if (str.charAt(start) != str.charAt(end)) {
return false;
}
return isPalindrome(str, start + 1, end - 1);
}

public static void main(String[] args) {


String str = "racecar";
System.out.println("Is palindrome: " + isPalindrome(str, 0, str.length() - 1));
}
}

389. Greatest Common Divisor (GCD)

java

public class GCD {


public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}

public static void main(String[] args) {


int num1 = 56, num2 = 98;
System.out.println("GCD of " + num1 + " and " + num2 + " is " + gcd(num1, num
2));
}
}

390. Sum of Array Elements Using Recursion

java

public class SumArray {


public static int sum(int[] arr, int n) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 189/250
if (n <= 0) {
return 0;
}
return sum(arr, n - 1) + arr[n - 1];
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5};
System.out.println("Sum of array elements: " + sum(arr, arr.length));
}
}

391. Count the Number of Digits in a Number

java

public class CountDigits {


public static int countDigits(int n) {
if (n == 0) {
return 0;
}
return 1 + countDigits(n / 10);
}

public static void main(String[] args) {


int number = 12345;
System.out.println("Number of digits in " + number + " is " + countDigits(numbe
r));
}
}

392. Tower of Hanoi

java

public class TowerOfHanoi {


public static void towerOfHanoi(int n, char source, char auxiliary, char target) {
if (n == 1) {
System.out.println("Move disk 1 from " + source + " to " + target);
return;
}
towerOfHanoi(n - 1, source, target, auxiliary);
System.out.println("Move disk " + n + " from " + source + " to " + target);
towerOfHanoi(n - 1, auxiliary, source, target);
}

public static void main(String[] args) {


int disks = 3;
towerOfHanoi(disks, 'A', 'B', 'C');
}
}

393. Sum of Digits of a Number

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 190/250
java

public class SumOfDigits {


public static int sumDigits(int n) {
if (n == 0) {
return 0;
}
return n % 10 + sumDigits(n / 10);
}

public static void main(String[] args) {


int number = 12345;
System.out.println("Sum of digits of " + number + " is " + sumDigits(number));
}
}

394. Find the Nth Fibonacci Number Using Recursion

java

public class NthFibonacci {


public static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}

public static void main(String[] args) {


int number = 8;
System.out.println("Fibonacci number at position " + number + " is " + fibonacci
(number));
}
}

395. Reverse an Array Using Recursion

java

public class ReverseArray {


public static void reverseArray(int[] arr, int start, int end) {
if (start >= end) {
return;
}
// Swap the elements
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;

reverseArray(arr, start + 1, end - 1);


}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5};
reverseArray(arr, 0, arr.length - 1);
System.out.print("Reversed Array: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 191/250
for (int num : arr) {
System.out.print(num + " ");
}
}
}

396. Sum of Even Numbers in an Array Using Recursion

java

public class SumEvenNumbers {


public static int sumEven(int[] arr, int n) {
if (n == 0) {
return 0;
}
int sum = (arr[n - 1] % 2 == 0) ? arr[n - 1] : 0;
return sum + sumEven(arr, n - 1);
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5};
System.out.println("Sum of even numbers: " + sumEven(arr, arr.length));
}
}

397. Sum of Odd Numbers in an Array Using Recursion

java

public class SumOddNumbers {


public static int sumOdd(int[] arr, int n) {
if (n == 0) {
return 0;
}
int sum = (arr[n - 1] % 2 != 0) ? arr[n - 1] : 0;
return sum + sumOdd(arr, n - 1);
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5};
System.out.println("Sum of odd numbers: " + sumOdd(arr, arr.length));
}
}

398. Find Maximum Element in an Array Using Recursion

java

public class MaxElement {


public static int findMax(int[] arr, int n) {
if (n == 1) {
return arr[0];

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 192/250
}
return Math.max(arr[n - 1], findMax(arr, n - 1));
}

public static void main(String[] args) {


int[] arr = {1, 5, 3, 9, 2};
System.out.println("Maximum element in the array: " + findMax(arr, arr.length));
}
}

399. Print All Substrings of a String

java

public class PrintSubstrings {


public static void printSubstrings(String str, int start, int end) {
if (end == str.length()) {
return;
}
if (start == end) {
printSubstrings(str, start + 1, end);
} else {
System.out.println(str.substring(start, end));
printSubstrings(str, start, end + 1);
}
}

public static void main(String[] args) {


String str = "abc";
printSubstrings(str, 0, 1);
}
}

400. Print All Permutations of a String

java

public class StringPermutations {


public static void permute(String str, String answer) {
if (str.length() == 0) {
System.out.println(answer);
return;
}
for (int i = 0; i < str.length(); i++) {
char currentChar = str.charAt(i);
String leftSubstring = str.substring(0, i);
String rightSubstring = str.substring(i + 1);
permute(leftSubstring + rightSubstring, answer + currentChar);
}
}

public static void main(String[] args) {


String str = "abc";
permute(str, "");
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 193/250
These are examples of common recursion problems in Java. Let me know if you need additional
explanations or more examples!

Here are additional Java programs focusing on Recursion:

401. Decimal to Binary Conversion

java

public class DecimalToBinary {


public static void decimalToBinary(int n) {
if (n <= 1) {
System.out.print(n);
return;
}
decimalToBinary(n / 2);
System.out.print(n % 2);
}

public static void main(String[] args) {


int number = 10;
System.out.print("Binary representation of " + number + " is ");
decimalToBinary(number);
}
}

402. Decimal to Hexadecimal Conversion

java

public class DecimalToHexadecimal {


public static void decimalToHex(int n) {
if (n == 0) {
return;
}
decimalToHex(n / 16);
int remainder = n % 16;
if (remainder < 10) {
System.out.print(remainder);
} else {
char hexChar = (char) ('A' + (remainder - 10));
System.out.print(hexChar);
}
}

public static void main(String[] args) {


int number = 255;
System.out.print("Hexadecimal representation of " + number + " is ");
decimalToHex(number);
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 194/250
403. Find the Length of a String Using Recursion

java

public class StringLength {


public static int length(String str) {
if (str.isEmpty()) {
return 0;
}
return 1 + length(str.substring(1));
}

public static void main(String[] args) {


String str = "Hello, World!";
System.out.println("Length of the string is: " + length(str));
}
}

404. Find the Minimum Element in an Array Using Recursion

java

public class MinElement {


public static int findMin(int[] arr, int n) {
if (n == 1) {
return arr[0];
}
return Math.min(arr[n - 1], findMin(arr, n - 1));
}

public static void main(String[] args) {


int[] arr = {3, 5, 7, 2, 8, 1};
System.out.println("Minimum element in the array is: " + findMin(arr, arr.lengt
h));
}
}

405. Count the Number of Occurrences of a Character in a String

java

public class CountOccurrences {


public static int countOccurrences(String str, char ch, int index) {
if (index == str.length()) {
return 0;
}
int count = (str.charAt(index) == ch) ? 1 : 0;
return count + countOccurrences(str, ch, index + 1);
}

public static void main(String[] args) {


String str = "programming";
char ch = 'r';
System.out.println("The character '" + ch + "' appears " + countOccurrences(str,
ch, 0) + " times.");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 195/250
}
}

406. Reverse an Integer Using Recursion

java

public class ReverseInteger {


public static int reverse(int num, int rev) {
if (num == 0) {
return rev;
}
return reverse(num / 10, rev * 10 + num % 10);
}

public static void main(String[] args) {


int number = 12345;
System.out.println("Reversed number is: " + reverse(number, 0));
}
}

407. Reverse a Linked List Using Recursion

java

class Node {
int data;
Node next;

Node(int data) {
this.data = data;
this.next = null;
}
}

public class ReverseLinkedList {


public static Node reverse(Node head) {
if (head == null || head.next == null) {
return head;
}
Node rest = reverse(head.next);
head.next.next = head;
head.next = null;
return rest;
}

public static void printList(Node head) {


Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}

public static void main(String[] args) {


Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 196/250
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);

System.out.print("Original List: ");


printList(head);

head = reverse(head);

System.out.print("\nReversed List: ");


printList(head);
}
}

408. Print All Prime Numbers Up to N Using Recursion

java

public class PrimeNumbers {


public static void printPrimes(int n, int i) {
if (i > n) {
return;
}
if (isPrime(i, 2)) {
System.out.print(i + " ");
}
printPrimes(n, i + 1);
}

public static boolean isPrime(int n, int i) {


if (n <= 2) {
return n == 2;
}
if (n % i == 0) {
return false;
}
if (i * i > n) {
return true;
}
return isPrime(n, i + 1);
}

public static void main(String[] args) {


int number = 20;
System.out.print("Prime numbers up to " + number + ": ");
printPrimes(number, 2);
}
}

409. Print All Subsets of a Set

java

import java.util.*;

public class Subsets {


public static void printSubsets(String str, String ans, int index) {
if (index == str.length()) {
System.out.println(ans);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 197/250
return;
}
printSubsets(str, ans, index + 1);
printSubsets(str, ans + str.charAt(index), index + 1);
}

public static void main(String[] args) {


String str = "abc";
System.out.println("Subsets of the string are: ");
printSubsets(str, "", 0);
}
}

410. Find the Sum of All Elements in an Array Using Recursion

java

public class SumArrayElements {


public static int sum(int[] arr, int n) {
if (n == 0) {
return 0;
}
return arr[n - 1] + sum(arr, n - 1);
}

public static void main(String[] args) {


int[] arr = {1, 2, 3, 4, 5};
System.out.println("Sum of all elements in the array is: " + sum(arr, arr.lengt
h));
}
}

411. Check if a Number is Prime Using Recursion

java

public class PrimeCheck {


public static boolean isPrime(int n, int i) {
if (n <= 2) {
return n == 2;
}
if (n % i == 0) {
return false;
}
if (i * i > n) {
return true;
}
return isPrime(n, i + 1);
}

public static void main(String[] args) {


int number = 29;
System.out.println("Is " + number + " prime? " + isPrime(number, 2));
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 198/250
412. Print All Permutations of a String Using Recursion

java

public class Permutations {


public static void permute(String str, String ans) {
if (str.length() == 0) {
System.out.println(ans);
return;
}
for (int i = 0; i < str.length(); i++) {
char currentChar = str.charAt(i);
String left = str.substring(0, i);
String right = str.substring(i + 1);
permute(left + right, ans + currentChar);
}
}

public static void main(String[] args) {


String str = "abc";
permute(str, "");
}
}

These examples demonstrate how recursion can be applied to a wide range of problems. Let me
know if you need more examples or further clarification!

Here are Java programs focused on advanced topics:

413. Implementing Custom Exception Handling

java

class InsufficientBalanceException extends Exception {


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

public class BankAccount {


private double balance;

public BankAccount(double balance) {


this.balance = balance;
}

public void withdraw(double amount) throws InsufficientBalanceException {


if (amount > balance) {
throw new InsufficientBalanceException("Insufficient balance for withdrawa
l.");
}
balance -= amount;
System.out.println("Withdrawal successful! New balance: " + balance);
}

public static void main(String[] args) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 199/250
BankAccount account = new BankAccount(500);
try {
account.withdraw(600);
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}
}
}

414. Multithreading - Creating a Thread Using the Runnable Interface

java

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running!");
}
}

public class ThreadExample {


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

415. Synchronization in Multithreading

java

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

public class SynchronizedExample {


public static void main(String[] args) {
Counter counter = new Counter();

Runnable task = () -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
};

Thread thread1 = new Thread(task);


Thread thread2 = new Thread(task);

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

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 200/250
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

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


}
}

416. Lambda Expression Example

java

import java.util.Arrays;
import java.util.List;

public class LambdaExample {


public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
}
}

417. Functional Interface Example

java

@FunctionalInterface
interface MyFunctionalInterface {
void sayHello();
}

public class FunctionalInterfaceExample {


public static void main(String[] args) {
MyFunctionalInterface hello = () -> System.out.println("Hello, world!");
hello.sayHello();
}
}

418. Using Streams in Java

java

import java.util.*;
import java.util.stream.*;

public class StreamExample {


public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 201/250
int sum = numbers.stream().filter(n -> n % 2 == 0).mapToInt(Integer::intValue).s
um();
System.out.println("Sum of even numbers: " + sum);
}
}

419. Generics - Creating a Generic Class

java

class Box<T> {
private T value;

public void setValue(T value) {


this.value = value;
}

public T getValue() {
return value;
}
}

public class GenericClassExample {


public static void main(String[] args) {
Box<Integer> integerBox = new Box<>();
integerBox.setValue(10);
System.out.println("Integer value: " + integerBox.getValue());

Box<String> stringBox = new Box<>();


stringBox.setValue("Hello Generics!");
System.out.println("String value: " + stringBox.getValue());
}
}

420. Reflection - Accessing Methods Dynamically

java

import java.lang.reflect.Method;

public class ReflectionExample {


public void displayMessage() {
System.out.println("Hello from Reflection!");
}

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


ReflectionExample obj = new ReflectionExample();
Method method = obj.getClass().getMethod("displayMessage");
method.invoke(obj);
}
}

421. Serialization in Java

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 202/250
java

import java.io.*;

class Student implements Serializable {


private String name;
private int age;

public Student(String name, int age) {


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

@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
}

public class SerializationExample {


public static void main(String[] args) {
Student student = new Student("John", 21);

try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("stude


nt.ser"))) {
oos.writeObject(student);
System.out.println("Student object serialized to student.ser");
} catch (IOException e) {
e.printStackTrace();
}

try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.


ser"))) {
Student deserializedStudent = (Student) ois.readObject();
System.out.println("Deserialized Student: " + deserializedStudent);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

422. Using File I/O in Java

java

import java.io.*;

public class FileIOExample {


public static void main(String[] args) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt")))
{
writer.write("This is an example of file I/O in Java.");
System.out.println("Data written to file.");
} catch (IOException e) {
e.printStackTrace();
}

try (BufferedReader reader = new BufferedReader(new FileReader("example.txt")))


{
String line = reader.readLine();
System.out.println("Read from file: " + line);
} catch (IOException e) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 203/250
e.printStackTrace();
}
}
}

423. Java 8 Optional Class

java

import java.util.Optional;

public class OptionalExample {


public static void main(String[] args) {
String str = "Hello, Optional!";
Optional<String> optionalStr = Optional.ofNullable(str);

optionalStr.ifPresent(System.out::println);

String result = optionalStr.orElse("Default Value");


System.out.println(result);
}
}

424. CompletableFuture for Asynchronous Programming

java

import java.util.concurrent.CompletableFuture;

public class CompletableFutureExample {


public static void main(String[] args) {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 42;
});

future.thenAccept(result -> System.out.println("Result: " + result));


System.out.println("Async task is running in the background...");
}
}

425. Implementing a Singleton Design Pattern

java

public class Singleton {


private static Singleton instance;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 204/250
private Singleton() {
// Private constructor to prevent instantiation
}

public static Singleton getInstance() {


if (instance == null) {
instance = new Singleton();
}
return instance;
}

public void showMessage() {


System.out.println("Singleton instance!");
}

public static void main(String[] args) {


Singleton singleton = Singleton.getInstance();
singleton.showMessage();
}
}

These programs cover a variety of advanced topics like multithreading, functional programming,
serialization, reflection, file I/O, and design patterns. Let me know if you need further explanation or
more examples!

Here are additional advanced Java program examples:

426. Implementing a Simple HTTP Server Using Java

java

import java.io.*;
import java.net.*;

public class SimpleHttpServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server started at port 8080");

while (true) {
Socket clientSocket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocke
t.getInputStream()));
OutputStreamWriter writer = new OutputStreamWriter(clientSocket.getOutputStr
eam());

String requestLine = reader.readLine();


System.out.println("Received request: " + requestLine);

writer.write("HTTP/1.1 200 OK\r\n");


writer.write("Content-Type: text/html\r\n");
writer.write("\r\n");
writer.write("<html><body><h1>Hello, World!</h1></body></html>");
writer.flush();
clientSocket.close();
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 205/250
}
}

427. Implementing a Simple Database Connection with JDBC

java

import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "password";

try (Connection connection = DriverManager.getConnection(url, user, password)) {


System.out.println("Connected to the database");

Statement statement = connection.createStatement();


String query = "SELECT * FROM students";
ResultSet resultSet = statement.executeQuery(query);

while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + result
Set.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

428. Implementing a Priority Queue in Java

java

import java.util.PriorityQueue;

public class PriorityQueueExample {


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

pq.offer(5);
pq.offer(2);
pq.offer(8);
pq.offer(1);

while (!pq.isEmpty()) {
System.out.println(pq.poll());
}
}
}

429. Implementing a Simple Chat Application Using Sockets


Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 206/250
java

import java.io.*;
import java.net.*;

public class ChatServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(12345);
System.out.println("Server started...");

Socket clientSocket = serverSocket.accept();


System.out.println("Client connected");

BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.ge


tInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);

String message;
while ((message = reader.readLine()) != null) {
System.out.println("Client: " + message);
writer.println("Echo: " + message);
}
}
}

class ChatClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 12345);
BufferedReader consoleReader = new BufferedReader(new InputStreamReader(System.i
n));
BufferedReader socketReader = new BufferedReader(new InputStreamReader(socket.ge
tInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

String message;
while ((message = consoleReader.readLine()) != null) {
writer.println(message);
System.out.println("Server: " + socketReader.readLine());
}
}
}

430. Implementing a Timer Using the Timer Class

java

import java.util.*;

public class TimerExample {


public static void main(String[] args) {
Timer timer = new Timer();

TimerTask task = new TimerTask() {


public void run() {
System.out.println("Task executed at: " + new Date());
}
};

timer.scheduleAtFixedRate(task, 0, 2000);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 207/250
}
}

431. Implementing a Circular Queue

java

class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;

public CircularQueue(int capacity) {


this.capacity = capacity;
queue = new int[capacity];
front = rear = size = 0;
}

public void enqueue(int item) {


if (size == capacity) {
System.out.println("Queue is full");
return;
}
queue[rear] = item;
rear = (rear + 1) % capacity;
size++;
}

public void dequeue() {


if (size == 0) {
System.out.println("Queue is empty");
return;
}
front = (front + 1) % capacity;
size--;
}

public void display() {


if (size == 0) {
System.out.println("Queue is empty");
return;
}
int i = front;
while (i != rear) {
System.out.print(queue[i] + " ");
i = (i + 1) % capacity;
}
System.out.println();
}
}

public class CircularQueueExample {


public static void main(String[] args) {
CircularQueue queue = new CircularQueue(5);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.display();

queue.dequeue();
queue.display();

queue.enqueue(40);
queue.enqueue(50);
queue.display();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 208/250
}
}

432. Implementing a Simple Calculator Using JavaFX (GUI)

java

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;

public class Calculator extends Application {


private TextField display;

public static void main(String[] args) {


launch(args);
}

@Override
public void start(Stage stage) {
display = new TextField();
display.setEditable(false);

Button btn1 = new Button("1");


Button btn2 = new Button("2");
Button btn3 = new Button("3");
Button btn4 = new Button("4");
Button btn5 = new Button("5");
Button btn6 = new Button("6");
Button btn7 = new Button("7");
Button btn8 = new Button("8");
Button btn9 = new Button("9");
Button btn0 = new Button("0");
Button btnAdd = new Button("+");
Button btnSub = new Button("-");
Button btnMul = new Button("*");
Button btnDiv = new Button("/");
Button btnEq = new Button("=");
Button btnClear = new Button("C");

btn1.setOnAction(e -> display.appendText("1"));


btn2.setOnAction(e -> display.appendText("2"));
btn3.setOnAction(e -> display.appendText("3"));
btn4.setOnAction(e -> display.appendText("4"));
btn5.setOnAction(e -> display.appendText("5"));
btn6.setOnAction(e -> display.appendText("6"));
btn7.setOnAction(e -> display.appendText("7"));
btn8.setOnAction(e -> display.appendText("8"));
btn9.setOnAction(e -> display.appendText("9"));
btn0.setOnAction(e -> display.appendText("0"));

btnClear.setOnAction(e -> display.clear());


btnEq.setOnAction(e -> evaluate());

VBox layout = new VBox();


layout.getChildren().addAll(display, btn1, btn2, btn3, btn4, btn5, btn6, btn7, b
tn8, btn9, btn0, btnAdd, btnSub, btnMul, btnDiv, btnEq, btnClear);

Scene scene = new Scene(layout, 250, 300);


stage.setTitle("Calculator");
stage.setScene(scene);
stage.show();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 209/250
}

private void evaluate() {


try {
double result = evaluateExpression(display.getText());
display.setText(Double.toString(result));
} catch (Exception e) {
display.setText("Error");
}
}

private double evaluateExpression(String expression) {


// Here you can implement basic expression evaluation logic (e.g., using a scrip
t engine or custom code)
return 0; // Placeholder
}
}

433. Implementing Observer Design Pattern

java

import java.util.*;

interface Observer {
void update(String message);
}

class ConcreteObserver implements Observer {


private String name;

public ConcreteObserver(String name) {


this.name = name;
}

public void update(String message) {


System.out.println(name + " received: " + message);
}
}

class Subject {
private List<Observer> observers = new ArrayList<>();

public void addObserver(Observer observer) {


observers.add(observer);
}

public void notifyObservers(String message) {


for (Observer observer : observers) {
observer.update(message);
}
}
}

public class ObserverPatternExample {


public static void main(String[] args) {
Subject subject = new Subject();
Observer observer1 = new ConcreteObserver("Observer 1");
Observer observer2 = new ConcreteObserver("Observer 2");

subject.addObserver(observer1);
subject.addObserver(observer2);

subject.notifyObservers("Update Message");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 210/250
}
}

These advanced programs cover a variety of topics such as networking, multithreading, databases,
GUI, and design patterns. Let me know if you'd like further assistance with any of these concepts!

Here are a few miscellaneous advanced Java programs that cover a wide range of concepts:

434. Palindrome Checker Using Recursion

java

public class PalindromeChecker {


public static void main(String[] args) {
String str = "madam";
if (isPalindrome(str, 0, str.length() - 1)) {
System.out.println(str + " is a palindrome.");
} else {
System.out.println(str + " is not a palindrome.");
}
}

public static boolean isPalindrome(String str, int start, int end) {


if (start >= end) {
return true;
}
if (str.charAt(start) != str.charAt(end)) {
return false;
}
return isPalindrome(str, start + 1, end - 1);
}
}

435. Fibonacci Series Using Memoization

java

import java.util.HashMap;

public class FibonacciMemoization {


private static HashMap<Integer, Long> memo = new HashMap<>();

public static void main(String[] args) {


int n = 50; // Find the 50th Fibonacci number
System.out.println("Fibonacci of " + n + " is: " + fibonacci(n));
}

public static long fibonacci(int n) {


if (n <= 1) {
return n;
}
if (memo.containsKey(n)) {
return memo.get(n);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 211/250
}
long result = fibonacci(n - 1) + fibonacci(n - 2);
memo.put(n, result);
return result;
}
}

436. Implementing a Simple Bank Account System

java

class BankAccount {
private double balance;

public BankAccount(double initialBalance) {


balance = initialBalance;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}

public double getBalance() {


return balance;
}
}

public class BankAccountSystem {


public static void main(String[] args) {
BankAccount account = new BankAccount(1000);
account.deposit(500);
account.withdraw(200);
System.out.println("Current Balance: " + account.getBalance());
}
}

437. Implementing a Sudoku Solver

java

public class SudokuSolver {


private static final int N = 9;

public static void main(String[] args) {


int[][] board = {
{5, 3, 0, 0, 7, 0, 0, 0, 0},
{6, 0, 0, 1, 9, 5, 0, 0, 0},
{0, 9, 8, 0, 0, 0, 0, 6, 0},

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 212/250
{8, 0, 0, 0, 6, 0, 0, 0, 3},
{4, 0, 0, 8, 0, 3, 0, 0, 1},
{7, 0, 0, 0, 2, 0, 0, 0, 6},
{0, 6, 0, 0, 0, 0, 2, 8, 0},
{0, 0, 0, 4, 1, 9, 0, 0, 5},
{0, 0, 0, 0, 8, 0, 0, 7, 9}
};
if (solveSudoku(board)) {
printBoard(board);
} else {
System.out.println("No solution exists");
}
}

public static boolean solveSudoku(int[][] board) {


for (int row = 0; row < N; row++) {
for (int col = 0; col < N; col++) {
if (board[row][col] == 0) {
for (int num = 1; num <= N; num++) {
if (isValid(board, row, col, num)) {
board[row][col] = num;
if (solveSudoku(board)) {
return true;
}
board[row][col] = 0;
}
}
return false;
}
}
}
return true;
}

public static boolean isValid(int[][] board, int row, int col, int num) {
for (int x = 0; x < N; x++) {
if (board[row][x] == num || board[x][col] == num || board[3 * (row / 3) + x
/ 3][3 * (col / 3) + x % 3] == num) {
return false;
}
}
return true;
}

public static void printBoard(int[][] board) {


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
}

438. Implementing a Simple ATM System Using OOP

java

class ATM {
private double balance;

public ATM(double initialBalance) {


balance = initialBalance;
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 213/250
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawn: " + amount);
} else {
System.out.println("Insufficient balance");
}
}

public void checkBalance() {


System.out.println("Current Balance: " + balance);
}
}

public class ATMSimulator {


public static void main(String[] args) {
ATM atm = new ATM(2000);
atm.deposit(500);
atm.withdraw(1000);
atm.checkBalance();
}
}

439. Implementing an LRU Cache (Least Recently Used)

java

import java.util.*;

class LRUCache {
private Map<Integer, Integer> cache;
private int capacity;
private LinkedHashMap<Integer, Long> accessTime;

public LRUCache(int capacity) {


this.capacity = capacity;
this.cache = new LinkedHashMap<>(capacity, 0.75f, true);
this.accessTime = new LinkedHashMap<>();
}

public void put(int key, int value) {


if (cache.size() >= capacity) {
evict();
}
cache.put(key, value);
accessTime.put(key, System.nanoTime());
}

public Integer get(int key) {


if (!cache.containsKey(key)) {
return null;
}
accessTime.put(key, System.nanoTime());
return cache.get(key);
}

private void evict() {


long oldestTime = Long.MAX_VALUE;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 214/250
int oldestKey = -1;

for (Map.Entry<Integer, Long> entry : accessTime.entrySet()) {


if (entry.getValue() < oldestTime) {
oldestTime = entry.getValue();
oldestKey = entry.getKey();
}
}
cache.remove(oldestKey);
accessTime.remove(oldestKey);
}
}

public class LRUCacheExample {


public static void main(String[] args) {
LRUCache lruCache = new LRUCache(3);
lruCache.put(1, 100);
lruCache.put(2, 200);
lruCache.put(3, 300);
System.out.println("Get 1: " + lruCache.get(1));
lruCache.put(4, 400);
System.out.println("Get 2: " + lruCache.get(2));
}
}

440. Merge Sort Algorithm

java

public class MergeSort {


public static void main(String[] args) {
int[] array = { 38, 27, 43, 3, 9, 82, 10 };
mergeSort(array, 0, array.length - 1);
for (int num : array) {
System.out.print(num + " ");
}
}

public static void mergeSort(int[] array, int left, int right) {


if (left < right) {
int middle = (left + right) / 2;
mergeSort(array, left, middle);
mergeSort(array, middle + 1, right);
merge(array, left, middle, right);
}
}

public static void merge(int[] array, int left, int middle, int right) {
int n1 = middle - left + 1;
int n2 = right - middle;

int[] leftArray = new int[n1];


int[] rightArray = new int[n2];

System.arraycopy(array, left, leftArray, 0, n1);


System.arraycopy(array, middle + 1, rightArray, 0, n2);

int i = 0, j = 0, k = left;
while (i < n1 && j < n2) {
if (leftArray[i] <= rightArray[j]) {
array[k] = leftArray[i];
i++;
} else {
array[k] = rightArray[j];

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 215/250
j++;
}
k++;
}

while (i < n1) {


array[k] = leftArray[i];
i++;
k++;
}

while (j < n2) {


array[k] = rightArray[j];
j++;
k++;
}
}
}

These are some miscellaneous Java programs that cover algorithms, system design, and different
problem-solving approaches, giving you a broad view of advanced topics in Java.

Here are additional Java programs focusing on advanced topics that you can explore:

441. Implementing a Simple HashMap

java

import java.util.LinkedList;

class HashMap<K, V> {


private LinkedList<Entry<K, V>>[] table;
private int size;

public HashMap(int capacity) {


table = new LinkedList[capacity];
size = 0;
}

public void put(K key, V value) {


int index = key.hashCode() % table.length;
if (table[index] == null) {
table[index] = new LinkedList<>();
}
for (Entry<K, V> entry : table[index]) {
if (entry.getKey().equals(key)) {
entry.setValue(value);
return;
}
}
table[index].add(new Entry<>(key, value));
size++;
}

public V get(K key) {


int index = key.hashCode() % table.length;
if (table[index] == null) return null;
for (Entry<K, V> entry : table[index]) {
if (entry.getKey().equals(key)) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 216/250
return entry.getValue();
}
}
return null;
}

public boolean containsKey(K key) {


return get(key) != null;
}

private static class Entry<K, V> {


private K key;
private V value;

public Entry(K key, V value) {


this.key = key;
this.value = value;
}

public K getKey() {
return key;
}

public V getValue() {
return value;
}

public void setValue(V value) {


this.value = value;
}
}
}

public class CustomHashMapExample {


public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>(10);
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);

System.out.println("Key One: " + map.get("One"));


System.out.println("Key Two exists: " + map.containsKey("Two"));
}
}

442. Implementing a Simple Linked List

java

class LinkedList {
private Node head;

private class Node {


int data;
Node next;

public Node(int data) {


this.data = data;
this.next = null;
}
}

public void insert(int data) {


Node newNode = new Node(data);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 217/250
if (head == null) {
head = newNode;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
}
}

public void display() {


Node temp = head;
while (temp != null) {
System.out.print(temp.data + " -> ");
temp = temp.next;
}
System.out.println("null");
}

public void delete(int data) {


if (head == null) return;

if (head.data == data) {
head = head.next;
return;
}

Node temp = head;


while (temp.next != null && temp.next.data != data) {
temp = temp.next;
}

if (temp.next != null) {
temp.next = temp.next.next;
}
}
}

public class LinkedListExample {


public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(10);
list.insert(20);
list.insert(30);
list.display();

list.delete(20);
list.display();
}
}

443. Implementing a Simple Stack Using Array

java

class Stack {
private int maxSize;
private int top;
private int[] stack;

public Stack(int size) {


maxSize = size;
stack = new int[maxSize];

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 218/250
top = -1;
}

public boolean isEmpty() {


return top == -1;
}

public boolean isFull() {


return top == maxSize - 1;
}

public void push(int value) {


if (isFull()) {
System.out.println("Stack Overflow");
} else {
stack[++top] = value;
System.out.println(value + " pushed to stack");
}
}

public int pop() {


if (isEmpty()) {
System.out.println("Stack Underflow");
return -1;
} else {
return stack[top--];
}
}

public int peek() {


if (isEmpty()) {
System.out.println("Stack is empty");
return -1;
} else {
return stack[top];
}
}
}

public class StackExample {


public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(10);
stack.push(20);
stack.push(30);

System.out.println(stack.pop() + " popped from stack");

System.out.println("Top element is: " + stack.peek());


}
}

444. Implementing a Queue Using Linked List

java

class Queue {
private Node front, rear;
private int size;

private class Node {


int data;
Node next;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 219/250
public Node(int data) {
this.data = data;
this.next = null;
}
}

public Queue() {
front = rear = null;
size = 0;
}

public void enqueue(int data) {


Node newNode = new Node(data);
if (rear == null) {
front = rear = newNode;
size++;
return;
}
rear.next = newNode;
rear = newNode;
size++;
}

public int dequeue() {


if (front == null) {
System.out.println("Queue is empty");
return -1;
}
int value = front.data;
front = front.next;
size--;
return value;
}

public int peek() {


if (front == null) {
System.out.println("Queue is empty");
return -1;
}
return front.data;
}

public int getSize() {


return size;
}
}

public class QueueExample {


public static void main(String[] args) {
Queue queue = new Queue();
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);

System.out.println(queue.dequeue() + " dequeued from queue");

System.out.println("Front element is: " + queue.peek());


System.out.println("Queue size is: " + queue.getSize());
}
}

445. Implementing a Priority Queue

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 220/250
java

import java.util.PriorityQueue;

public class PriorityQueueExample {


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

pq.add(10);
pq.add(20);
pq.add(15);

System.out.println("Priority Queue: " + pq);

System.out.println("Removed: " + pq.poll());


System.out.println("Priority Queue after poll: " + pq);

System.out.println("Peek: " + pq.peek());


}
}

446. Depth First Search (DFS) in Graph

java

import java.util.*;

class Graph {
private Map<Integer, List<Integer>> adjList;

public Graph() {
adjList = new HashMap<>();
}

public void addEdge(int v, int w) {


adjList.putIfAbsent(v, new ArrayList<>());
adjList.get(v).add(w);
}

public void DFS(int start) {


Set<Integer> visited = new HashSet<>();
dfsUtil(start, visited);
}

private void dfsUtil(int v, Set<Integer> visited) {


visited.add(v);
System.out.print(v + " ");

for (int neighbor : adjList.get(v)) {


if (!visited.contains(neighbor)) {
dfsUtil(neighbor, visited);
}
}
}
}

public class DFSExample {


public static void main(String[] args) {
Graph g = new Graph();
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 221/250
g.addEdge(2, 0);
g.addEdge(2, 3);

System.out.println("DFS starting from vertex 2:");


g.DFS(2);
}
}

447. Breadth First Search (BFS) in Graph

java

import java.util.*;

class Graph {
private Map<Integer, List<Integer>> adjList;

public Graph() {
adjList = new HashMap<>();
}

public void addEdge(int v, int w) {


adjList.putIfAbsent(v, new ArrayList<>());
adjList.get(v).add(w);
}

public void BFS(int start) {


Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new LinkedList<>();

visited.add(start);
queue.add(start);

while (!queue.isEmpty()) {
int v = queue.poll();
System.out.print(v + " ");

for (int neighbor : adjList.get(v)) {


if (!visited.contains(neighbor)) {
visited.add(neighbor);
queue.add(neighbor);
}
}
}
}
}

public class BFSExample {


public static void main(String[] args) {
Graph g = new Graph();
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);

System.out.println("BFS starting from vertex 2:");


g.BFS(2);
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 222/250
These programs are designed to help you build a deeper understanding of Java, focusing on data
structures, algorithms, and advanced topics like graph traversal, custom collections, and more.

Here are additional advanced Java programs for you to explore:

448. Implementing a Binary Search Tree (BST)

java

class BinarySearchTree {
class Node {
int data;
Node left, right;

public Node(int data) {


this.data = data;
left = right = null;
}
}

private Node root;

public BinarySearchTree() {
root = null;
}

public void insert(int data) {


root = insertRec(root, data);
}

private Node insertRec(Node root, int data) {


if (root == null) {
root = new Node(data);
return root;
}

if (data < root.data) {


root.left = insertRec(root.left, data);
} else if (data > root.data) {
root.right = insertRec(root.right, data);
}

return root;
}

public void inorder() {


inorderRec(root);
}

private void inorderRec(Node root) {


if (root != null) {
inorderRec(root.left);
System.out.print(root.data + " ");
inorderRec(root.right);
}
}
}

public class BSTExample {


public static void main(String[] args) {
BinarySearchTree tree = new BinarySearchTree();

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 223/250
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);

System.out.println("Inorder traversal of BST:");


tree.inorder();
}
}

449. Implementing Dijkstra’s Algorithm for Shortest Path

java

import java.util.*;

class Graph {
private int V;
private LinkedList<Edge>[] adjList;

public Graph(int v) {
V = v;
adjList = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjList[i] = new LinkedList<>();
}
}

class Edge {
int dest, weight;
public Edge(int dest, int weight) {
this.dest = dest;
this.weight = weight;
}
}

public void addEdge(int src, int dest, int weight) {


adjList[src].add(new Edge(dest, weight));
adjList[dest].add(new Edge(src, weight));
}

public void dijkstra(int start) {


int[] dist = new int[V];
Arrays.fill(dist, Integer.MAX_VALUE);
dist[start] = 0;

PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.comparingInt(u -> dis


t[u]));
pq.add(start);

while (!pq.isEmpty()) {
int u = pq.poll();
for (Edge edge : adjList[u]) {
int v = edge.dest;
int weight = edge.weight;
if (dist[u] + weight < dist[v]) {
dist[v] = dist[u] + weight;
pq.add(v);
}
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 224/250
System.out.println("Shortest distances from node " + start + ":");
for (int i = 0; i < V; i++) {
System.out.println("Node " + i + ": " + dist[i]);
}
}
}

public class DijkstraExample {


public static void main(String[] args) {
Graph g = new Graph(5);
g.addEdge(0, 1, 10);
g.addEdge(0, 2, 20);
g.addEdge(1, 3, 30);
g.addEdge(2, 3, 10);
g.addEdge(3, 4, 40);

g.dijkstra(0);
}
}

450. Implementing a Circular Queue

java

class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;

public CircularQueue(int capacity) {


this.capacity = capacity;
queue = new int[capacity];
front = rear = size = 0;
}

public boolean isEmpty() {


return size == 0;
}

public boolean isFull() {


return size == capacity;
}

public void enqueue(int value) {


if (isFull()) {
System.out.println("Queue is full");
return;
}
queue[rear] = value;
rear = (rear + 1) % capacity;
size++;
}

public int dequeue() {


if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
int value = queue[front];
front = (front + 1) % capacity;
size--;
return value;
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 225/250
public int peek() {
if (isEmpty()) {
System.out.println("Queue is empty");
return -1;
}
return queue[front];
}

public int getSize() {


return size;
}
}

public class CircularQueueExample {


public static void main(String[] args) {
CircularQueue q = new CircularQueue(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);

System.out.println("Dequeued element: " + q.dequeue());


q.enqueue(60);

System.out.println("Front element: " + q.peek());


System.out.println("Queue size: " + q.getSize());
}
}

451. Implementing Merge Sort

java

class MergeSort {
public static void mergeSort(int[] arr) {
if (arr.length < 2) {
return;
}

int mid = arr.length / 2;


int[] left = new int[mid];
int[] right = new int[arr.length - mid];

System.arraycopy(arr, 0, left, 0, mid);


System.arraycopy(arr, mid, right, 0, arr.length - mid);

mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}

private static void merge(int[] arr, int[] left, int[] right) {


int i = 0, j = 0, k = 0;

while (i < left.length && j < right.length) {


if (left[i] <= right[j]) {
arr[k++] = left[i++];
} else {
arr[k++] = right[j++];
}
}

while (i < left.length) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 226/250
arr[k++] = left[i++];
}

while (j < right.length) {


arr[k++] = right[j++];
}
}

public static void printArray(int[] arr) {


for (int val : arr) {
System.out.print(val + " ");
}
System.out.println();
}
}

public class MergeSortExample {


public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6, 7};
System.out.println("Unsorted array:");
MergeSort.printArray(arr);

MergeSort.mergeSort(arr);

System.out.println("Sorted array:");
MergeSort.printArray(arr);
}
}

452. Implementing Quick Sort

java

class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}

private static int partition(int[] arr, int low, int high) {


int pivot = arr[high];
int i = low - 1;

for (int j = low; j < high; j++) {


if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

int temp = arr[i + 1];


arr[i + 1] = arr[high];
arr[high] = temp;

return i + 1;
}

public static void printArray(int[] arr) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 227/250
for (int val : arr) {
System.out.print(val + " ");
}
System.out.println();
}
}

public class QuickSortExample {


public static void main(String[] args) {
int[] arr = {10, 7, 8, 9, 1, 5};
System.out.println("Unsorted array:");
QuickSort.printArray(arr);

QuickSort.quickSort(arr, 0, arr.length - 1);

System.out.println("Sorted array:");
QuickSort.printArray(arr);
}
}

453. Implementing Heap Sort

java

class HeapSort {
public static void heapify(int[] arr, int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest]) {


largest = left;
}

if (right < n && arr[right] > arr[largest]) {


largest = right;
}

if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;

heapify(arr, n, largest);
}
}

public static void heapSort(int[] arr) {


int n = arr.length;

for (int i = n / 2 - 1; i >= 0; i--) {


heapify(arr, n, i);
}

for (int i = n - 1; i > 0; i--) {


int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;

heapify(arr, i, 0);
}
}

public static void printArray(int[] arr) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 228/250
for (int val : arr) {
System.out.print(val + " ");
}
System.out.println();
}
}

public class HeapSortExample {


public static void main(String[] args) {
int[] arr = {12, 11, 13, 5, 6, 7};
System.out.println("Unsorted array:");
HeapSort.printArray(arr);

HeapSort.heapSort(arr);

System.out.println("Sorted array:");
HeapSort.printArray(arr);
}
}

These programs will further enhance your understanding of advanced Java topics such as sorting
algorithms, graph traversal, and custom data structures. Let me know if you need more programs!

Here are some Java programs based on real-world scenarios:

454. Bank Account Management System

java

import java.util.*;

class BankAccount {
private int accountNumber;
private String accountHolder;
private double balance;

public BankAccount(int accountNumber, String accountHolder) {


this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = 0.0;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: " + amount);
}

public void withdraw(double amount) {


if (amount > balance) {
System.out.println("Insufficient balance!");
} else {
balance -= amount;
System.out.println("Withdrawn: " + amount);
}
}

public void checkBalance() {


System.out.println("Account balance: " + balance);
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 229/250
}

public class BankAccountSystem {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
BankAccount account = new BankAccount(101, "John Doe");

account.deposit(1000);
account.checkBalance();
account.withdraw(500);
account.checkBalance();
}
}

Scenario: This program simulates basic bank account operations like deposit, withdrawal, and
balance check.

455. Library Management System

java

import java.util.*;

class Book {
private String title;
private boolean isAvailable;

public Book(String title) {


this.title = title;
this.isAvailable = true;
}

public String getTitle() {


return title;
}

public boolean isAvailable() {


return isAvailable;
}

public void borrowBook() {


if (isAvailable) {
isAvailable = false;
System.out.println("You have borrowed: " + title);
} else {
System.out.println("Sorry, the book is not available.");
}
}

public void returnBook() {


isAvailable = true;
System.out.println("You have returned: " + title);
}
}

class Library {
private List<Book> books;

public Library() {
books = new ArrayList<>();
}

public void addBook(Book book) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 230/250
books.add(book);
}

public void showAvailableBooks() {


for (Book book : books) {
if (book.isAvailable()) {
System.out.println(book.getTitle());
}
}
}
}

public class LibraryManagementSystem {


public static void main(String[] args) {
Library library = new Library();
Book book1 = new Book("The Alchemist");
Book book2 = new Book("Java Programming");
library.addBook(book1);
library.addBook(book2);

System.out.println("Available Books:");
library.showAvailableBooks();

book1.borrowBook();
book2.borrowBook();

System.out.println("\nAvailable Books after borrowing:");


library.showAvailableBooks();

book1.returnBook();

System.out.println("\nAvailable Books after returning:");


library.showAvailableBooks();
}
}

Scenario: A library management system to manage books, their availability, and the
borrowing/returning process.

456. Online Shopping Cart System

java

import java.util.*;

class Product {
private String name;
private double price;

public Product(String name, double price) {


this.name = name;
this.price = price;
}

public String getName() {


return name;
}

public double getPrice() {


return price;
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 231/250
class ShoppingCart {
private List<Product> cart;

public ShoppingCart() {
cart = new ArrayList<>();
}

public void addProduct(Product product) {


cart.add(product);
System.out.println(product.getName() + " has been added to the cart.");
}

public void removeProduct(Product product) {


cart.remove(product);
System.out.println(product.getName() + " has been removed from the cart.");
}

public double calculateTotal() {


double total = 0;
for (Product product : cart) {
total += product.getPrice();
}
return total;
}

public void showCart() {


System.out.println("Items in your cart:");
for (Product product : cart) {
System.out.println(product.getName() + " - $" + product.getPrice());
}
}
}

public class ShoppingCartSystem {


public static void main(String[] args) {
Product p1 = new Product("Laptop", 1200);
Product p2 = new Product("Smartphone", 800);
Product p3 = new Product("Headphones", 100);

ShoppingCart cart = new ShoppingCart();

cart.addProduct(p1);
cart.addProduct(p2);
cart.showCart();
System.out.println("Total Price: $" + cart.calculateTotal());

cart.removeProduct(p1);
cart.showCart();
System.out.println("Total Price: $" + cart.calculateTotal());
}
}

Scenario: This program simulates adding/removing items to/from a shopping cart, and calculating
the total price.

457. Taxi Fare Calculation System

java

import java.util.Scanner;

class TaxiFareCalculator {
private static final double BASE_FARE = 50.0;

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 232/250
private static final double RATE_PER_KM = 15.0;

public double calculateFare(double distance) {


return BASE_FARE + (distance * RATE_PER_KM);
}
}

public class TaxiFareSystem {


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

System.out.print("Enter distance traveled (in km): ");


double distance = scanner.nextDouble();

double fare = calculator.calculateFare(distance);


System.out.println("The total fare for your ride is: $" + fare);
}
}

Scenario: This program calculates the taxi fare based on a base fare and the distance traveled.

458. Student Grading System

java

import java.util.Scanner;

class Student {
private String name;
private double marks;

public Student(String name, double marks) {


this.name = name;
this.marks = marks;
}

public String getGrade() {


if (marks >= 90) {
return "A";
} else if (marks >= 75) {
return "B";
} else if (marks >= 50) {
return "C";
} else {
return "F";
}
}

public void displayResult() {


System.out.println("Student: " + name);
System.out.println("Marks: " + marks);
System.out.println("Grade: " + getGrade());
}
}

public class GradingSystem {


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

System.out.print("Enter student name: ");


String name = scanner.nextLine();
System.out.print("Enter student marks: ");
double marks = scanner.nextDouble();
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 233/250
Student student = new Student(name, marks);
student.displayResult();
}
}

Scenario: This program takes student details (name and marks), calculates their grade, and displays
the result.

459. Hotel Reservation System

java

import java.util.*;

class Room {
private int roomNumber;
private boolean isBooked;

public Room(int roomNumber) {


this.roomNumber = roomNumber;
this.isBooked = false;
}

public int getRoomNumber() {


return roomNumber;
}

public boolean isBooked() {


return isBooked;
}

public void bookRoom() {


isBooked = true;
}

public void releaseRoom() {


isBooked = false;
}
}

class Hotel {
private List<Room> rooms;

public Hotel(int totalRooms) {


rooms = new ArrayList<>();
for (int i = 1; i <= totalRooms; i++) {
rooms.add(new Room(i));
}
}

public void bookRoom(int roomNumber) {


for (Room room : rooms) {
if (room.getRoomNumber() == roomNumber && !room.isBooked()) {
room.bookRoom();
System.out.println("Room " + roomNumber + " has been booked.");
return;
}
}
System.out.println("Room " + roomNumber + " is either already booked or does not
exist.");
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 234/250
public void releaseRoom(int roomNumber) {
for (Room room : rooms) {
if (room.getRoomNumber() == roomNumber && room.isBooked()) {
room.releaseRoom();
System.out.println("Room " + roomNumber + " has been released.");
return;
}
}
System.out.println("Room " + roomNumber + " is either not booked or does not exi
st.");
}

public void showAvailableRooms() {


System.out.println("Available Rooms:");
for (Room room : rooms) {
if (!room.isBooked()) {
System.out.println("Room " + room.getRoomNumber());
}
}
}
}

public class HotelReservationSystem {


public static void main(String[] args) {
Hotel hotel = new Hotel(5);
hotel.showAvailableRooms();
hotel.bookRoom(2);
hotel.showAvailableRooms();
hotel.releaseRoom(2);
hotel.showAvailableRooms();
}
}

Scenario: This program simulates a hotel reservation system, where users can book and release
rooms.

These programs cover a range of real-world scenarios and can be enhanced with additional features
depending on the requirements. Let me know if you need any modifications or additional examples!

Here are some more real-world scenario-based Java programs:

460. Employee Management System

java

import java.util.*;

class Employee {
private int id;
private String name;
private double salary;

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


this.id = id;
this.name = name;
this.salary = salary;
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 235/250
public int getId() {
return id;
}

public String getName() {


return name;
}

public double getSalary() {


return salary;
}

public void updateSalary(double newSalary) {


this.salary = newSalary;
}

public void displayInfo() {


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

class EmployeeManagementSystem {
private List<Employee> employees;

public EmployeeManagementSystem() {
employees = new ArrayList<>();
}

public void addEmployee(Employee employee) {


employees.add(employee);
}

public void removeEmployee(int id) {


employees.removeIf(emp -> emp.getId() == id);
}

public void displayEmployees() {


for (Employee employee : employees) {
employee.displayInfo();
System.out.println("------");
}
}
}

public class EmployeeSystem {


public static void main(String[] args) {
EmployeeManagementSystem system = new EmployeeManagementSystem();

Employee emp1 = new Employee(101, "John Doe", 5000);


Employee emp2 = new Employee(102, "Jane Smith", 6000);

system.addEmployee(emp1);
system.addEmployee(emp2);

system.displayEmployees();

emp1.updateSalary(5500);
system.displayEmployees();
}
}

Scenario: This program simulates an employee management system where employees can be
added, removed, and their information (name, ID, salary) can be updated.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 236/250
461. Online Voting System

java

import java.util.*;

class Candidate {
private String name;
private int votes;

public Candidate(String name) {


this.name = name;
this.votes = 0;
}

public String getName() {


return name;
}

public void addVote() {


votes++;
}

public int getVotes() {


return votes;
}
}

class VotingSystem {
private List<Candidate> candidates;

public VotingSystem(List<String> candidateNames) {


candidates = new ArrayList<>();
for (String name : candidateNames) {
candidates.add(new Candidate(name));
}
}

public void vote(String candidateName) {


for (Candidate candidate : candidates) {
if (candidate.getName().equals(candidateName)) {
candidate.addVote();
System.out.println("Voted for " + candidateName);
return;
}
}
System.out.println("Invalid candidate!");
}

public void displayVotes() {


for (Candidate candidate : candidates) {
System.out.println(candidate.getName() + ": " + candidate.getVotes() + " vot
es");
}
}

public void getWinner() {


Candidate winner = candidates.get(0);
for (Candidate candidate : candidates) {
if (candidate.getVotes() > winner.getVotes()) {
winner = candidate;
}
}
System.out.println("The winner is: " + winner.getName());
}
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 237/250
public class OnlineVotingSystem {
public static void main(String[] args) {
List<String> candidateNames = Arrays.asList("Alice", "Bob", "Charlie");
VotingSystem system = new VotingSystem(candidateNames);

system.vote("Alice");
system.vote("Bob");
system.vote("Alice");
system.vote("Charlie");
system.vote("Alice");

system.displayVotes();
system.getWinner();
}
}

Scenario: This program simulates an online voting system where users can vote for their preferred
candidate, and the winner is determined after all votes are cast.

462. ATM System

java

import java.util.Scanner;

class ATM {
private double balance;

public ATM() {
this.balance = 10000.0;
}

public void deposit(double amount) {


balance += amount;
System.out.println("Deposited: $" + amount);
}

public void withdraw(double amount) {


if (amount > balance) {
System.out.println("Insufficient balance!");
} else {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
}
}

public void checkBalance() {


System.out.println("Your balance is: $" + balance);
}
}

public class ATMSystem {


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

do {
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Exit");
System.out.print("Choose an option: ");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 238/250
option = scanner.nextInt();

switch (option) {
case 1:
System.out.print("Enter deposit amount: ");
double depositAmount = scanner.nextDouble();
atm.deposit(depositAmount);
break;
case 2:
System.out.print("Enter withdrawal amount: ");
double withdrawAmount = scanner.nextDouble();
atm.withdraw(withdrawAmount);
break;
case 3:
atm.checkBalance();
break;
case 4:
System.out.println("Thank you for using the ATM.");
break;
default:
System.out.println("Invalid option. Try again.");
}
} while (option != 4);
}
}

Scenario: This program simulates an ATM system where users can deposit money, withdraw money,
and check their balance.

463. Grocery Store Billing System

java

import java.util.*;

class Item {
private String name;
private double price;

public Item(String name, double price) {


this.name = name;
this.price = price;
}

public String getName() {


return name;
}

public double getPrice() {


return price;
}
}

class BillingSystem {
private List<Item> items;

public BillingSystem() {
items = new ArrayList<>();
}

public void addItem(Item item) {


items.add(item);
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 239/250
public void generateBill() {
double total = 0;
System.out.println("------ Grocery Bill ------");
for (Item item : items) {
System.out.println(item.getName() + " - $" + item.getPrice());
total += item.getPrice();
}
System.out.println("-------------------------");
System.out.println("Total Amount: $" + total);
}
}

public class GroceryStoreBillingSystem {


public static void main(String[] args) {
BillingSystem billingSystem = new BillingSystem();

Item item1 = new Item("Apple", 1.5);


Item item2 = new Item("Banana", 0.8);
Item item3 = new Item("Milk", 2.3);

billingSystem.addItem(item1);
billingSystem.addItem(item2);
billingSystem.addItem(item3);

billingSystem.generateBill();
}
}

Scenario: This program simulates a grocery store's billing system, where items are added to the
cart, and the total amount is calculated.

464. Bus Reservation System

java

import java.util.*;

class Bus {
private int busNumber;
private int totalSeats;
private int availableSeats;

public Bus(int busNumber, int totalSeats) {


this.busNumber = busNumber;
this.totalSeats = totalSeats;
this.availableSeats = totalSeats;
}

public int getBusNumber() {


return busNumber;
}

public void reserveSeats(int seats) {


if (seats <= availableSeats) {
availableSeats -= seats;
System.out.println("Seats reserved: " + seats);
} else {
System.out.println("Not enough seats available.");
}
}

public void cancelReservation(int seats) {

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 240/250
if (availableSeats + seats <= totalSeats) {
availableSeats += seats;
System.out.println("Reservation canceled: " + seats);
} else {
System.out.println("Invalid cancellation request.");
}
}

public void showAvailableSeats() {


System.out.println("Available seats: " + availableSeats);
}
}

public class BusReservationSystem {


public static void main(String[] args) {
Bus bus1 = new Bus(101, 40);
Bus bus2 = new Bus(102, 30);

bus1.reserveSeats(10);
bus2.reserveSeats(5);

bus1.showAvailableSeats();
bus2.showAvailableSeats();

bus1.cancelReservation(5);
bus2.cancelReservation(3);

bus1.showAvailableSeats();
bus2.showAvailableSeats();
}
}

Scenario: This program simulates a bus reservation system where users can reserve and cancel
seats, and check available seats.

These examples illustrate how Java can be applied in various real-world applications, including
banking, voting, transportation, and retail systems. Let me know if you would like more examples or
modifications!

Here is a Java program using built-in methods to demonstrate how various common Java classes
and methods can be utilized.

Program: String Manipulation Using Built-In Methods

java

public class BuiltInMethodsExample {

public static void main(String[] args) {

// 1. String length() - to get the length of the string


String str = "Hello, Java!";
System.out.println("Length of the string: " + str.length());

// 2. String toUpperCase() - to convert all characters to uppercase


System.out.println("Uppercase: " + str.toUpperCase());

// 3. String toLowerCase() - to convert all characters to lowercase

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 241/250
System.out.println("Lowercase: " + str.toLowerCase());

// 4. String substring() - to extract a substring from a string


System.out.println("Substring (from index 7): " + str.substring(7));

// 5. String charAt() - to get a character at a specific position


System.out.println("Character at index 5: " + str.charAt(5));

// 6. String contains() - to check if a substring exists in the string


System.out.println("Contains 'Java': " + str.contains("Java"));

// 7. String equals() - to compare two strings for equality


String str2 = "Hello, Java!";
System.out.println("Strings are equal: " + str.equals(str2));

// 8. String replace() - to replace a character or substring in a string


System.out.println("Replace 'Java' with 'World': " + str.replace("Java", "Worl
d"));

// 9. String trim() - to remove leading and trailing spaces


String strWithSpaces = " Hello, World! ";
System.out.println("Trimmed string: '" + strWithSpaces.trim() + "'");

// 10. String split() - to split a string into an array based on a delimiter


String str3 = "apple,banana,orange";
String[] fruits = str3.split(",");
System.out.println("Fruits:");
for (String fruit : fruits) {
System.out.println(fruit);
}

// 11. Math methods: Math.max() and Math.min()


System.out.println("Maximum of 10 and 20: " + Math.max(10, 20));
System.out.println("Minimum of 10 and 20: " + Math.min(10, 20));

// 12. Math.random() - to generate a random number


System.out.println("Random number between 0 and 1: " + Math.random());

// 13. Math.abs() - to get the absolute value of a number


System.out.println("Absolute value of -15: " + Math.abs(-15));

// 14. Arrays.sort() - to sort an array


int[] numbers = {5, 1, 9, 3, 7};
System.out.println("Array before sorting:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
Arrays.sort(numbers);
System.out.println("Array after sorting:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
}

Explanation of Built-In Methods Used:

1. String Methods:
`length()`:Returns the length of the string.
`toUpperCase()`: Converts the string to uppercase.
`toLowerCase()`: Converts the string to lowercase.
`substring()`: Extracts a substring from a string.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 242/250
`charAt()`: Returns the character at the specified index.
`contains()`: Checks if a substring exists in the string.
`equals()`: Compares two strings for equality.
`replace()`: Replaces a specified substring with another.
`trim()`: Removes leading and trailing whitespaces.
`split()`: Splits a string into an array using a delimiter.
2. Math Methods:
`Math.max()`: Returns the maximum of two numbers.
`Math.min()`: Returns the minimum of two numbers.
`Math.random()`: Generates a random number between 0 and 1.
`Math.abs()`: Returns the absolute value of a number.
3. Arrays:
`Arrays.sort()`: Sorts an array of numbers.

Output:

yaml

Length of the string: 13


Uppercase: HELLO, JAVA!
Lowercase: hello, java!
Substring (from index 7): Java!
Character at index 5: ,
Contains 'Java': true
Strings are equal: true
Replace 'Java' with 'World': Hello, World!
Trimmed string: 'Hello, World!'
Fruits:
apple
banana
orange
Maximum of 10 and 20: 20
Minimum of 10 and 20: 10
Random number between 0 and 1: 0.2683312103806078
Absolute value of -15: 15
Array before sorting:
5 1 9 3 7
Array after sorting:
1 3 5 7 9

This program demonstrates how you can use built-in methods in Java for common string
manipulations, mathematical operations, and array handling.

Here’s another Java program that demonstrates different built-in methods from Java’s standard
library for a variety of common tasks. This program showcases additional features such as date
manipulation, list operations, file handling, and more.

Program: Using Built-In Methods for Date, List, and File Handling

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 243/250
java

import java.io.*;
import java.util.*;
import java.text.*;

public class BuiltInMethodsAdvancedExample {

public static void main(String[] args) {

// 1. Date Methods
Date currentDate = new Date();
System.out.println("Current Date and Time: " + currentDate);

// 2. SimpleDateFormat: Formatting a Date


SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String formattedDate = formatter.format(currentDate);
System.out.println("Formatted Date: " + formattedDate);

// 3. List Methods
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");

System.out.println("Original List: " + fruits);

// 4. List remove() - Removes a specific element


fruits.remove("Banana");
System.out.println("List after removing Banana: " + fruits);

// 5. List size() - Getting the size of the list


System.out.println("Size of the List: " + fruits.size());

// 6. List contains() - Checking if an element exists in the list


System.out.println("Does the list contain 'Apple'? " + fruits.contains("Appl
e"));

// 7. List get() - Accessing an element by index


System.out.println("Element at index 1: " + fruits.get(1));

// 8. File Handling: Writing to a file


try {
FileWriter writer = new FileWriter("example.txt");
writer.write("This is an example of file handling in Java.\n");
writer.write("We are using built-in methods for writing to files.");
writer.close();
System.out.println("Data written to file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}

// 9. File Handling: Reading from a file


try {
FileReader reader = new FileReader("example.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
System.out.println("\nReading from file:");
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
System.out.println("An error occurred while reading from the file.");
e.printStackTrace();
}

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 244/250
// 10. Arrays.asList() - Convert array to list
String[] colorArray = {"Red", "Green", "Blue"};
List<String> colorList = Arrays.asList(colorArray);
System.out.println("\nConverted Array to List: " + colorList);

// 11. Arrays.equals() - Compare two arrays


String[] array1 = {"Java", "Python", "C"};
String[] array2 = {"Java", "Python", "C"};
System.out.println("\nArrays are equal: " + Arrays.equals(array1, array2));

// 12. Collections.sort() - Sorting a list


Collections.sort(fruits);
System.out.println("Sorted List: " + fruits);

// 13. String join() - Joining elements of a list into a string


String joinedFruits = String.join(", ", fruits);
System.out.println("Joined Fruits: " + joinedFruits);

// 14. String format() - Formatting strings


String formattedString = String.format("Formatted String: %s - %d", "Java", 10
1);
System.out.println(formattedString);
}
}

Explanation of Built-In Methods Used:

1. Date Methods:
`Date()`:
Creates a Date object representing the current date and time.
`SimpleDateFormat()`: Formats a Date object into a readable string format.
2. List Methods (ArrayList):
`add()`:Adds elements to the list.
`remove()`:Removes a specific element from the list.
`size()`: Returns the size of the list.
`contains()`: Checks if a specific element is present in the list.
`get()`: Retrieves an element from the list based on its index.
3. File Handling (File I/O):
`FileWriter()`:
Writes text data to a file.
`BufferedReader()`: Reads text data from a file line by line.
`write()`: Writes data to the file.
`close()`: Closes the file after reading/writing.
4. Arrays Methods:
`Arrays.asList()`:
Converts an array into a list.
`Arrays.equals()`: Compares two arrays for equality.
5. Collections Methods:
`Collections.sort()`: Sorts a list in ascending order.
6. String Methods:
`String.join()`:Joins multiple strings or elements from a collection into a single string.
`String.format()`: Formats strings using specified format specifiers.

Output:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 245/250
mathematica

Current Date and Time: Wed Dec 25 14:20:14 UTC 2024


Formatted Date: 25/12/2024 14:20:14
Original List: [Apple, Banana, Cherry]
List after removing Banana: [Apple, Cherry]
Size of the List: 2
Does the list contain 'Apple'? true
Element at index 1: Cherry
Data written to file successfully.

Reading from file:


This is an example of file handling in Java.
We are using built-in methods for writing to files.

Converted Array to List: [Red, Green, Blue]


Arrays are equal: true
Sorted List: [Apple, Cherry]
Joined Fruits: Apple, Cherry
Formatted String: Java - 101

Key Points:

This program demonstrates a wide range of Java's built-in methods, including date formatting,
list operations, file handling, and array manipulations.
It also covers how to sort a list, convert an array to a list, and format strings.
The use of file handling methods such as `FileWriter`, `BufferedReader`, and others is shown
to read from and write to files, illustrating practical file operations in Java.

This code illustrates how powerful Java's built-in methods can be for a variety of common tasks, such
as working with data, lists, and files. Let me know if you'd like more examples or explanations!

In Java, the `import` statement is used to include classes or entire packages in a Java program. This
allows you to use the classes and methods from external libraries and packages without needing to
specify their full path every time you reference them. Here's a breakdown of the `import` statement
from basic to intermediate levels:

1. Importing a Single Class (Basic)

To import a specific class, you use the `import` statement followed by the full path of the class. For
example, if you want to use the `Scanner` class from the `java.util` package to read user input:

java

import java.util.Scanner;

public class BasicImportExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Using the imported Scanner class
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 246/250
}
}

Explanation:

`import java.util.Scanner;` tells the compiler to import the `Scanner` class from the
`java.util` package so it can be used in the program.
Without this import, you'd have to use the full class path, like `java.util.Scanner`.

2. Importing All Classes from a Package (Intermediate)

You can import all the classes from a package using a wildcard (`*`). For example, if you want to use
many classes from the `java.util` package, you can import them all at once:

java

import java.util.*;

public class IntermediateImportExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Using the imported Scanner class
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("You entered: " + number);

List<String> list = new ArrayList<>(); // Using the ArrayList from java.util


list.add("Java");
list.add("Python");
list.add("C++");

System.out.println("Languages: " + list);


}
}

Explanation:

`import java.util.*;` imports all the classes from the `java.util` package. This is convenient
when you need multiple classes from the same package, but it’s generally not recommended if
you’re only using one or two classes, as it might increase memory usage or import
unnecessary classes.

3. Importing Static Members (Intermediate)

If you want to import static members (fields or methods) of a class, you can use the `import static`
statement. This is particularly useful when you want to avoid qualifying static members with the
class name.

For example, the `Math` class has static methods like `Math.pow()` or `Math.sqrt()`. You can import
these methods statically:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 247/250
java

import static java.lang.Math.pow;


import static java.lang.Math.sqrt;

public class StaticImportExample {


public static void main(String[] args) {
double result1 = pow(2, 3); // Using the imported pow method without class name
double result2 = sqrt(16); // Using the imported sqrt method

System.out.println("2^3 = " + result1);


System.out.println("sqrt(16) = " + result2);
}
}

Explanation:

`import static java.lang.Math.pow;` imports the `pow` method of the `Math` class so it can be
used directly without the class name.
Similarly, `import static java.lang.Math.sqrt;` imports the `sqrt` method of the `Math` class.

4. Importing Classes with Same Name from Different Packages (Intermediate)

If you want to use two classes with the same name from different packages, Java allows you to
import them with fully qualified names.

For example, if you want to use both `Vector` classes from `java.util` and `java.awt`:

java

import java.util.Vector;
import java.awt.Vector;

public class ConflictingImportExample {


public static void main(String[] args) {
Vector<Integer> intVector = new Vector<>();
intVector.add(10);
intVector.add(20);

// Here you can use the java.util.Vector without conflict


System.out.println("Vector from java.util: " + intVector);
}
}

Explanation:

`import java.util.Vector;` imports the `Vector` class from the `java.util` package.
`import java.awt.Vector;` imports the `Vector` class from the `java.awt` package.
In this case, you can choose which one to use in your code. However, this approach is rare, as
typically, classes with the same name in different packages are avoided.

5. Fully Qualified Class Names (Advanced)

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 248/250
In some cases, you may choose to avoid using the `import` statement and instead use the full path
of the class directly in the code. This is generally not recommended for readability and
maintainability reasons but is occasionally used for clarity.

Example:

java

public class FullyQualifiedClassExample {


public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in); // Fully qualifie
d class name
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");
}
}

Explanation:

Here, instead of importing `Scanner`, we directly reference `java.util.Scanner` whenever we


need to use it.

Summary of Import Types:

1. Single Class Import:


`import java.util.Scanner;` - Importing a single class from a package.
2. Wildcard Import:
`import java.util.*;` - Importing all classes from a package.
3. Static Import:
`import static java.lang.Math.pow;` - Importing static members of a class.
4. Handling Name Conflicts:
Use fully qualified class names if you want to import classes with the same name from
different packages.
5. Fully Qualified Class Names:
No `import` statement, instead use the full class name in the code.

These examples cover the most common ways to use the `import` statement in Java from basic to
intermediate levels.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 249/250
Messages beyond this point are only visible to you

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 250/250

You might also like