Skip to main content

Top 20 Java Coding Interview Questions with Real Solutions – 2025 Edition

Top 20 Java Coding Interview Questions with Real Solutions – 2025 Edition

Java coding questions are frequently asked in TCS, Infosys, Capgemini, Wipro, Accenture, and product-based company interviews. This guide covers important Java coding interview questions with clean solutions, explanations, and Java 8 concepts useful for freshers and experienced developers.

1. Reverse a String

This question tests string manipulation concepts in Java.


public String reverse(String input) {
    return new StringBuilder(input).reverse().toString();
}

Time Complexity: O(n)

2. Check if a String is Palindrome

Palindrome questions are commonly asked to test loops and condition handling.


public boolean isPalindrome(String str) {
    int i = 0, j = str.length() - 1;

    while (i < j) {
        if (str.charAt(i++) != str.charAt(j--)) {
            return false;
        }
    }

    return true;
}

Time Complexity: O(n)

3. Find Duplicates in Array

This problem checks understanding of HashSet and duplicate detection.


Set<Integer> set = new HashSet<>();

for (int num : arr) {
    if (!set.add(num)) {
        System.out.println("Duplicate: " + num);
    }
}

Time Complexity: O(n)

4. Check if Two Strings Are Anagrams


public boolean isAnagram(String s1, String s2) {

    char[] a1 = s1.toCharArray();
    char[] a2 = s2.toCharArray();

    Arrays.sort(a1);
    Arrays.sort(a2);

    return Arrays.equals(a1, a2);
}

5. Frequency of Characters in String

HashMap is commonly used to count character frequency.


Map<Character, Integer> map = new HashMap<>();

for (char c : str.toCharArray()) {
    map.put(c, map.getOrDefault(c, 0) + 1);
}

6. First Non-Repeating Character


Map<Character, Integer> freq = new LinkedHashMap<>();

for (char c : str.toCharArray()) {
    freq.put(c, freq.getOrDefault(c, 0) + 1);
}

for (Map.Entry<Character, Integer> entry : freq.entrySet()) {

    if (entry.getValue() == 1) {
        System.out.println(entry.getKey());
        break;
    }
}

7. Remove Duplicates from List


List<String> distinct = list.stream()
    .distinct()
    .collect(Collectors.toList());

8. 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);
    }
}

9. Sort HashMap by Value


map.entrySet()
   .stream()
   .sorted(Map.Entry.comparingByValue())
   .forEach(e -> 
       System.out.println(e.getKey() + ": " + e.getValue()));

10. Count Vowels and Consonants


int vowels = 0;
int consonants = 0;

for (char ch : str.toLowerCase().toCharArray()) {

    if ("aeiou".indexOf(ch) != -1) {
        vowels++;
    }
    else if (Character.isLetter(ch)) {
        consonants++;
    }
}

11. Check Armstrong Number


int num = 153;
int temp = num;
int result = 0;

while (temp != 0) {

    int digit = temp % 10;
    result += digit * digit * digit;

    temp /= 10;
}

System.out.println(result == num);

12. Factorial using Recursion


public int factorial(int n) {

    if (n == 0) {
        return 1;
    }

    return n * factorial(n - 1);
}

13. Binary to Decimal Conversion


int decimal = Integer.parseInt("1010", 2);

14. Prime Number Check


boolean isPrime(int n) {

    if (n <= 1) {
        return false;
    }

    for (int i = 2; i <= Math.sqrt(n); i++) {

        if (n % i == 0) {
            return false;
        }
    }

    return true;
}

15. Find Second Largest Number


int first = Integer.MIN_VALUE;
int second = Integer.MIN_VALUE;

for (int num : arr) {

    if (num > first) {

        second = first;
        first = num;
    }

    else if (num > second && num != first) {
        second = num;
    }
}

16. Find Missing Number in Range


int sum = (n * (n + 1)) / 2;

for (int val : arr) {
    sum -= val;
}

System.out.println("Missing: " + sum);

17. Sort Custom Objects with Comparator


Collections.sort(list,
    (a, b) -> a.getAge() - b.getAge());

18. Java 8 Map and Filter


list.stream()
    .filter(s -> s.startsWith("A"))
    .map(String::toUpperCase)
    .forEach(System.out::println);

19. Group By Using Java Streams


Map<String, List<Employee>> grouped =
    employees.stream()
        .collect(Collectors.groupingBy(Employee::getDept));

20. Read File Line by Line


Files.lines(Paths.get("file.txt"))
     .forEach(System.out::println);

Frequently Asked Questions

Are Java coding questions asked in TCS interviews?

Yes, companies like TCS, Infosys, Wipro, and Capgemini frequently ask Java coding questions for freshers and experienced candidates.

Is Java 8 important for coding interviews?

Yes, Java 8 features like Streams, Lambda Expressions, and Functional Interfaces are commonly asked in modern interviews.

How can I practice Java coding questions?

Practice regularly using IntelliJ IDEA or Eclipse and focus on arrays, strings, collections, and Java 8 concepts.

Pro Tip: Practice these programs in your local IDE and explain the logic step-by-step during interviews.

📅 Last Updated: May 2025
📎 #JavaCodingInterview #JavaPractice2025 #JavaInterviewQuestions

Comments

Popular posts from this blog

Top 15 React Interview Questions for 1–2 Years Experience

🟦 Top 15 React Interview Questions for 1–2 Years Experience Preparing for a React interview with 1–2 years of experience? Here's a carefully curated list of 15 important React questions with clear, real-world answers. These are frequently asked in interviews at companies like TCS, Infosys, Cognizant, Capgemini, and product-based firms. Q1. What is the Virtual DOM in React, and how does it improve performance? Answer: The Virtual DOM is a lightweight, in-memory copy of the real DOM. When state/props change, React creates a new Virtual DOM tree, compares it with the old one (diffing), and only updates the parts of the real DOM that changed. This makes rendering much faster and improves performance in large applications. Q2. What is JSX in React? Answer: JSX stands for JavaScript XML. It allows us to write HTML elements in JavaScript and place them in the DOM without using createElement() . JSX improves code readability and is transpiled to React.createElement() calls. ...

Top 15 Spring Boot Interview Questions and Answers – Real Examples (2025)

Top 15 Spring Boot Interview Questions – 2025 Spring Boot is one of the most demanded frameworks for Java backend development. Whether you're interviewing for TCS, Infosys, or a product-based company, these Spring Boot questions will help you prepare like a pro. Here are 15 questions with detailed explanations for developers with 1–2 years of experience. Q1. What is Spring Boot? Answer: Spring Boot is a Java-based open-source framework built on top of the Spring Framework. It helps developers create stand-alone, production-ready Spring applications with minimal configuration. Its key features include: Auto-configuration Embedded servers (Tomcat, Jetty) Starter dependencies Production-ready tools (Actuator, Metrics, etc.) Example: You can create a REST API within minutes by using @RestController and spring-boot-starter-web — no need for external web server deployment. Q2. What is the role of @SpringBootApplication annotation? Answer: This annotation i...

Wipro Java Developer Interview Questions with Answers (Mid-Level Role)

  Wipro Java Developer Interview Questions with Answers (Mid-Level Role) (Glassdoor Based – May 2024) Interview Location: Bengaluru Interview Mode: Online Candidate Role: Mid-Level Java Developer Source: Based on real experience shared on Glassdoor Review Summary: Easy and conversational. Interviewer was friendly. Focus was mainly on Java basics, internals, and real-world understanding. Q1: What is static in public static void main(String[] args) ? A: The static keyword lets the JVM call the method without creating an object. It indicates that the method belongs to the class, not instances. Q2: Why does a Java program start from the main method? A: main() is the predefined entry point of a Java application. The JVM starts execution from there. Q3: What are Checked and Unchecked Exceptions? With examples. A: Checked Exceptions : Detected at compile time. E.g., IOException , SQLException . Unchecked Exceptions : Detected at runtime. E.g., NullPointerExce...