Featured Post

How to Get Your First IT Job With No Experience

10 Top Java Interview Questions Coding: That Often Ask to Freshers

Top 10 Java interview questions coding for freshers with laptop and code

I still remember sitting in my first Java interview, palms sweating, wondering if I'd prepared enough. The interviewer opened his laptop and said, "Let's start with something simple—reverse a string without using any built-in methods." My mind went blank for a second, but thankfully, I'd practiced this exact problem the week before.

If you're preparing for Java interviews, you're probably feeling the same mix of excitement and nervousness. The good news? Most companies ask similar fundamental questions, especially for fresher positions. I've compiled the 10 most common java interview questions coding that keep showing up across different companies. These aren't just random problems—these are the ones I've faced myself and seen my friends encounter repeatedly.


Why Do Interviewers Keep Asking These Same Questions?

Here's something I learned after sitting on both sides of the interview table: interviewers aren't trying to trick you. They want to see how you think, how you handle pressure, and whether you actually understand Java basics or just memorized syntax.

These classic java interview questions programs reveal more than you'd think. When you're solving them, the interviewer is watching:

  • How you break down problems
  • Whether you ask clarifying questions
  • If you test your code mentally before running it
  • How you handle mistakes (because we all make them!)

The 10 Questions That Keep Coming Up

1. Reverse a String Without Using Built-in Methods

The Question: Write a Java program to reverse a string without using the reverse() method.

Honestly, this was the first coding question I ever faced in an interview. It seems simple, but it tests whether you understand arrays and loops properly.

Here's How I Solved It:

public class ReverseString {
    public static String reverseStr(String input) {
        char[] characters = input.toCharArray();
        int left = 0, right = characters.length - 1;
        
        while (left < right) {
            // Swap characters
            char temp = characters[left];
            characters[left] = characters[right];
            characters[right] = temp;
            left++;
            right--;
        }
        return new String(characters);
    }
    
    public static void main(String[] args) {
        System.out.println(reverseStr("Hello World")); // dlroW olleH
    }
}

What I Learned: The two-pointer approach is your best friend. Start from both ends and swap as you move toward the center. Simple, elegant, and interviewers love it.


2. Check if a Number is Prime

The Question: Write a program to check whether a given number is prime.

I've seen this question in at least 5 different interviews. It's a classic test of your mathematical thinking and loop control.

My Solution:

public class PrimeCheck {
    public static boolean isPrime(int num) {
        if (num <= 1) return false;
        if (num == 2) return true;
        if (num % 2 == 0) return false;
        
        // Only check odd numbers up to square root
        for (int i = 3; i <= Math.sqrt(num); i += 2) {
            if (num % i == 0) return false;
        }
        return true;
    }
    
    public static void main(String[] args) {
        System.out.println(isPrime(17)); // true
        System.out.println(isPrime(20)); // false
    }
}

Pro Tip from Experience: In my second interview, I wrote a basic version that checked every number up to n. The interviewer asked, "Can you optimize this?" That's when I learned about checking only up to the square root. Always be ready to improve your first solution!


3. Find Duplicate Elements in an Array

The Question: Write a Java program to find and print duplicate elements in an array.

This is where knowing your data structures pays off. My first attempt involved nested loops (which worked, but was slow). Then I discovered HashSet, and everything changed.

The Better Approach:

import java.util.HashSet;

public class FindDuplicates {
    public static void findDuplicates(int[] arr) {
        HashSet<Integer> set = new HashSet<>();
        HashSet<Integer> duplicates = new HashSet<>();
        
        for (int num : arr) {
            if (!set.add(num)) {
                duplicates.add(num);
            }
        }
        System.out.println("Duplicates: " + duplicates);
    }
    
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 2, 5, 6, 3};
        findDuplicates(numbers);
    }
}

Real Talk: When I used HashSet in an interview, the interviewer immediately perked up. It showed I knew about collections, not just basic arrays. Small things like this make a difference.


4. Fibonacci Series Generation

The Question: Generate the first N numbers of the Fibonacci sequence.

Ah, Fibonacci—the problem that appears in literally every java interview questions core java list. You'll see this one coming from a mile away.

The Smart Way (Iterative):

public class Fibonacci {
    public static void printFibonacci(int n) {
        int first = 0, second = 1;
        
        for (int i = 0; i < n; i++) {
            System.out.print(first + " ");
            int next = first + second;
            first = second;
            second = next;
        }
    }
    
    public static void main(String[] args) {
        printFibonacci(10); // 0 1 1 2 3 5 8 13 21 34
    }
}

Lesson I Learned the Hard Way: Yes, recursion looks cool and elegant. But when the interviewer asked me to generate the first 50 Fibonacci numbers using recursion, my code took forever to run. Iteration is faster and more practical here.


5. Check if a String is a Palindrome

The Question: Write a program to check if a given string is a palindrome.

This one trips people up because of edge cases. What about spaces? Capital letters? Special characters?

My Foolproof Solution:

public class PalindromeCheck {
    public static boolean isPalindrome(String str) {
        // Remove non-alphanumeric and convert to lowercase
        str = str.toLowerCase().replaceAll("[^a-z0-9]", "");
        int left = 0, right = str.length() - 1;
        
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
    
    public static void main(String[] args) {
        System.out.println(isPalindrome("A man, a plan, a canal: Panama")); // true
        System.out.println(isPalindrome("Hello")); // false
    }
}

Interview Tip: Always ask about edge cases before coding. "Should I ignore spaces and punctuation?" This shows you're thinking ahead.


6. Calculate Factorial Using Recursion

The Question: Calculate the factorial of a given number using recursion.

This is the classic recursion problem in every java interview questions programs for freshers collection.

Simple Recursive Solution:

public class Factorial {
    public static long factorial(int n) {
        if (n == 0 || n == 1) return 1;
        return n * factorial(n - 1);
    }
    
    public static void main(String[] args) {
        System.out.println(factorial(5)); // 120
        System.out.println(factorial(7)); // 5040
    }
}

Word of Caution: I once confidently wrote this in an interview, then the interviewer asked, "What happens with factorial(20)?" It overflows! Be ready to discuss limitations and mention BigInteger for large numbers.


7. Implement Bubble Sort

The Question: Sort an array of integers using bubble sort algorithm.

Not gonna lie—I thought sorting algorithms were outdated until I faced this in an interview. They want to see if you understand basic algorithms, not just use Arrays.sort().

Here's Bubble Sort:

public class BubbleSort {
    public 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]) {
                    // Swap
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
    }
    
    public static void main(String[] args) {
        int[] numbers = {64, 34, 25, 12, 22};
        bubbleSort(numbers);
        for (int num : numbers) {
            System.out.print(num + " ");
        }
    }
}

Real Experience: When I explained the logic while coding ("Each pass bubbles the largest element to the end"), the interviewer nodded approvingly. Talking through your code matters!


8. Find the Largest Element in an Array

The Question: Find the largest number in an array without using built-in methods.

This seems almost too easy, but it's a warm-up question to see how you approach basic problems.

Straightforward Solution:

public class LargestElement {
    public static int findLargest(int[] arr) {
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        return max;
    }
    
    public static void main(String[] args) {
        int[] numbers = {12, 35, 1, 10, 34, 1};
        System.out.println("Largest: " + findLargest(numbers)); // 35
    }
}

What They're Really Testing: Can you handle a simple problem cleanly without overcomplicating it? Sometimes the answer is yes, it's really that simple.


9. Count Vowels and Consonants

The Question: Count the number of vowels and consonants in a given string.

I love this question because it tests string manipulation and conditional logic together.

My Approach:

public class VowelConsonantCount {
    public static void countLetters(String str) {
        str = str.toLowerCase();
        int vowels = 0, consonants = 0;
        
        for (char ch : str.toCharArray()) {
            if (ch >= 'a' && ch <= 'z') {
                if ("aeiou".indexOf(ch) != -1) {
                    vowels++;
                } else {
                    consonants++;
                }
            }
        }
        System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);
    }
    
    public static void main(String[] args) {
        countLetters("Hello World"); // Vowels: 3, Consonants: 7
    }
}

Quick Tip: I initially forgot to filter out spaces and numbers. Always think about what characters you're actually counting!


10. Remove All Spaces from a String

The Question: Write a program to remove all whitespace from a string.

The interviewer wants to see if you know regex or if you'll manually loop through the string. Both approaches work!

Two Solutions:

public class RemoveWhitespace {
    // Using regex (quick and clean)
    public static String removeSpaces(String str) {
        return str.replaceAll("\\s", "");
    }
    
    // Manual approach (shows understanding)
    public static String removeSpacesManually(String str) {
        StringBuilder result = new StringBuilder();
        for (char ch : str.toCharArray()) {
            if (ch != ' ') {
                result.append(ch);
            }
        }
        return result.toString();
    }
    
    public static void main(String[] args) {
        System.out.println(removeSpaces("Hello World Java")); // HelloWorldJava
    }
}

Interview Story: I used replaceAll() once, and the interviewer asked, "Can you do it without regex?" Always be prepared to solve the same problem different ways.


What I Wish Someone Had Told Me Before My First Interview

Talk While You Code

Seriously, this changed everything for me. Don't just sit silently coding. Explain what you're thinking: "I'm using a HashSet here because it gives me O(1) lookup time." Even if you're stuck, talk through your thought process.

It's Okay to Start Simple

My biggest mistake early on was trying to write the perfect optimized solution immediately. Start with something that works, even if it's not optimal. Then improve it. Interviewers love seeing your thought progression.

Ask Questions

Before writing a single line of code, clarify:

  • What about null inputs?
  • Should I handle negative numbers?
  • Are there memory constraints?
  • What should I return for edge cases?

These questions show you're thinking like a real developer.

Practice on Paper First

Most interviews use whiteboards or shared screens without autocomplete. Practice writing code by hand or in a plain text editor. You'll catch silly mistakes you'd normally miss.


Common Mistakes I Made (So You Don't Have To)

Forgetting Edge Cases: I once wrote a perfect palindrome checker that crashed on empty strings. Always test with empty inputs, single elements, and null values.

Not Testing My Code: Walk through your code with sample input before saying "I'm done." Catch bugs yourself rather than having the interviewer point them out.

Using Terrible Variable Names: I used "x, y, z" in my first interview. Use "left, right, max, count"—meaningful names that make your logic crystal clear.

Getting Defensive About Mistakes: When an interviewer points out a bug, don't make excuses. Say "Good catch! Let me fix that" and move on. Everyone makes mistakes.


Frequently Asked Questions

How many problems should I practice before feeling ready?

Start with these 10, then expand to about 50-70 problems covering different topics. But here's the thing—it's not about quantity. I practiced 100+ problems but still struggled in interviews because I was just memorizing. Focus on understanding the why behind each solution.

What if I completely blank out during the interview?

It happens to everyone. Take a breath, reread the question out loud, and start with the simplest possible solution. I once blanked on reversing a string (the easiest problem!), so I just started talking: "Okay, I need to swap characters... maybe from both ends?" Talking helped me think.

Should I mention time complexity?

Yes! Even if they don't ask, mention it. "This solution is O(n) time and O(1) space." It shows you're thinking beyond just making code work.

Are these questions really enough for interviews?

For entry-level and fresher positions, absolutely. These cover the core concepts most companies test. As you gain experience, you'll face more complex problems, but these fundamentals never go away.

What if the interviewer asks me to optimize my solution?

Don't panic—this is actually good! It means your first solution works. Ask what they want optimized: time complexity or space complexity? Then think about data structures that could help (HashMaps for faster lookup, StringBuilder for string operations, etc.).


Final Thoughts from Someone Who's Been There

Look, I'm not going to promise that mastering these 10 questions guarantees you'll ace every interview. But I will say this: every single one of these problems taught me something valuable, and I've seen variations of them in almost every Java interview I've had.

The difference between struggling in interviews and feeling confident isn't talent—it's preparation and practice. Start with these questions. Write the code yourself (don't just read solutions). Break things. Fix them. Try different approaches.

And remember, interviews are as much about showing how you think as getting the right answer. I've seen people solve problems incorrectly but get hired because they communicated well and showed good problem-solving instincts. I've also seen people write perfect code but struggle because they couldn't explain their thinking.

You've got this. Now go practice, stay calm in your interviews, and show them what you know!


Disclaimer

This article shares educational information and personal experiences to help with interview preparation. Interview formats and questions vary significantly across companies and roles. The solutions provided are examples—many problems have multiple valid approaches. Your interview experience will depend on the company, role, and your individual preparation. This content does not guarantee interview success or job placement. Practice thoroughly and adapt these concepts to your specific situation.

Comments