Java@Programs
Java@Programs
Here is a categorized list of 150+ Java programs ranging from basic to intermediate levels:
2. Control Statements
3. Loops
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
5. Strings
6. Object-Oriented Programming
7. Exception Handling
8. File Handling
9. Collections
10. 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
13. Miscellaneous
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
Let me know which specific topics or programs you'd like detailed explanations or examples for!
java
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);
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 6/250
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
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
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
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!
java
import java.util.Scanner;
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 9/250
int end = scanner.nextInt();
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 11/250
}
}
java
import java.util.Scanner;
while (num != 0) {
num /= 10;
count++;
}
java
import java.util.Scanner;
while (num != 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 12/250
java
import java.util.Scanner;
while (num != 0) {
int digit = num % 10;
sum += digit;
num /= 10;
}
java
import java.util.Scanner;
Let me know if you want programs for the next set or detailed explanations!
java
import java.util.Scanner;
long result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
java
import java.util.Scanner;
while (num2 != 0) {
int temp = num2;
num2 = num1 % num2;
num1 = temp;
}
java
import java.util.Scanner;
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;
}
java
import java.util.Scanner;
java
import java.util.Scanner;
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);
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 16/250
java
import java.util.Scanner;
java
import java.util.Arrays;
import java.util.Scanner;
Arrays.sort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
}
java
import java.util.Scanner;
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];
}
java
import java.util.Scanner;
if (secondLargest == Integer.MIN_VALUE) {
System.out.println("No second largest element found.");
} else {
System.out.println("Second largest element: " + secondLargest);
}
}
}
import java.util.Arrays;
import java.util.Scanner;
Arrays.sort(arr);
System.out.print("Array after removing duplicates: ");
java
import java.util.HashMap;
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 19/250
34. Merge Two Arrays
java
import java.util.Scanner;
java
import java.util.Scanner;
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();
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
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;
if (sum == num) {
System.out.println(num + " is a perfect number.");
} else {
System.out.println(num + " is not a perfect number.");
}
}
}
java
import java.util.Scanner;
System.out.println("Prime numbers between " + low + " and " + high + ":");
for (int num = low; num <= high; num++) {
if (isPrime(num)) {
System.out.print(num + " ");
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 22/250
java
import java.util.Scanner;
if (sum == originalNum) {
System.out.println(originalNum + " is an Armstrong number.");
} else {
System.out.println(originalNum + " is not an Armstrong number.");
}
}
}
java
import java.util.Scanner;
if (sum == originalNum) {
System.out.println(originalNum + " is a strong number.");
} else {
System.out.println(originalNum + " is not a strong number.");
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 23/250
}
}
java
import java.util.Scanner;
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();
}
}
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 24/250
java
import java.util.Scanner;
int sum = 0;
while (num > 0) {
sum += num % 10;
num /= 10;
}
java
import java.util.Scanner;
int reversed = 0;
while (num > 0) {
int digit = num % 10;
reversed = reversed * 10 + digit;
num /= 10;
}
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
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
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Arrays;
import java.util.Scanner;
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);
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 29/250
java
import java.util.Scanner;
java
import java.util.Scanner;
System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd(num1, num
2));
}
java
import java.util.Scanner;
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);
}
java
import java.util.Scanner;
java
import java.util.Scanner;
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 32/250
java
import java.util.Scanner;
java
import java.util.Scanner;
System.out.println("Fibonacci series:");
for (int i = 0; i < terms; i++) {
System.out.print(fibonacci(i) + " ");
}
}
java
import java.util.Scanner;
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);
}
}
java
import java.util.Scanner;
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
java
import java.util.Scanner;
System.out.println("Reversed array:");
for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 34/250
java
import java.util.Scanner;
System.out.println("Sorted array:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
if (secondLargest == Integer.MIN_VALUE) {
System.out.println("No second largest element found.");
} else {
System.out.println("The second largest element is: " + secondLargest);
}
}
}
java
import java.util.Scanner;
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];
java
import java.util.Arrays;
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++];
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 37/250
java
import java.util.Arrays;
import java.util.Scanner;
rotate(arr, k);
System.out.println("Array after rotation: " + Arrays.toString(arr));
}
java
import java.util.HashMap;
import java.util.Scanner;
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));
}
}
}
java
import java.util.HashSet;
import java.util.Scanner;
if (repeating != -1) {
System.out.println("First repeating element: " + repeating);
} else {
System.out.println("No repeating elements found.");
}
}
}
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;
java
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 40/250
int[] arr2 = new int[n2];
java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 41/250
java
import java.util.Scanner;
if (str.equals(reversedStr)) {
System.out.println("The string is a palindrome.");
} else {
System.out.println("The string is not a palindrome.");
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 42/250
}
}
}
java
import java.util.Scanner;
if (isPrime) {
System.out.println(num + " is a prime number.");
} else {
System.out.println(num + " is not a prime number.");
}
}
}
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
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 + " ");
}
}
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
long factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
java
import java.util.Scanner;
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;
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
java
import java.util.Scanner;
int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
java
import java.util.Scanner;
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);
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
long result = 1;
for (int i = 1; i <= exponent; i++) {
result *= base;
}
System.out.println(base + " raised to the power " + exponent + " is: " + resul
t);
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 47/250
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 48/250
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
int length = 0;
for (char ch : str.toCharArray()) {
length++;
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 49/250
java
import java.util.Scanner;
java
import java.util.Scanner;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 50/250
int b = scanner.nextInt();
java
import java.util.Scanner;
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:
java
import java.util.Scanner;
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();
java
import java.util.Scanner;
int largest = (num1 > num2) ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2
: num3);
System.out.println("The largest number is: " + largest);
}
}
java
import java.util.Scanner;
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 + " ");
}
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 53/250
106. Print Multiplication Table
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
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
java
java
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);
}
}
java
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 56/250
java
import java.util.Arrays;
java
import java.util.Arrays;
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};
java
if (found) {
System.out.println("Element found");
} else {
System.out.println("Element not found");
}
}
}
java
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);
}
}
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
java
import java.util.Scanner;
if (sum == originalNum) {
System.out.println(originalNum + " is an Armstrong number.");
} else {
System.out.println(originalNum + " is not an Armstrong number.");
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 59/250
java
import java.util.Scanner;
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):
java
import java.util.Scanner;
if (num % 2 == 0) {
System.out.println(num + " is even.");
} else {
System.out.println(num + " is odd.");
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 60/250
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 62/250
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 63/250
int num = scanner.nextInt();
int sum = 0;
System.out.println("Sum of first " + num + " natural numbers is: " + sum);
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
while (num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}
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;
java
import java.util.Scanner;
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--;
}
}
}
java
import java.util.Scanner;
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;
}
}
}
java
import java.util.Scanner;
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);
}
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 66/250
lcm++;
}
}
}
java
import java.util.Scanner;
do {
System.out.println(num + " * " + i + " = " + (num * i));
i++;
} while (i <= 10);
}
}
java
java
import java.util.Scanner;
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;
}
}
These are the next set of Java programs related to control statements. Let me know if you'd like
more!
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 68/250
java
import java.util.Scanner;
while (num != 0) {
num /= 10;
count++;
}
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 70/250
arr[i] = scanner.nextInt();
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 71/250
int element = scanner.nextInt();
int count = 0;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 72/250
}
}
}
java
import java.util.Scanner;
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!
java
import java.util.Scanner;
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;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 74/250
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
int i = 1;
while (i <= n) {
sum += i;
i++;
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 75/250
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
while (n >= 1) {
System.out.print(n + " ");
n--;
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 76/250
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
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;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 78/250
System.out.print("*");
}
System.out.println();
}
}
}
java
import java.util.Scanner;
These programs cover various loop operations, including `for`, `while`, and `do-while` loops. Let
me know if you'd like more!
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 79/250
number++;
}
System.out.println();
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
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);
}
}
java
import java.util.Scanner;
System.out.println("LCM of " + num1 + " and " + num2 + " is: " + lcm);
}
}
java
import java.util.Scanner;
if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible.");
return;
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 81/250
int[][] result = new int[rows1][cols2];
// 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];
}
}
}
java
import java.util.Scanner;
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
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 83/250
java
import java.util.Scanner;
while (num != 0) {
sum += num % 10;
num /= 10;
}
java
import java.util.Scanner;
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!
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 84/250
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 85/250
java
import java.util.Scanner;
System.out.println("Reversed array:");
for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
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;
java
import java.util.Scanner;
java
import java.util.Scanner;
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();
}
java
import java.util.Scanner;
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;
java
import java.util.Scanner;
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!
java
import java.util.Scanner;
import java.util.HashMap;
System.out.println("Element frequencies:");
for (int key : frequency.keySet()) {
System.out.println(key + ": " + frequency.get(key));
}
}
}
java
import java.util.Scanner;
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];
java
import java.util.Scanner;
import java.util.HashSet;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 91/250
java
import java.util.Scanner;
java
import java.util.Scanner;
import java.util.HashSet;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 92/250
set.remove(arr2[i]); // To avoid duplicates
}
}
}
}
java
import java.util.Scanner;
import java.util.HashSet;
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);
Arrays.sort(arr);
System.out.println(k + "th largest element: " + arr[n - k]);
}
}
java
import java.util.Scanner;
import java.util.HashSet;
java
import java.util.Scanner;
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];
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] != 0) {
arr[count++] = 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!
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 95/250
}
java
import java.util.Scanner;
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;
java
import java.util.Scanner;
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--;
}
java
import java.util.Scanner;
if (isPalindrome) {
System.out.println("The array is a palindrome.");
} else {
System.out.println("The array is not a palindrome.");
}
}
}
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);
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:
java
import java.util.Scanner;
import java.util.Arrays;
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
}
}
java
import java.util.Scanner;
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 100/250
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 101/250
negativeCount++;
}
}
java
import java.util.Scanner;
import java.util.HashMap;
int maxCount = 0;
int maxElement = arr[0];
for (int key : map.keySet()) {
if (map.get(key) > maxCount) {
maxCount = map.get(key);
maxElement = key;
}
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 102/250
int n = scanner.nextInt();
int[] arr = new int[n];
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 103/250
java
import java.util.Scanner;
java
import java.util.Scanner;
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!
java
import java.util.Scanner;
java
import java.util.Scanner;
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;
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++;
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 106/250
Scanner scanner = new Scanner(System.in);
java
import java.util.Scanner;
java
import java.util.Scanner;
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);
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.");
}
}
}
java
import java.util.Scanner;
import java.util.HashMap;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 108/250
java
import java.util.Scanner;
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
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();
java
import java.util.Scanner;
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch) {
count++;
}
}
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:
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 110/250
Scanner scanner = new Scanner(System.in);
java
import java.util.Scanner;
java
import java.util.Scanner;
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
}
}
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 112/250
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 113/250
String input = scanner.nextLine();
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 114/250
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
try {
int number = Integer.parseInt(input);
System.out.println("Converted number: " + number);
} catch (NumberFormatException e) {
System.out.println("Invalid number format.");
}
}
}
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 115/250
Scanner scanner = new Scanner(System.in);
java
import java.util.Scanner;
java
import java.util.Scanner;
if (input.matches("[0-9]+")) {
System.out.println("The string contains only digits.");
} else {
System.out.println("The string contains non-digit characters.");
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 116/250
java
import java.util.Scanner;
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:
java
import java.util.Scanner;
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;
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ch) {
count++;
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
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();
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 119/250
Scanner scanner = new Scanner(System.in);
java
import java.util.Arrays;
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
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);
}
}
java
import java.util.Scanner;
if (str1.equalsIgnoreCase(str2)) {
System.out.println("The strings are equal (case insensitive).");
} else {
System.out.println("The strings are not equal.");
}
}
}
java
import java.util.Scanner;
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:
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 122/250
}
}
java
import java.util.Scanner;
System.out.println("ASCII values:");
for (int i = 0; i < input.length(); i++) {
System.out.println(input.charAt(i) + ": " + (int) input.charAt(i));
}
}
}
java
import java.util.Scanner;
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.");
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 123/250
java
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 124/250
StringBuilder result = new StringBuilder();
java
import java.util.Scanner;
java
import java.util.Scanner;
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.");
}
}
}
java
import java.util.Scanner;
java
import java.util.Scanner;
import java.util.Scanner;
java
import java.util.Scanner;
java
import java.util.Scanner;
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!
java
class Person {
String name;
int age;
java
class Calculator {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
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));
}
}
java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
java
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 129/250
car.move();
}
}
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");
}
}
java
interface Animal {
void sound(); // abstract method
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 130/250
java
void display() {
System.out.println("Shape displayed");
}
}
java
class Counter {
static int count = 0; // Static variable
Counter() {
count++;
System.out.println("Count: " + count);
}
Counter.displayCount();
}
}
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;
}
}
java
class Animal {
void sound() {
System.out.println("Animal makes a 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);
}
}
If you'd like more examples or further explanations on any concept, feel free to ask!
java
class Book {
String title;
String author;
void display() {
System.out.println("Book Title: " + title + ", Author: " + author);
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 133/250
}
}
java
interface Animal {
void sound();
}
interface Movable {
void move();
}
java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 134/250
}
}
java
class Animal {
}
java
class Person {
String name;
// Constructor
Person(String name) {
this.name = name;
}
void display() {
System.out.println("Person's Name: " + name);
}
}
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
}
}
}
java
class OuterClass {
static int outerVar = 10;
java
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);
}
}
java
class BankAccount {
private double balance;
BankAccount(double initialBalance) {
this.balance = initialBalance;
}
void displayBalance() {
System.out.println("Balance: " + balance);
}
}
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!");
}
}
java
interface Animal {
void sound();
}
class AnimalFactory {
public Animal createAnimal(String type) {
if (type.equalsIgnoreCase("Dog")) {
return new Dog();
} else if (type.equalsIgnoreCase("Cat")) {
return new Cat();
}
return null;
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 138/250
}
}
Feel free to ask if you'd like more examples on specific OOP topics or concepts!
java
void display() {
System.out.println("Book Title: " + title + ", Author: " + author);
}
}
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");
}
}
// Overloaded method
void area(double radius) {
System.out.println("Area of Circle with radius " + radius + ": " + (3.14 * radiu
s * radius));
}
}
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");
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 140/250
car.drive();
}
}
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");
}
}
java
class Animal {
Animal() {
System.out.println("Animal is created");
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 141/250
}
}
java
class Person {
String name;
int 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 + "}";
}
}
System.out.println(p1.equals(p2)); // true
System.out.println(p1.hashCode());
System.out.println(p1.toString());
}
}
java
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();
}
}
java
// Concrete method
void breathe() {
System.out.println("Animal breathes");
}
}
java
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);
}
}
If you need more examples or further explanations on any specific concept, feel free to ask!
java
class Person {
private String name;
private int age;
void display() {
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 144/250
System.out.println("Name: " + name + ", Age: " + age);
}
}
java
class MathOperations {
static int square(int number) {
return number * number;
}
}
java
class Outer {
private int outerValue = 10;
class Inner {
void display() {
System.out.println("Outer class value: " + outerValue);
}
}
}
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");
}
}
java
class Animal {
final void speak() {
System.out.println("Animal speaks");
}
}
java
interface Animal {
void sound();
}
interface Movement {
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 146/250
void move();
}
@Override
public void move() {
System.out.println("Dog runs");
}
}
java
void displayMessage() {
System.out.println("Shape is being drawn");
}
}
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
}
java
class Calculator {
int add(int a, int b) {
return a + b;
}
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 148/250
}
}
java
interface Animal {
void sound();
}
Here are some Exception Handling programs in Java, demonstrating different types of exceptions
and how to handle them.
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 149/250
}
}
java
java
java
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());
}
}
}
java
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 151/250
}
}
java
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 152/250
java
java
class Parent {
void methodA() throws Exception {
throw new Exception("Exception in methodA");
}
}
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 153/250
}
}
}
These programs cover a wide range of exception handling techniques in Java, including:
java
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.*;
java
import java.util.logging.*;
java
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);
}
}
}
java
import java.io.*;
java
import java.io.*;
java
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);
}
}
java
import java.io.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 157/250
328. Handling NullPointerException
java
java
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 158/250
java
int getErrorCode() {
return errorCode;
}
}
java
import java.sql.*;
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
Here are Java Collections programs demonstrating the usage of various Collection classes and
interfaces.
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 160/250
335. Using HashSet
java
import java.util.*;
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 161/250
}
}
}
java
import java.util.*;
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 162/250
vector.add("Python");
vector.add("C++");
java
import java.util.*;
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
java
import java.util.*;
while (!pq.isEmpty()) {
System.out.println(pq.poll()); // Retrieves and removes the smallest elemen
t
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 163/250
java
import java.util.*;
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 164/250
Collections.sort(list); // Sorting the list
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 165/250
java
import java.util.*;
java
import java.util.*;
java
import java.util.*;
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:
Here are different types of programs across various Java topics that cover a wide range of
concepts, from basic to advanced:
java
import java.util.*;
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.");
}
}
java
import java.util.*;
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.");
}
}
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 168/250
355. Armstrong Number Check
java
import java.util.*;
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.");
}
}
java
import java.util.*;
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;
int temp = a;
a = b;
b = temp;
java
import java.util.*;
a = a + b;
b = a - b;
a = a - b;
java
import java.util.*;
str = str.toLowerCase();
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);
}
}
java
import java.util.*;
java
import java.util.*;
while (number != 0) {
number /= 10;
count++;
}
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 171/250
while (number != 0) {
sum += number % 10;
number /= 10;
}
java
import java.util.*;
java
import java.util.*;
System.out.println("GCD of " + num1 + " and " + num2 + " is " + gcd);
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 172/250
java
import java.util.*;
while (true) {
if (lcm % num1 == 0 && lcm % num2 == 0) {
System.out.println("LCM of " + num1 + " and " + num2 + " is " + lcm);
break;
}
lcm++;
}
}
}
java
import java.util.*;
if (num1 >=
Here are some additional different types of programs using Java Collections, covering more
advanced usage and operations:
java
import java.util.*;
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;
@Override
public String toString() {
return name + " (" + age + " years)";
}
}
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 174/250
java
import java.util.*;
System.out.println("Stack elements:");
while (!stack.isEmpty()) {
System.out.println(stack.pop());
}
}
}
java
import java.util.*;
@Override
public int compareTo(Student other) {
return this.grade - other.grade; // Sorting by grade
}
@Override
public String toString() {
return name + " (" + grade + ")";
}
}
Collections.sort(students);
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;
@Override
public String toString() {
return name + " ($" + salary + ")";
}
}
java
import java.util.*;
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.*;
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 177/250
for (String language : list) {
System.out.println(language);
}
}
}
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 178/250
java
import java.util.*;
java
import java.util.*;
java
import java.util.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 179/250
System.out.println(language);
}
}
}
Here are some Java File Handling programs, covering common file operations such as reading,
writing, and manipulating files:
java
import java.io.*;
java
import java.io.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 180/250
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java
import java.io.*;
java
import java.io.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 181/250
java
import java.io.*;
java
import java.io.*;
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();
}
}
}
java
import java.io.*;
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.");
}
}
}
java
import java.io.*;
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}
}
java
import java.io.*;
if (files != null) {
for (String file : files) {
System.out.println(file);
}
} else {
System.out.println("The directory is empty or not found.");
}
}
}
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.");
}
}
}
java
import java.io.*;
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.");
}
}
}
java
import java.io.*;
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.*;
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java
import java.io.*;
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();
}
}
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 185/250
java
import java.io.*;
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java
import java.io.*;
import java.util.*;
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
java
import java.io.*;
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`.
Here are some Java programs focused on Recursion, covering a variety of common recursive
problems:
java
java
java
java
java
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));
}
}
java
java
java
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];
}
java
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 190/250
java
java
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 191/250
for (int num : arr) {
System.out.print(num + " ");
}
}
}
java
java
java
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));
}
java
java
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!
java
java
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
java
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 195/250
}
}
java
java
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
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);
head = reverse(head);
java
java
import java.util.*;
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);
}
java
java
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
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!
java
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());
}
}
}
java
java
class Counter {
private int count = 0;
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();
}
java
import java.util.Arrays;
import java.util.List;
java
@FunctionalInterface
interface MyFunctionalInterface {
void sayHello();
}
java
import java.util.*;
import java.util.stream.*;
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);
}
}
java
class Box<T> {
private T value;
public T getValue() {
return value;
}
}
java
import java.lang.reflect.Method;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 202/250
java
import java.io.*;
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + "}";
}
}
java
import java.io.*;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 203/250
e.printStackTrace();
}
}
}
java
import java.util.Optional;
optionalStr.ifPresent(System.out::println);
java
import java.util.concurrent.CompletableFuture;
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 204/250
private Singleton() {
// Private constructor to prevent instantiation
}
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!
java
import java.io.*;
import java.net.*;
while (true) {
Socket clientSocket = serverSocket.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocke
t.getInputStream()));
OutputStreamWriter writer = new OutputStreamWriter(clientSocket.getOutputStr
eam());
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 205/250
}
}
java
import java.sql.*;
while (resultSet.next()) {
System.out.println("ID: " + resultSet.getInt("id") + ", Name: " + result
Set.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
java
import java.util.PriorityQueue;
pq.offer(5);
pq.offer(2);
pq.offer(8);
pq.offer(1);
while (!pq.isEmpty()) {
System.out.println(pq.poll());
}
}
}
import java.io.*;
import java.net.*;
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());
}
}
}
java
import java.util.*;
timer.scheduleAtFixedRate(task, 0, 2000);
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 207/250
}
}
java
class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;
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
}
}
java
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
@Override
public void start(Stage stage) {
display = new TextField();
display.setEditable(false);
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 209/250
}
java
import java.util.*;
interface Observer {
void update(String message);
}
class Subject {
private List<Observer> observers = new ArrayList<>();
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:
java
java
import java.util.HashMap;
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;
}
}
java
class BankAccount {
private double balance;
java
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 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;
}
java
class ATM {
private double balance;
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);
}
java
import java.util.*;
class LRUCache {
private Map<Integer, Integer> cache;
private int capacity;
private LinkedHashMap<Integer, Long> accessTime;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 214/250
int oldestKey = -1;
java
public static void merge(int[] array, int left, int middle, int right) {
int n1 = middle - left + 1;
int n2 = right - middle;
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++;
}
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:
java
import java.util.LinkedList;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 216/250
return entry.getValue();
}
}
return null;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
java
class LinkedList {
private Node head;
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;
}
}
if (head.data == data) {
head = head.next;
return;
}
if (temp.next != null) {
temp.next = temp.next.next;
}
}
}
list.delete(20);
list.display();
}
}
java
class Stack {
private int maxSize;
private int top;
private int[] stack;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 218/250
top = -1;
}
java
class Queue {
private Node front, rear;
private int size;
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;
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 220/250
java
import java.util.PriorityQueue;
pq.add(10);
pq.add(20);
pq.add(15);
java
import java.util.*;
class Graph {
private Map<Integer, List<Integer>> adjList;
public Graph() {
adjList = new HashMap<>();
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 221/250
g.addEdge(2, 0);
g.addEdge(2, 3);
java
import java.util.*;
class Graph {
private Map<Integer, List<Integer>> adjList;
public Graph() {
adjList = new HashMap<>();
}
visited.add(start);
queue.add(start);
while (!queue.isEmpty()) {
int v = queue.poll();
System.out.print(v + " ");
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.
java
class BinarySearchTree {
class Node {
int data;
Node left, right;
public BinarySearchTree() {
root = null;
}
return root;
}
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);
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;
}
}
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]);
}
}
}
g.dijkstra(0);
}
}
java
class CircularQueue {
private int[] queue;
private int front, rear, size, capacity;
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];
}
java
class MergeSort {
public static void mergeSort(int[] arr) {
if (arr.length < 2) {
return;
}
mergeSort(left);
mergeSort(right);
merge(arr, left, right);
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 226/250
arr[k++] = left[i++];
}
MergeSort.mergeSort(arr);
System.out.println("Sorted array:");
MergeSort.printArray(arr);
}
}
java
class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
return i + 1;
}
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();
}
}
System.out.println("Sorted array:");
QuickSort.printArray(arr);
}
}
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 (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}
heapify(arr, i, 0);
}
}
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();
}
}
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!
java
import java.util.*;
class BankAccount {
private int accountNumber;
private String accountHolder;
private double balance;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 229/250
}
account.deposit(1000);
account.checkBalance();
account.withdraw(500);
account.checkBalance();
}
}
Scenario: This program simulates basic bank account operations like deposit, withdrawal, and
balance check.
java
import java.util.*;
class Book {
private String title;
private boolean isAvailable;
class Library {
private List<Book> books;
public Library() {
books = new ArrayList<>();
}
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 230/250
books.add(book);
}
System.out.println("Available Books:");
library.showAvailableBooks();
book1.borrowBook();
book2.borrowBook();
book1.returnBook();
Scenario: A library management system to manage books, their availability, and the
borrowing/returning process.
java
import java.util.*;
class Product {
private String name;
private double 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<>();
}
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.
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;
Scenario: This program calculates the taxi fare based on a base fare and the distance traveled.
java
import java.util.Scanner;
class Student {
private String name;
private double marks;
Scenario: This program takes student details (name and marks), calculates their grade, and displays
the result.
java
import java.util.*;
class Room {
private int roomNumber;
private boolean isBooked;
class Hotel {
private List<Room> rooms;
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.");
}
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!
java
import java.util.*;
class Employee {
private int id;
private String name;
private double salary;
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 235/250
public int getId() {
return id;
}
class EmployeeManagementSystem {
private List<Employee> employees;
public EmployeeManagementSystem() {
employees = new ArrayList<>();
}
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;
class VotingSystem {
private List<Candidate> candidates;
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.
java
import java.util.Scanner;
class ATM {
private double balance;
public ATM() {
this.balance = 10000.0;
}
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.
java
import java.util.*;
class Item {
private String name;
private double price;
class BillingSystem {
private List<Item> items;
public BillingSystem() {
items = new ArrayList<>();
}
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);
}
}
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.
java
import java.util.*;
class Bus {
private int busNumber;
private int totalSeats;
private int availableSeats;
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.");
}
}
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.
java
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 241/250
System.out.println("Lowercase: " + str.toLowerCase());
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
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.*;
// 1. Date Methods
Date currentDate = new Date();
System.out.println("Current Date and Time: " + currentDate);
// 3. List Methods
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
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);
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
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:
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;
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`.
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.*;
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.
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
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.
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;
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.
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
Explanation:
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