Skip to main content

Basic Coding - Section 1

1. Reverse a number

public class NumReverse {
public static int reverse(int number) {
int reverse = 0;
int reminder;

while (number > 0) {
reminder = number % 10;
reverse = (reverse * 10) + reminder;
number = number / 10;
}
return reverse;
}

public static void main(String[] args) {
int number = 358;
System.out.println("Reversed Number is:" + reverse(number));
}
}

Output

Reversed Number is:853

2. Reverse a number with Recursion

public class NumReverseWithRecursion {
static int reverse = 0;

static void reverse(int number){
if(number<=0)
return;
int reminder = number % 10;
reverse = (reverse * 10) + reminder;
reverse(number / 10);
}

public static void main(String[] args) {
int number = 1234;
reverse(number);
System.out.print("Reversed Number is: " + reverse);
}
}

Output:

Reversed Number is: 4321

3. Reverse using StringBuilder

public class StringBuilderReverse {
public static void main(String[] args) {
int number = 123456;
String temp = ""+number;

StringBuilder sb = new StringBuilder(temp);
StringBuilder str = sb.reverse();
System.out.println("Reversed String is: "+str.toString());
}
}

Output:

Reversed String is: 654321

Basic Coding - Section 2

1. Reverse a String

 public static String reverseString(String s) {
return new StringBuilder(s).reverse().toString();
}

2. FizzBuzz (1–100)

public static void fizzBuzz() {
for (int i = 1; i <= 100; i++) {
if (i % 15 == 0) System.out.println("FizzBuzz");
else if (i % 3 == 0) System.out.println("Fizz");
else if (i % 5 == 0) System.out.println("Buzz");
else System.out.println(i);
}
}

3. Two Sum

public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
return new int[0];
}

4. Palindrome Check

public static boolean isPalindrome(String s) {
int i = 0, j = s.length() - 1;
while (i < j) {
if (s.charAt(i) != s.charAt(j)) return false;
i++; j--;
}
return true;
}

5. Missing Number

public static int missingNumber(int[] nums) {
int n = nums.length;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : nums) actualSum += num;
return expectedSum - actualSum;
}

6. Detect Duplicates

public static boolean hasDuplicates(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num)) return true;
}
return false;
}

7. Reverse Linked List

    static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode reverseList(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
    public static int binarySearch(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}

9. Merge Sort

    public static void mergeSort(int[] arr, int l, int r) {
if (l < r) {
int m = (l + r) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
private static void merge(int[] arr, int l, int m, int r) {
int n1 = m - l + 1, n2 = r - m;
int[] L = new int[n1], R = new int[n2];
for (int i = 0; i < n1; i++) L[i] = arr[l + i];
for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
arr[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}

10. Second Largest Number

    public static int secondLargest(int[] nums) {
int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : nums) {
if (num > max) {
second = max;
max = num;
} else if (num > second && num != max) {
second = num;
}
}
return second;
}

11. Check Prime Number

    public static boolean isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) return false;
}
return true;
}

12. Fibonacci (Recursion)

    public static int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}

13. Count Words in a Sentence

    public static int countWords(String s) {
s = s.trim();
if (s.isEmpty()) return 0;
return s.split("\\s+").length;
}

14. Shuffle an Array

    public static void shuffleArray(int[] a) {
Random rand = new Random();
for (int i = 0; i < a.length; i++) {
int j = rand.nextInt(a.length);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}

15. Reverse String Without Built-In

    public static String reverseManual(String s) {
char[] c = s.toCharArray();
for (int i = 0; i < c.length / 2; i++) {
char temp = c[i];
c[i] = c[c.length - 1 - i];
c[c.length - 1 - i] = temp;
}
return new String(c);
}

16. Remove Spaces

    public static String removeSpaces(String s) {
return s.replaceAll("\\s", "");
}

17. Trim Leading and Trailing Spaces

   public static String trimSpaces(String s) {
return s.strip();
}

18. Sort an Array

    public static void sortArray(int[] a) {
Arrays.sort(a);
}

19. Check If Only Odds

    public static boolean onlyOdds(List<Integer> list) {
return list.stream().allMatch(x -> x % 2 != 0);
}

20. Factorial

    public static long factorial(int n) {
return (n <= 1) ? 1 : n * factorial(n - 1);
}

21. Swap Two Numbers Without Temp

    public static void swap(int a, int b) {
a = a + b;
b = a - b;
a = a - b;
System.out.println("a=" + a + " b=" + b);
}

22. Count Distinct Characters

    public static Map<Character, Integer> countDistinctChars(String s) {
Map<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
return map;
}

23. Immutable String Demo

    public static void immutableDemo() {
String s1 = "Java";
String s2 = s1;
s1 = "Python";
System.out.println("s1: " + s1); // Python
System.out.println("s2: " + s2); // Java
}

24. Character Pyramid

    public static void printPyramid(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n - i; j++) System.out.print(" ");
for (int j = 0; j < 2 * i - 1; j++) System.out.print("*");
System.out.println();
}
}

25. Exception Handling


public static void fileReadDemo() {
try {
FileInputStream fis = new FileInputStream("file.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

26. Deadlock Example


static class Deadlock {
final Object lock1 = new Object();
final Object lock2 = new Object();

public void method1() {
synchronized (lock1) {
synchronized (lock2) {
System.out.println("Method 1");
}
}
}

public void method2() {
synchronized (lock2) {
synchronized (lock1) {
System.out.println("Method 2");
}
}
}
}

27. Enum Example


enum State { START, RUNNING, WAITING, DEAD }

28. Record Example (Java 16+)


record Person(String name, int age) {}

29. Text Blocks Example (Java 15+)


public static void textBlockExample() {
String text = """
Line1
Line2
""";
System.out.println(text);
}

30. Max Depth of Binary Tree


static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static int maxDepth(TreeNode root) {
return (root == null) ? 0 : 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}