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 20 Spring Boot Microservices Architecture Interview Questions (With Speakable Answers)

Top 20 Spring Boot Microservices Architecture Interview Questions (With Speakable Answers) * * * 1. What is Microservices Architecture?   → Microservices architecture breaks an application into small, independent services. Each one handles a specific business function and can be developed, deployed, and scaled independently. They usually communicate over REST APIs or messaging queues. * * * 2. How does Spring Boot help in building microservices?   → Spring Boot offers embedded servers, auto-configuration, starter templates, and production-ready tools. It works well with Spring Cloud to provide service discovery, config management, load balancing, and more. * * * 3. What are the core components in a microservices setup?   → Key components include:   ✓ API Gateway   ✓ Eureka (Service Discovery)   ✓ Config Server   ✓ Kafka or RabbitMQ   ✓ Circuit Breaker (like Resilience4j)   ✓ Centralized logging and monitoring (ELK, Prometheus) * * * 4. What i...

TCS Java Interview | Java | Spring Boot | Microservices | Database

TCS Java Interview | Java | Spring Boot | Microservices | Database This post is based on a Java backend developer interview simulation and provides direct transcript-based answers to help you prepare for similar interviews. 📺 This interview scenario was inspired by a video from the  YouTube channel:  CloudTech . 🔗 Watch the full video here:  https://www.youtube.com/watch?v=yVj2EgwZxk4 1. Can you introduce yourself and talk about your tech stack and domains? I have around 4.5 years of experience working as a Java developer. My core expertise is in Java and developing REST APIs using Spring Boot. I also have basic knowledge of microservices architecture. On the database side, I work with SQL and Oracle. Additionally, I have exposure to UI technologies like Angular, HTML, and CSS, but they are secondary skills. My primary focus is backend Java development. 2. Which version of Java are you currently working on? We are currently using Java 8 but are in the process of upgr...

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. ...