Saturday, July 26, 2025

10 Java Code Snippets to Test Your Output Prediction Skills

 

๐Ÿง  10 Java Output Questions That Will Sharpen Your Mind

One of the best ways to strengthen your Java skills is by predicting what a program prints without running it. These snippets test your understanding of concepts like operators, memory, method overloading, strings, and more. Ready for a brain workout?


✅ 1. String Pool Puzzle

public class Test1 {
    public static void main(String[] args) {
        String s1 = "hello";
        String s2 = new String("hello");
        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));
    }
}

๐ŸŸก Output:

false
true

✅ 2. Post-Increment Confusion

public class Test2 {
    public static void main(String[] args) {
        int x = 5;
        int y = x++;
        System.out.println(x);
        System.out.println(y);
    }
}

๐ŸŸก Output:

6
5

✅ 3. Static vs Instance Method

class Demo {
    static void print() {
        System.out.println("Static");
    }
    void show() {
        System.out.println("Instance");
    }
    public static void main(String[] args) {
        Demo d = null;
        d.print();
        // d.show(); // Uncomment this line and see what happens
    }
}

๐ŸŸก Output:

Static

(Calling static method via null object is allowed, but not instance methods.)


✅ 4. String Immutability Trap

public class Test4 {
    public static void main(String[] args) {
        String s = "abc";
        s.concat("def");
        System.out.println(s);
    }
}

๐ŸŸก Output:

abc

(Strings are immutable. concat doesn’t change the original unless assigned.)


✅ 5. Switch Without Break

public class Test5 {
    public static void main(String[] args) {
        int day = 2;
        switch(day) {
            case 1: System.out.println("Mon");
            case 2: System.out.println("Tue");
            case 3: System.out.println("Wed");
        }
    }
}

๐ŸŸก Output:

Tue
Wed

✅ 6. Overloading Mystery

public class Test6 {
    void test(int a) {
        System.out.println("int");
    }
    void test(Integer a) {
        System.out.println("Integer");
    }
    public static void main(String[] args) {
        new Test6().test(10);
    }
}

๐ŸŸก Output:

int

(Primitive match is preferred over wrapper type.)


✅ 7. Array Printing

public class Test7 {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3};
        System.out.println(arr);
    }
}

๐ŸŸก Output:

[I@15db9742

(Default toString() on array shows object reference. Use Arrays.toString() for readable output.)


✅ 8. Final Parameters

public class Test8 {
    public static void main(final String[] args) {
        args[0] = "Changed";
        System.out.println(args[0]);
    }
}

๐ŸŸก Output:

Changed

(You can change contents of final reference, not the reference itself.)


✅ 9. Null Argument Overloading

public class Test9 {
    void print(Object o) {
        System.out.println("Object");
    }
    void print(String s) {
        System.out.println("String");
    }
    public static void main(String[] args) {
        new Test9().print(null);
    }
}

๐ŸŸก Output:

String

(Most specific method is chosen when calling with null.)


✅ 10. Wrapper Caching

public class Test10 {
    public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;
        Integer x = 200;
        Integer y = 200;
        System.out.println(a == b);
        System.out.println(x == y);
    }
}

๐ŸŸก Output:

true
false

(Integer caching works for values between -128 and 127.)


๐Ÿ’ก Final Thoughts

These snippets aren't just trivia — they reveal how Java handles memory, types, and execution flow. Try modifying each example slightly to see how behavior changes!


Would you like this exported as an HTML/Markdown blog, or want an image for social sharing?





This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication

Saturday, July 12, 2025

Reversing a LinkedList in Java: A Step-by-Step Guide


Whether you're preparing for coding interviews or building scalable backend systems, knowing how to reverse a LinkedList is a must-have skill in any Java developer's toolkit.

In this blog, we'll cover:

  • What a LinkedList is
  • Why reversing it matters
  • How to reverse it using both iterative and recursive approaches
  • Bonus: Reversing a LinkedList using Java's built-in class

๐Ÿง  What is a LinkedList?

A LinkedList is a linear data structure where each element (called a node) contains:

  • Data
  • A reference (or pointer) to the next node

Example:

Head → 1 → 2 → 3 → 4 → null

Reversing the list would result in:

Head → 4 → 3 → 2 → 1 → null

๐Ÿ”ง Custom Singly LinkedList in Java

First, let's define a simple Node class and build our custom LinkedList.

class Node {
    int data;
    Node next;

    Node(int data) {
        this.data = data;
        this.next = null;
    }
}

๐Ÿ” Iterative Approach to Reverse a LinkedList

Code:

public Node reverseList(Node head) {
    Node prev = null;
    Node current = head;
    Node next = null;

    while (current != null) {
        next = current.next;   // store next
        current.next = prev;   // reverse current node's pointer
        prev = current;        // move pointers one step forward
        current = next;
    }

    return prev; // new head
}

How it Works:

  • Traverse through the list
  • Reverse the link direction for each node
  • Use three pointers (prev, current, next) to safely navigate and modify links

๐Ÿ”„ Recursive Approach to Reverse a LinkedList

Code:

public Node reverseRecursive(Node head) {
    if (head == null || head.next == null) {
        return head;
    }

    Node rest = reverseRecursive(head.next);
    head.next.next = head;
    head.next = null;

    return rest;
}

How it Works:

  • Recursively reverse all nodes after the head
  • Set the next node's next pointer to the current node
  • Set current node’s next to null (to prevent cycles)

✅ Bonus: Reversing Java’s Built-in LinkedList

If you’re using Java’s LinkedList<E> class from the java.util package:

Code:

LinkedList<Integer> list = new LinkedList<>(Arrays.asList(1, 2, 3, 4));
Collections.reverse(list);
System.out.println(list); // Output: [4, 3, 2, 1]

Super simple — but remember, this only reverses the order of the list, not the underlying pointers like in a custom linked structure.


๐Ÿงช Testing the Reversed List

Here's a quick utility function to print a LinkedList:

public void printList(Node head) {
    while (head != null) {
        System.out.print(head.data + " → ");
        head = head.next;
    }
    System.out.println("null");
}

๐Ÿ Final Thoughts

Reversing a LinkedList is more than an academic exercise — it's foundational for mastering data structures and acing technical interviews. Whether you're iterating or recursing, the underlying logic builds your muscle memory in pointer manipulation and algorithm design.

Next Step? Try reversing a doubly linked list or reversing only part of the list (e.g., from position m to n) for an extra challenge!


๐Ÿ’ฌ What’s your preferred method—iterative or recursive? Let us know in the comments!




This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication

Sunday, July 6, 2025

Mastering Java Strings: Detecting Repeating Characters Using HashMap in Just a Few Lines

 


Whether you're prepping for a coding interview or cleaning messy data, identifying character repetition in a string is a classic challenge—and HashMap makes it surprisingly elegant in Java. In this blog, we’ll walk through the step-by-step logic, code, and a few clever tricks to help you nail it.


๐Ÿง  Why Use a HashMap?

It offers constant-time lookup for keys.

Helps track frequency efficiently without manual looping.

Ideal for character counting in strings.


✍️ The Problem

Given a string like "JavaProgramming", we want to:

Count how many times each character occurs.

Identify which characters repeat.


⚙️ The Plan

Convert the string to a character array.

Use a HashMap<Character, Integer> to store character frequencies.

Loop through the map to find characters with count > 1.


๐Ÿ“œ Java Code Example

import java.util.HashMap;


public class RepeatingCharacters {

    public static void main(String[] args) {

        String input = "JavaProgramming";

        findRepeatingCharacters(input);

    }


    public static void findRepeatingCharacters(String str) {

        HashMap<Character, Integer> charCountMap = new HashMap<>();


        // Step 1: Populate map with character frequencies

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

            c = Character.toLowerCase(c); // optional: handle case insensitivity

            charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);

        }


        // Step 2: Print characters with count > 1

        System.out.println("Repeating characters in the string:");

        for (char c : charCountMap.keySet()) {

            if (charCountMap.get(c) > 1) {

                System.out.println(c + " occurs " + charCountMap.get(c) + " times");

            }

        }

    }

}


๐Ÿงช Output Example

For input "JavaProgramming", you'd get something like:

a occurs 3 times  

g occurs 2 times  

r occurs 2 times  

m occurs 2 times  


๐Ÿงฉ Tips and Tricks

Want to ignore spaces and punctuation? Add a filter in the loop.

Need to sort by frequency? Use LinkedHashMap or sort entries manually.

Looking to highlight the first repeating character? You can break out of the loop as soon as a repeat is found.


This simple use of HashMap elegantly solves a common string processing task. Want help extending it to Unicode characters, user input, or performance tuning? Just tap me on the shoulder—I’ve got ideas ๐Ÿค“



This Content Sponsored by Buymote Shopping app

BuyMote E-Shopping Application is One of the Online Shopping App

Now Available on Play Store & App Store (Buymote E-Shopping)

Click Below Link and Install Application: https://buymote.shop/links/0f5993744a9213079a6b53e8

Sponsor Content: #buymote #buymoteeshopping #buymoteonline #buymoteshopping #buymoteapplication