100 JAVA Programs for Interview with Answer :
- Hello
World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello,
World!");
}
}
- Print
numbers from 1 to N
public class PrintNumbers {
public static void main(String[] args) {
int N = 10;
for (int i = 1; i <= N; i++) {
System.out.println(i);
}
}
}
- Calculate
the sum of N natural numbers
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: " +
sum);
}
}
- Factorial
of a number
public class Factorial {
public static void main(String[] args) {
int num = 5;
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("Factorial:
" + factorial);
}
}
- Fibonacci
series
public class Fibonacci {
public static void main(String[] args) {
int N = 10;
int first = 0, second = 1;
System.out.print(first + " "
+ second);
for (int i = 2; i < N; i++) {
int next = first + second;
System.out.print(" " +
next);
first = second;
second = next;
}
}
}
- Prime
number checker
public class PrimeChecker {
public static void main(String[] args) {
int num = 17;
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num);
i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
System.out.println(num + " is
prime: " + isPrime);
}
}
- Palindrome
checker
public class
PalindromeChecker {
public static void main(String[] args) {
String str = "radar";
boolean isPalindrome = true;
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) !=
str.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
System.out.println(str + " is
palindrome: " + isPalindrome);
}
}
- Reverse
a string
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
StringBuilder reversed = new
StringBuilder(str).reverse();
System.out.println("Reversed:
" + reversed);
}
}
- Check
for Armstrong number
public class ArmstrongNumber
{
public static void main(String[] args) {
int num = 153;
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;
}
boolean isArmstrong = sum ==
originalNum;
System.out.println(originalNum + "
is Armstrong: " + isArmstrong);
}
}
- Swap
two numbers
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);
}
}
- Find
the largest element in an array
public class LargestElementInArray
{
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
int largest = arr[0];
for (int i = 1; i < arr.length; i++)
{
if (arr[i] > largest) {
largest = arr[i];
}
}
System.out.println("Largest
element: " + largest);
}
}
- Calculate
the average of elements in an array
public class AverageOfArray {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
int sum = 0;
for (int num : arr) {
sum += num;
}
double average = (double) sum /
arr.length;
System.out.println("Average:
" + average);
}
}
- Reverse
an array
public class ReverseArray {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
int left = 0, right = arr.length - 1;
while (left < right) {
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
System.out.print("Reversed array:
");
for (int num : arr) {
System.out.print(num + "
");
}
}
}
- Find
the second largest element
public class
SecondLargestElement {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
int firstLargest = Integer.MIN_VALUE;
int secondLargest = Integer.MIN_VALUE;
for (int num : arr) {
if (num > firstLargest) {
secondLargest = firstLargest;
firstLargest = num;
} else if (num > secondLargest
&& num < firstLargest) {
secondLargest = num;
}
}
System.out.println("Second largest
element: " + secondLargest);
}
}
- Merge
two arrays
public class MergeArrays {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 4, 5, 6 };
int[] merged = new int[arr1.length +
arr2.length];
int index = 0;
for (int num : arr1) {
merged[index] = num;
index++;
}
for (int num : arr2) {
merged[index] = num;
index++;
}
System.out.print("Merged array:
");
for (int num : merged) {
System.out.print(num + " ");
}
}
}
- Count
occurrences of an element
public class CountOccurrences
{
public static void main(String[] args) {
int[] arr = { 1, 2, 2, 3, 2, 4, 5 };
int target = 2;
int count = 0;
for (int num : arr) {
if (num == target) {
count++;
}
}
System.out.println("Occurrences of
" + target + ": " + count);
}
}
- Remove
duplicates from an array
public class RemoveDuplicates
{
public static void main(String[] args) {
int[] arr = { 1, 2, 2, 3, 4, 4, 5 };
int[] unique = new int[arr.length];
int index = 0;
for (int num : arr) {
boolean isDuplicate = false;
for (int i = 0; i < index; i++)
{
if (num == unique[i]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
unique[index] = num;
index++;
}
}
System.out.print("Array with
duplicates removed: ");
for (int i = 0; i < index; i++) {
System.out.print(unique[i] + "
");
}
}
}
- Check
if an array is sorted
public class ArraySortedCheck
{
public static void main(String[] args) {
int[] arr = { 1, 2, 4, 4, 5 };
boolean isSorted = true;
for (int i = 1; i < arr.length; i++)
{
if (arr[i] < arr[i - 1]) {
isSorted = false;
break;
}
}
System.out.println("Array is
sorted: " + isSorted);
}
}
- Find
the intersection of two arrays
public class
ArrayIntersection {
public static void main(String[] args) {
int[] arr1 = { 1, 2, 2, 3, 4, 5 };
int[] arr2 = { 2, 2, 4, 5, 6 };
Set<Integer> set = new
HashSet<>();
for (int num : arr1) {
set.add(num);
}
List<Integer> intersection = new
ArrayList<>();
for (int num : arr2) {
if (set.contains(num)) {
intersection.add(num);
set.remove(num);
}
}
System.out.print("Intersection:
");
for (int num : intersection) {
System.out.print(num + "
");
}
}
}
- Rotate
an array
public class RotateArray {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5 };
int rotateBy = 2;
int n = arr.length;
rotateBy %= n; // Handle cases where
rotateBy is greater than n
int[] rotated = new int[n];
for (int i = 0; i < n; i++) {
rotated[(i + rotateBy) % n] =
arr[i];
}
System.out.print("Rotated array:
");
for (int num : rotated) {
System.out.print(num + "
");
}
}
}
- Count
characters, words, and sentences in a string
public class StringStatistics
{
public static void main(String[] args) {
String text = "Hello, this is a
sample sentence. It contains multiple words.";
int charCount = 0;
int wordCount = 0;
int sentenceCount = 0;
for (char c : text.toCharArray()) {
if (Character.isLetter(c)) {
charCount++;
}
if (c == ' ' || c == '.' || c ==
'?' || c == '!') {
if (charCount > 0) {
wordCount++;
}
if (c == '.' || c == '?' || c
== '!') {
sentenceCount++;
}
charCount = 0;
}
}
System.out.println("Character
count: " + charCount);
System.out.println("Word count:
" + wordCount);
System.out.println("Sentence
count: " + sentenceCount);
}
}
- Convert
uppercase to lowercase and vice versa
public class CaseConversion {
public static void main(String[] args) {
String text = "Hello World";
String uppercase = text.toUpperCase();
String lowercase = text.toLowerCase();
System.out.println("Uppercase:
" + uppercase);
System.out.println("Lowercase:
" + lowercase);
}
}
- Check
if a string is a palindrome
public class StringPalindrome
{
public static void main(String[] args) {
String str = "radar";
boolean isPalindrome = true;
int left = 0, right = str.length() - 1;
while (left < right) {
if (str.charAt(left) !=
str.charAt(right)) {
isPalindrome = false;
break;
}
left++;
right--;
}
System.out.println(str + " is
palindrome: " + isPalindrome);
}
}
- Count
occurrences of a substring
public class
SubstringOccurrences {
public static void main(String[] args) {
String text = "Hello, world!
Hello, universe!";
String substring = "Hello";
int count = 0;
int index = text.indexOf(substring);
while (index != -1) {
count++;
index = text.indexOf(substring,
index + substring.length());
}
System.out.println("Occurrences of
\"" + substring + "\": " + count);
}
}
- Replace
a substring in a string
public class ReplaceSubstring
{
public static void main(String[] args) {
String text = "Hello, world!
Hello, universe!";
String oldSubstring =
"Hello";
String newSubstring = "Hi";
String replaced =
text.replace(oldSubstring, newSubstring);
System.out.println("Replaced:
" + replaced);
}
}
- Check
if two strings are anagrams
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
boolean isAnagram = true;
if (str1.length() != str2.length()) {
isAnagram = false;
} else {
int[] charCount = new int[26]; //
Assuming input contains only lowercase letters
for (char c : str1.toCharArray()) {
charCount[c - 'a']++;
}
for (char c : str2.toCharArray()) {
charCount[c - '
a']--;
}
for (int count : charCount) {
if (count != 0) {
isAnagram = false;
break;
}
}
}
System.out.println("Anagram:
" + isAnagram);
}
}
- Reverse
words in a sentence
public class ReverseWordsInSentence
{
public static void main(String[] args) {
String sentence = "Hello world,
how are you?";
String[] words =
sentence.split("\\s+");
StringBuilder reversedSentence = new
StringBuilder();
for (int i = words.length - 1; i >=
0; i--) {
reversedSentence.append(words[i]).append(" ");
}
System.out.println("Reversed
sentence: " + reversedSentence.toString().trim());
}
}
- Remove
spaces from a string
public class RemoveSpaces {
public static void main(String[] args) {
String sentence = " Hello
world, how are you?
";
String trimmed = sentence.trim();
String noSpaces =
trimmed.replaceAll("\\s+", " ");
System.out.println("Without
spaces: " + noSpaces);
}
}
- Find
the longest common prefix
public class
LongestCommonPrefix {
public static void main(String[] args) {
String[] strings = {
"flower", "flow", "flight" };
String longestPrefix = strings[0];
for (int i = 1; i < strings.length;
i++) {
while
(!strings[i].startsWith(longestPrefix)) {
longestPrefix =
longestPrefix.substring(0, longestPrefix.length() - 1);
}
}
System.out.println("Longest common
prefix: " + longestPrefix);
}
}
- Convert
string to integer (and vice versa)
public class
StringToIntAndViceVersa {
public static void main(String[] args) {
String strNumber = "12345";
int intNumber =
Integer.parseInt(strNumber);
int incremented = intNumber + 1;
String strResult =
String.valueOf(incremented);
System.out.println("Incremented as
string: " + strResult);
}
}
- Factorial
using recursion
public class
FactorialRecursion {
public static void main(String[] args) {
int num = 5;
int factorial =
calculateFactorial(num);
System.out.println("Factorial of
" + num + ": " + factorial);
}
private static int calculateFactorial(int
n) {
if (n == 0 || n == 1) {
return 1;
}
return n * calculateFactorial(n - 1);
}
}
- Fibonacci
using recursion
public class
FibonacciRecursion {
public static void main(String[] args) {
int N = 10;
System.out.print("Fibonacci
series: ");
for (int i = 0; i < N; i++) {
System.out.print(fibonacci(i) +
" ");
}
}
private static int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n -
2);
}
}
- GCD
(Greatest Common Divisor) using recursion
public class GCDRecursion {
public static void main(String[] args) {
int a = 48, b = 18;
int gcd = findGCD(a, b);
System.out.println("GCD of "
+ a + " and " + b + ": " + gcd);
}
private static int findGCD(int a, int b) {
if (b == 0) {
return a;
}
return findGCD(b, a % b);
}
}
- Sum
of digits using recursion
public class
SumOfDigitsRecursion {
public static void main(String[] args) {
int num = 12345;
int sum = calculateSumOfDigits(num);
System.out.println("Sum of digits
in " + num + ": " + sum);
}
private static int calculateSumOfDigits(int
num) {
if (num == 0) {
return 0;
}
return num % 10 + calculateSumOfDigits(num
/ 10);
}
}
- Tower
of Hanoi
public class TowerOfHanoi {
public static void main(String[] args) {
int numDiscs = 3;
solveTowerOfHanoi(numDiscs, 'A', 'C',
'B');
}
private static void solveTowerOfHanoi(int n,
char source, char destination, char auxiliary) {
if (n == 1) {
System.out.println("Move disc
1 from " + source + " to " + destination);
return;
}
solveTowerOfHanoi(n - 1, source,
auxiliary, destination);
System.out.println("Move disc " + n + " from " +
source + " to " + destination);
solveTowerOfHanoi(n - 1, auxiliary,
destination, source);
}
}
- Binary
search using recursion
public class
BinarySearchRecursion {
public static void main(String[] args) {
int[] arr = { 1, 3, 5, 7, 9, 11, 13, 15
};
int target = 7;
int index = binarySearch(arr, target,
0, arr.length - 1);
if (index != -1) {
System.out.println(target + "
found at index " + index);
}
else {
System.out.println(target + "
not found in the array.");
}
}
private static int binarySearch(int[] arr,
int target, int left, int right) {
if (left > right) {
return -1;
}
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
return binarySearch(arr, target,
mid + 1, right);
} else {
return binarySearch(arr, target, left,
mid - 1);
}
}
}
- Calculate
power using recursion
public class
PowerCalculationRecursion {
public static void main(String[] args) {
int base = 2;
int exponent = 5;
int result = calculatePower(base,
exponent);
System.out.println(base + " raised to
the power " + exponent + ": " + result);
}
private static int calculatePower(int base,
int exponent) {
if (exponent == 0) {
return 1;
}
return base * calculatePower(base,
exponent - 1);
}
}
- Print
permutations of a string
public class
StringPermutations {
public static void main(String[] args) {
String str = "abc";
generatePer
mutations(str, 0,
str.length() - 1);
}
private static void generatePermutations(String
str, int left, int right) {
if (left == right) {
System.out.println(str);
return;
}
for (int i = left; i <= right; i++)
{
str = swap(str, left, i);
generatePermutations(str, left + 1,
right);
str = swap(str, left, i);
}
}
private static String swap(String str, int
i, int j) {
char[] charArray = str.toCharArray();
char temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = temp;
return new String(charArray);
}
}
- Print
combinations of a string
public class
StringCombinations {
public static void main(String[] args) {
String str = "abc";
int r = 2; // Combination length
generateCombinations(str, new char[r],
0, 0);
}
private static void
generateCombinations(String str, char[] data, int start, int index) {
if (index == data.length) {
System.out.println(new
String(data));
return;
}
for (int i = start; i <
str.length(); i++) {
data[index] = str.charAt(i);
generateCombinations(str, data, i +
1, index + 1);
}
}
}
- Recursive
palindrome check
public class
RecursivePalindrome {
public static void main(String[] args) {
String str = "radar";
boolean isPalindrome =
checkPalindrome(str, 0, str.length() - 1);
System.out.println(str + " is
palindrome: " + isPalindrome);
}
private static boolean checkPalindrome(String
str, int left, int right) {
if (left >= right) {
return true;
}
if (str.charAt(left) !=
str.charAt(right)) {
return false;
}
return checkPalindrome(str, left + 1,
right - 1);
}
}
- Bubble
Sort
public class BubbleSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
bubbleSort(arr);
System.out.print("Sorted array:
");
for (int num : arr) {
System.out.print(num + "
");
}
}
private static void bubbleSort(int[] arr) {
int n = arr.length;
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;
}
}
}
}
}
- Selection
Sort
public class SelectionSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
selectionSort(arr);
System.out.print("Sorted array:
");
for (int num : arr) {
System.out.print(num + "
");
}
}
private static void selectionSort(int[]
arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++)
{
if (arr[j] < arr[minIndex])
{
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
- Insertion
Sort
public class InsertionSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
insertionSort(arr);
System.out.print("Sorted array:
");
for (int num : arr) {
System.out.print(num + "
");
}
}
private static void insertionSort(int[]
arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j]
> key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
}
- Merge
Sort
public class MergeSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
mergeSort(arr, 0, arr.length - 1);
System.out.print("Sorted array:
");
for (int num : arr) {
System.out.print(num + "
");
}
}
private static void mergeSort(int[] arr,
int left, int right) {
if (left < right) {
int mid = left + (right - left) /
2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
private static void merge(int[] arr, int
left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int[] leftArray = new int[n1];
int[] rightArray = new int[n2];
for (int i = 0; i < n1; i++) {
leftArray[i] = arr[left + i];
}
for (int i = 0; i < n2; i++) {
rightArray[i] = arr[mid + 1 + i];
}
int i = 0, j = 0, k = left;
while (i < n1 && j < n2)
{
if (leftArray[i] <=
rightArray[j]) {
arr[k] = leftArray[i];
i++;
} else {
arr[k] = rightArray[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = leftArray[i];
i++;
k++;
}
while (j < n2) {
arr[k] = rightArray[j];
j++;
k++;
}
}
}
- Quick
Sort
public class QuickSort {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
quickSort(arr, 0, arr.length - 1);
System.out.print("Sorted array:
");
for (int num : arr) {
System.out.print(num + "
");
}
}
private static void quickSort(int[] arr,
int low, int high) {
if (low < high) {
int pivotIndex = partition(arr,
low, high);
quickSort(arr, low, pivotIndex -
1);
quickSort(arr, pivotIndex + 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;
}
}
- Binary
Search
public class BinarySearch {
public static void main(String[] args) {
int[] arr = { 1, 3, 5, 7, 9, 11, 13, 15
};
int target = 7;
int index = binarySearch(arr, target);
if (index != -1) {
System.out.println(target + "
found at index " + index);
} else {
System.out.println(target + "
not found in the array.");
}
}
private static int binarySearch(int[] arr,
int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) /
2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
- Linear
Search
public class LinearSearch {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
int target = 8;
int index = linearSearch(arr, target);
if (index != -1) {
System.out.println(target + " found at
index " + index);
} else {
System.out.println(target + "
not found in the array.");
}
}
private static int linearSearch(int[] arr,
int target) {
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == target) {
return i;
}
}
return -1;
}
}
- Find
Kth largest/smallest element
import java.util.Arrays;
public class
KthLargestSmallest {
public static void main(String[] args) {
int[] arr = { 5, 2, 8, 10, 1 };
int k = 3;
int kthLargest = findKthLargest(arr,
k);
System.out.println("Kth largest
element: " + kthLargest);
int kthSmallest = findKthSmallest(arr,
k);
System.out.println("Kth smallest
element: " + kthSmallest);
}
private static int findKthLargest(int[]
arr, int k) {
Arrays.sort(arr);
return arr[arr.length - k];
}
private static int findKthSmallest(int[]
arr, int k) {
Arrays.sort(arr);
return arr[k - 1];
}
}
- Counting
Sort
public class CountingSort {
public static void main(String[] args) {
int[] arr = { 4, 2, 2, 8, 3, 3, 1 };
countingSort(arr);
System.out.print("Sorted array:
");
for (int num : arr) {
System.out.print(num + "
");
}
}
private static void countingSort(int[] arr)
{
int max =
Arrays.stream(arr).max().getAsInt();
int min =
Arrays.stream(arr).min().getAsInt();
int range = max - min + 1;
int[] count = new int[range];
int[] output = new int[arr.length];
for (int num : arr) {
count[num - min]++;
}
for (int i = 1; i < range; i++) {
count[i] += count[i - 1];
}
for (int i = arr.length - 1; i >= 0;
i--) {
output[count[arr[i] - min] - 1] =
arr[i];
count[arr[i] - min]--;
}
for (int i = 0; i < arr.length; i++)
{
arr[i] = output[i];
}
}
}
- Radix
Sort
public class RadixSort {
public static void main(String[] args) {
int[] arr = { 170, 45, 75, 90, 802, 24,
2, 66 };
radixSort(arr);
System.out.print("Sorted array:
");
for (int num : arr) {
System.out.print(num + "
");
}
}
private static void radixSort(int[] arr) {
int max =
Arrays.stream(arr).max().getAsInt();
for (int exp = 1; max / exp > 0; exp
*= 10) {
countSort(arr, exp);
}
}
private static void countSort(int[] arr,
int exp) {
int n = arr.length;
int[] output = new int[n];
int[] count = new int[10];
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % 10]++;
}
for (int i = 1; i < 10; i++) {
count[i] += count[i - 1];
}
for (int i = n - 1; i >= 0
; i--) {
output[count[(arr[i] / exp) % 10] -
1] = arr[i];
count[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
}
- Implement
a Stack
import
java.util.EmptyStackException;
class Stack {
private int[] data;
private int top;
private int capacity;
public Stack(int capacity) {
this.capacity = capacity;
this.data = new int[capacity];
this.top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == capacity - 1;
}
public void push(int value) {
if (isFull()) {
throw new
StackOverflowError("Stack is full");
}
data[++top] = value;
}
public int pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
return data[top--];
}
public int peek() {
if (isEmpty()) {
throw new EmptyStackException();
}
return data[top];
}
}
public class
StackImplementation {
public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Peek: " +
stack.peek());
System.out.println("Pop: " +
stack.pop());
System.out.println("Peek: " +
stack.peek());
}
}
- Implement
a Queue
import java.util.LinkedList;
import java.util.Queue;
public class
QueueImplementation {
public static void main(String[] args) {
Queue<Integer> queue = new
LinkedList<>();
queue.offer(1);
queue.offer(2);
queue.offer(3);
System.out.println("Peek: " +
queue.peek());
System.out.println("Poll: " +
queue.poll());
System.out.println("Peek: " +
queue.peek());
}
}
- Implement
a Linked List
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
class LinkedList {
ListNode head;
void insert(int val) {
ListNode newNode = new ListNode(val);
newNode.next = head;
head = newNode;
}
void display() {
ListNode current = head;
while (current != null) {
System.out.print(current.val +
" -> ");
current = current.next;
}
System.out.println("null");
}
}
public class
LinkedListImplementation {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(3);
list.insert(2);
list.insert(1);
list.display();
}
}
- Implement
a Binary Search Tree
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
class BinarySearchTree {
TreeNode root;
void insert(int val) {
root = insertRec(root, val);
}
TreeNode insertRec(TreeNode root, int val)
{
if (root == null) {
root = new TreeNode(val);
return root;
}
if (val < root.val) {
root.left = insertRec(root.left,
val);
} else if (val > root.val) {
root.right = insertRec(root.right,
val);
}
return root;
}
void inorderTraversal(TreeNode root) {
if (root != null) {
inorderTraversal(root.left);
System.out.print(root.val + "
");
inorderTraversal(root.right);
}
}
}
public class
BinarySearchTreeImplementation {
public static void main(String[] args) {
BinarySearchTree tree = new
BinarySearchTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
tree.inorderTraversal(tree.root);
}
}
- Implement
a Hash Map
import java.util.ArrayList;
import java.util.List;
class KeyValue {
int key;
int value;
KeyValue(int key, int value) {
this.key = key;
this.value = value;
}
}
class HashMap {
private List<KeyValue>[] map;
private int capacity;
public HashMap(int capacity) {
this.capacity = capacity;
this.map = new ArrayList[capacity];
}
private int hash(int key) {
return key % capacity;
}
public void put(int key, int value) {
int hash = hash(key);
if (map[hash] == null) {
map[hash] = new
ArrayList<>();
}
for (KeyValue entry : map[hash]) {
if (entry.key == key) {
entry.value = value;
return;
}
}
map[hash].add(new KeyValue(key,
value));
}
public int get(int key) {
int hash = hash(key);
if (map[hash] != null) {
for (KeyValue entry : map[hash]) {
if (entry.key == key) {
return entry.value;
}
}
}
return -1;
}
public void remove(int key) {
int hash = hash(key);
if (map[hash] != null) {
for (KeyValue entry : map[hash]) {
if (entry.key == key) {
map[hash].remove(entry);
return;
}
}
}
}
}
public class
HashMapImplementation {
public static void main(String[] args) {
HashMap map = new HashMap(10);
map.put(1, 10);
map.put(2, 20);
map.put(11, 110);
map.put(21, 210);
System.out.println("Value at key
1: " + map.get(1));
System.out.println("Value at key
11: " + map.get(11));
System.out.println("Value at key
3: " + map.get(3));
map.remove(2);
System.out.println("Value at key 2
(after removal): " + map.get(2));
}
}
- Implement
a Graph
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Graph {
private Map<Integer,
List<Integer>> adjacencyList;
public Graph() {
this.adjacencyList = new HashMap<>();
}
public void addVertex(int vertex) {
adjacencyList.put(vertex, new
ArrayList<>());
}
public void addEdge(int source, int
destination) {
adjacencyList.get(source).add(destination);
adjacencyList.get(destination).add(source); // For undirected graph
}
public List<Integer> getNeighbors(int
vertex) {
return adjacencyList.get(vertex);
}
}
public class
GraphImplementation {
public static void main(String[] args) {
Graph graph = new Graph();
graph.add
Vertex(0);
graph.addVertex(1);
graph.addVertex(2);
graph.addVertex(3);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(2, 3);
List<Integer> neighbors =
graph.getNeighbors(0);
System.out.println("Neighbors of
vertex 0: " + neighbors);
}
}
- Implement
a Priority Queue (Heap)
import
java.util.PriorityQueue;
public class
PriorityQueueImplementation {
public static void main(String[] args) {
PriorityQueue<Integer> minHeap =
new PriorityQueue<>();
minHeap.offer(5);
minHeap.offer(2);
minHeap.offer(8);
minHeap.offer(1);
System.out.println("Min element:
" + minHeap.peek());
System.out.println("Poll: " +
minHeap.poll());
System.out.println("Min element
after poll: " + minHeap.peek());
}
}
- Implement
a Trie
class TrieNode {
TrieNode[] children;
boolean isEndOfWord;
TrieNode() {
this.children = new TrieNode[26];
this.isEndOfWord = false;
}
}
class Trie {
private TrieNode root;
Trie() {
this.root = new TrieNode();
}
void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
node.children[index] = new
TrieNode();
}
node = node.children[index];
}
node.isEndOfWord = true;
}
boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
return false;
}
node = node.children[index];
}
return node.isEndOfWord;
}
boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
int index = c - 'a';
if (node.children[index] == null) {
return false;
}
node = node.children[index];
}
return true;
}
}
public class
TrieImplementation {
public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("apple");
System.out.println("Search for
'apple': " + trie.search("apple")); // Output: true
System.out.println("Search for
'app': " + trie.search("app")); // Output: false
System.out.println("Starts with
'app': " + trie.startsWith("app")); // Output: true
trie.insert("app");
System.out.println("Search for
'app': " + trie.search("app")); // Output: true
}
}
- Implement
a Red-Black Tree
enum Color {
RED,
BLACK
}
class RBTreeNode {
int val;
RBTreeNode parent;
RBTreeNode left;
RBTreeNode right;
Color color;
RBTreeNode(int val) {
this.val = val;
this.color = Color.RED;
}
}
class RedBlackTree {
private RBTreeNode root;
private RBTreeNode nil; // Sentinel node
public RedBlackTree() {
nil = new RBTreeNode(-1);
nil.color = Color.BLACK;
root = nil;
}
// Insertion, deletion, and balancing
operations here...
}
public class
RedBlackTreeImplementation {
public static void main(String[] args) {
RedBlackTree tree = new RedBlackTree();
// Perform insertion, deletion, or
other operations on the Red-Black Tree
}
}
- Implement
an AVL Tree
class AVLTreeNode {
int val;
int height;
AVLTreeNode left;
AVLTreeNode right;
AVLTreeNode(int val) {
this.val = val;
this.height = 1;
}
}
class AVLTree {
private AVLTreeNode root;
// Insertion, deletion, and balancing
operations here...
}
public class
AVLTreeImplementation {
public static void main(String[] args) {
AVLTree tree = new AVLTree();
// Perform insertion, deletion, or
other operations on the AVL Tree
}
}
- Create
a class and object
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void display() {
System.out.println("Name: " +
name + ", Age: " + age);
}
}
public class ClassAndObject {
public static void main(String[] args) {
Person person1 = new
Person("Alice", 25);
person1.display();
Person person2 = new
Person("Bob", 30);
person2.display();