SF Learners Hub · Blog · About · Contact

50 Basic Java Coding Interview Questions

By Aman Garg · Published · Interview Questions

50 Basic Java Coding Interview Questions

50 Basic Java Coding Interview Questions with Solutions

1. Basic Logic-Building Programs

1. Check whether a number is even or odd

public class Main {
    public static void main(String[] args) {
        int num = 10;

        if (num % 2 == 0)
            System.out.println("Even Number");
        else
            System.out.println("Odd Number");
    }
}

Output: Even Number

2. Check whether a number is positive, negative, or zero

public class Main {
    public static void main(String[] args) {
        int num = -5;

        if (num > 0)
            System.out.println("Positive");
        else if (num < 0)
            System.out.println("Negative");
        else
            System.out.println("Zero");
    }
}

Output: Negative

3. Find the largest of two numbers

public class Main {
    public static void main(String[] args) {
        int a = 20, b = 30;

        if (a > b)
            System.out.println(a);
        else
            System.out.println(b);
    }
}

Output: 30

4. Find the largest of three numbers

public class Main {
    public static void main(String[] args) {
        int a = 10, b = 25, c = 15;

        if (a >= b && a >= c)
            System.out.println(a);
        else if (b >= a && b >= c)
            System.out.println(b);
        else
            System.out.println(c);
    }
}

Output: 25

5. Swap two numbers using a third variable

public class Main {
    public static void main(String[] args) {
        int a = 10, b = 20, temp;

        temp = a;
        a = b;
        b = temp;

        System.out.println(a + " " + b);
    }
}

Output: 20 10

6. Swap two numbers without a third variable

public class Main {
    public static void main(String[] args) {
        int a = 10, b = 20;

        a = a + b;
        b = a - b;
        a = a - b;

        System.out.println(a + " " + b);
    }
}

Output: 20 10

7. Check whether a year is a leap year

public class Main {
    public static void main(String[] args) {
        int year = 2024;

        if (year % 400 == 0 ||
           (year % 4 == 0 && year % 100 != 0))
            System.out.println("Leap Year");
        else
            System.out.println("Not a Leap Year");
    }
}

Output: Leap Year

8. Find the factorial of a number

public class Main {
    public static void main(String[] args) {
        int num = 5;
        long fact = 1;

        for (int i = 1; i <= num; i++) {
            fact *= i;
        }

        System.out.println(fact);
    }
}

Output: 120

9. Print the multiplication table

public class Main {
    public static void main(String[] args) {
        int num = 5;

        for (int i = 1; i <= 10; i++) {
            System.out.println(num + " x " + i +
                               " = " + (num * i));
        }
    }
}

10. Find the sum of the first N natural numbers

public class Main {
    public static void main(String[] args) {
        int n = 10;
        int sum = 0;

        for (int i = 1; i <= n; i++) {
            sum += i;
        }

        System.out.println(sum);
    }
}

Output: 55


2. Number-Based Coding Questions

11. Reverse a number

public class Main {
    public static void main(String[] args) {
        int num = 12345;
        int reverse = 0;

        while (num != 0) {
            int digit = num % 10;
            reverse = reverse * 10 + digit;
            num /= 10;
        }

        System.out.println(reverse);
    }
}

Output: 54321

12. Check whether a number is a palindrome

public class Main {
    public static void main(String[] args) {
        int num = 121;
        int original = num;
        int reverse = 0;

        while (num > 0) {
            int digit = num % 10;
            reverse = reverse * 10 + digit;
            num /= 10;
        }

        if (original == reverse)
            System.out.println("Palindrome");
        else
            System.out.println("Not Palindrome");
    }
}

Output: Palindrome

13. Check whether a number is an Armstrong number

public class Main {
    public static void main(String[] args) {
        int num = 153;
        int original = num;
        int sum = 0;
        int digits = String.valueOf(num).length();

        while (num > 0) {
            int digit = num % 10;
            sum += (int) Math.pow(digit, digits);
            num /= 10;
        }

        if (sum == original)
            System.out.println("Armstrong Number");
        else
            System.out.println("Not Armstrong");
    }
}

Output: Armstrong Number

14. Check whether a number is prime

public class Main {
    public static void main(String[] args) {
        int num = 17;
        boolean prime = num > 1;

        for (int i = 2; i <= num / i; i++) {
            if (num % i == 0) {
                prime = false;
                break;
            }
        }

        System.out.println(prime ? "Prime" : "Not Prime");
    }
}

Output: Prime

15. Print prime numbers between 1 and 100

public class Main {
    public static void main(String[] args) {
        for (int num = 2; num <= 100; num++) {
            boolean prime = true;

            for (int i = 2; i <= num / i; i++) {
                if (num % i == 0) {
                    prime = false;
                    break;
                }
            }

            if (prime)
                System.out.print(num + " ");
        }
    }
}

16. Find the sum of digits

public class Main {
    public static void main(String[] args) {
        int num = 1234;
        int sum = 0;

        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }

        System.out.println(sum);
    }
}

Output: 10

17. Count the number of digits

public class Main {
    public static void main(String[] args) {
        int num = 12345;
        int count = 0;

        do {
            count++;
            num /= 10;
        } while (num != 0);

        System.out.println(count);
    }
}

Output: 5

18. Find the product of digits

public class Main {
    public static void main(String[] args) {
        int num = 234;
        int product = 1;

        while (num > 0) {
            product *= num % 10;
            num /= 10;
        }

        System.out.println(product);
    }
}

Output: 24

19. Check whether a number is a perfect number

public class Main {
    public static void main(String[] args) {
        int num = 28;
        int sum = 0;

        for (int i = 1; i <= num / 2; i++) {
            if (num % i == 0)
                sum += i;
        }

        System.out.println(sum == num ?
                           "Perfect Number" : "Not Perfect");
    }
}

Output: Perfect Number

20. Print the Fibonacci series

public class Main {
    public static void main(String[] args) {
        int n = 10;
        int a = 0, b = 1;

        for (int i = 1; i <= n; i++) {
            System.out.print(a + " ");

            int next = a + b;
            a = b;
            b = next;
        }
    }
}

Output: 0 1 1 2 3 5 8 13 21 34


3. String-Based Coding Questions

21. Reverse a string

public class Main {
    public static void main(String[] args) {
        String str = "Java";
        String reverse = "";

        for (int i = str.length() - 1; i >= 0; i--) {
            reverse += str.charAt(i);
        }

        System.out.println(reverse);
    }
}

Output: avaJ

22. Check whether a string is a palindrome

public class Main {
    public static void main(String[] args) {
        String str = "madam";
        String reverse = "";

        for (int i = str.length() - 1; i >= 0; i--) {
            reverse += str.charAt(i);
        }

        if (str.equals(reverse))
            System.out.println("Palindrome");
        else
            System.out.println("Not Palindrome");
    }
}

Output: Palindrome

23. Count vowels and consonants

public class Main {
    public static void main(String[] args) {
        String str = "Hello World";
        int vowels = 0, consonants = 0;

        for (int i = 0; i < str.length(); i++) {
            char ch = Character.toLowerCase(str.charAt(i));

            if (ch >= 'a' && ch <= 'z') {
                if ("aeiou".indexOf(ch) != -1)
                    vowels++;
                else
                    consonants++;
            }
        }

        System.out.println("Vowels: " + vowels);
        System.out.println("Consonants: " + consonants);
    }
}

Output: Vowels: 3, Consonants: 7

24. Count words in a string

public class Main {
    public static void main(String[] args) {
        String str = "Java is easy to learn";

        String trimmed = str.trim();
        int count = trimmed.isEmpty() ? 0 :
                    trimmed.split("\\s+").length;

        System.out.println(count);
    }
}

Output: 5

25. Count the occurrence of each character

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String str = "banana";
        Map<Character, Integer> map = new LinkedHashMap<>();

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

        System.out.println(map);
    }
}

Output: {b=1, a=3, n=2}

26. Remove duplicate characters from a string

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        String result = "";

        for (char ch : str.toCharArray()) {
            if (result.indexOf(ch) == -1)
                result += ch;
        }

        System.out.println(result);
    }
}

Output: progamin

27. Find duplicate characters in a string

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String str = "programming";
        Map<Character, Integer> map = new LinkedHashMap<>();

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

        for (char ch : map.keySet()) {
            if (map.get(ch) > 1)
                System.out.println(ch + " = " + map.get(ch));
        }
    }
}

Output:

r = 2
g = 2
m = 2

28. Check whether two strings are anagrams

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String s1 = "listen";
        String s2 = "silent";

        char[] a = s1.toLowerCase().toCharArray();
        char[] b = s2.toLowerCase().toCharArray();

        Arrays.sort(a);
        Arrays.sort(b);

        System.out.println(Arrays.equals(a, b) ?
                           "Anagram" : "Not Anagram");
    }
}

Output: Anagram

29. Convert lowercase characters to uppercase

public class Main {
    public static void main(String[] args) {
        String str = "hello java";

        System.out.println(str.toUpperCase());
    }
}

Output: HELLO JAVA

30. Find the first non-repeated character

import java.util.*;

public class Main {
    public static void main(String[] args) {
        String str = "swiss";
        Map<Character, Integer> map = new LinkedHashMap<>();

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

        for (char ch : str.toCharArray()) {
            if (map.get(ch) == 1) {
                System.out.println(ch);
                break;
            }
        }
    }
}

Output: w


4. Array-Based Coding Questions

31. Find the largest element in an array

public class Main {
    public static void main(String[] args) {
        int[] arr = {10, 25, 5, 40, 15};
        int max = arr[0];

        for (int num : arr) {
            if (num > max)
                max = num;
        }

        System.out.println(max);
    }
}

Output: 40

32. Find the smallest element in an array

public class Main {
    public static void main(String[] args) {
        int[] arr = {10, 25, 5, 40, 15};
        int min = arr[0];

        for (int num : arr) {
            if (num < min)
                min = num;
        }

        System.out.println(min);
    }
}

Output: 5

33. Find the second-largest distinct element

public class Main {
    public static void main(String[] args) {
        int[] arr = {10, 25, 40, 15, 40};

        Integer largest = null;
        Integer second = null;

        for (int num : arr) {
            if (largest == null || num > largest) {
                second = largest;
                largest = num;
            } else if (num != largest &&
                       (second == null || num > second)) {
                second = num;
            }
        }

        System.out.println(second == null ?
                           "No second largest" : second);
    }
}

Output: 25

34. Reverse an array

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};

        int left = 0, right = arr.length - 1;

        while (left < right) {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;

            left++;
            right--;
        }

        System.out.println(Arrays.toString(arr));
    }
}

Output: [5, 4, 3, 2, 1]

35. Sort an array without built-in sorting

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 1, 3};

        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }

        System.out.println(Arrays.toString(arr));
    }
}

Output: [1, 2, 3, 5, 8]

36. Find duplicate elements in an array

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 4, 1, 5};
        Set<Integer> seen = new HashSet<>();
        Set<Integer> duplicates = new LinkedHashSet<>();

        for (int num : arr) {
            if (!seen.add(num))
                duplicates.add(num);
        }

        System.out.println(duplicates);
    }
}

Output: [2, 1]

37. Remove duplicate elements from an array

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 3, 4, 3};

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

        for (int num : arr)
            set.add(num);

        System.out.println(set);
    }
}

Output: [1, 2, 3, 4]

38. Find the sum of all array elements

public class Main {
    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40};
        int sum = 0;

        for (int num : arr)
            sum += num;

        System.out.println(sum);
    }
}

Output: 100

39. Find the missing number from 1 to N

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 4, 5};
        int n = 5;

        int expected = n * (n + 1) / 2;
        int actual = 0;

        for (int num : arr)
            actual += num;

        System.out.println(expected - actual);
    }
}

Output: 3

Assumption: The array contains distinct numbers from 1 to N, with exactly one missing number.

40. Merge two arrays

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = {4, 5, 6};

        int[] result = new int[a.length + b.length];

        for (int i = 0; i < a.length; i++)
            result[i] = a[i];

        for (int i = 0; i < b.length; i++)
            result[a.length + i] = b[i];

        System.out.println(Arrays.toString(result));
    }
}

Output: [1, 2, 3, 4, 5, 6]


5. Basic Java and OOP Coding Questions

41. Create an Employee class with properties and methods

class Employee {
    int id;
    String name;
    double salary;

    void display() {
        System.out.println(id + " " + name + " " + salary);
    }
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();

        emp.id = 101;
        emp.name = "Rahul";
        emp.salary = 30000;

        emp.display();
    }
}

Output: 101 Rahul 30000.0

42. Demonstrate constructor overloading

class Student {
    String name;
    int age;

    Student() {
        name = "Unknown";
        age = 0;
    }

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    void display() {
        System.out.println(name + " " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student("Amit", 22);

        s1.display();
        s2.display();
    }
}

Output:

Unknown 0
Amit 22

43. Demonstrate method overloading

class Calculator {
    int add(int a, int b) {
        return a + b;
    }

    int add(int a, int b, int c) {
        return a + b + c;
    }

    double add(double a, double b) {
        return a + b;
    }
}

public class Main {
    public static void main(String[] args) {
        Calculator c = new Calculator();

        System.out.println(c.add(10, 20));
        System.out.println(c.add(10, 20, 30));
        System.out.println(c.add(2.5, 3.5));
    }
}

Output:

30
60
6.0

44. Demonstrate method overriding

class Animal {
    void sound() {
        System.out.println("Animal makes sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal obj = new Dog();
        obj.sound();
    }
}

Output: Dog barks

45. Demonstrate inheritance

class Person {
    void displayName() {
        System.out.println("I am a person");
    }
}

class Employee extends Person {
    void work() {
        System.out.println("I am working");
    }
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();

        emp.displayName();
        emp.work();
    }
}

Output:

I am a person
I am working

46. Demonstrate encapsulation

class Employee {
    private double salary;

    public void setSalary(double salary) {
        if (salary >= 0)
            this.salary = salary;
    }

    public double getSalary() {
        return salary;
    }
}

public class Main {
    public static void main(String[] args) {
        Employee emp = new Employee();

        emp.setSalary(40000);
        System.out.println(emp.getSalary());
    }
}

Output: 40000.0

47. Demonstrate abstraction using an abstract class

abstract class Shape {
    abstract void calculateArea();
}

class Circle extends Shape {
    double radius = 5;

    void calculateArea() {
        System.out.println(Math.PI * radius * radius);
    }
}

public class Main {
    public static void main(String[] args) {
        Shape s = new Circle();
        s.calculateArea();
    }
}

Output: Approximately 78.54

48. Demonstrate an interface

interface Vehicle {
    void start();
}

class Car implements Vehicle {
    public void start() {
        System.out.println("Car started");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle v = new Car();
        v.start();
    }
}

Output: Car started

49. Demonstrate exception handling using try-catch

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Program completed");
        }
    }
}

Output:

Cannot divide by zero
Program completed

50. Demonstrate the use of ArrayList

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();

        names.add("Amit");
        names.add("Rahul");
        names.add("Priya");

        names.remove("Rahul");

        for (String name : names) {
            System.out.println(name);
        }
    }
}

Output:

Amit
Priya

Interview Preparation Tips

For every coding question, candidates should be able to explain:

  1. What is the problem asking?

  2. What is the logic behind the solution?

  3. Why did they choose a particular loop or condition?

  4. What happens with edge cases?

  5. What is the time and space complexity?

  6. Can they solve the same problem without using built-in methods?

Final advice: Freshers should first understand the logic and then write the code independently. Memorizing solutions alone is not enough for a coding interview.

Related articles