Java Coding Interview Questions
Java Coding Interview Questions — Core Java.
A few short coding problems commonly asked in interviews, with solutions.
Q1. Write a program to swap two numbers without using a third variable.
javapublic class SwapNumbers { public static void main(String[] args) { int a = 5, b = 10; a = a + b; b = a - b; a = a - b; System.out.println("a = " + a + ", b = " + b); } }
Output:
a = 10, b = 5Q2. Write a program to check if a string contains only digits.
javapublic class DigitCheck { public static void main(String[] args) { String text = "12345"; boolean allDigits = text.matches("[0-9]+"); System.out.println("Contains only digits: " + allDigits); } }
Output:
Contains only digits: trueQ3. Write a program to find the second largest number in an array.
javapublic class SecondLargest { public static void main(String[] args) { int[] numbers = {12, 45, 7, 89, 34}; int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE; for (int num : numbers) { if (num > largest) { secondLargest = largest; largest = num; } else if (num > secondLargest && num != largest) { secondLargest = num; } } System.out.println("Second largest: " + secondLargest); } }
Output:
Second largest: 45Key Points to Remember
- Practice writing these solutions by hand, without an IDE's auto-complete, to simulate real whiteboard or online interview conditions.
- Always consider edge cases out loud during an interview (empty arrays, negative numbers, duplicate values).
- Interviewers often ask you to explain the time complexity of your solution after writing it.