We’ve been hiring full-stack developers lately and drawing from a pool of Java interview questions. Here are some of the basics.
1. What is the difference between the JDK and the JRE?
- JDK (Java Development Kit): The full toolkit used to develop Java applications.
- JRE (Java Runtime Environment): The runtime environment required to execute Java applications.
- Relationship: The JDK contains the JRE. Inside the JDK directory, there is a
jrefolder containing two subdirectories:binandlib. Thebindirectory represents the Java Virtual Machine (JVM), whilelibcontains the class libraries required for the JVM to operate.
2. What is the difference between == and equals()?
- Primitive types:
==compares the actual values. - Reference types:
==compares the memory addresses (references). - Usage limitation:
equals()cannot be used on primitive types. - Default behavior: Unless overridden,
equals()behaves identically to==. - Overridden behavior: When overridden (such as in
String),equals()compares object content rather than reference addresses.
3. What is the purpose of the final keyword in Java?
- Variable/Reference:
- For primitive types, it creates a constant whose value cannot be reassigned.
- For reference types (such as objects or arrays), the object state can still be modified, but the reference itself cannot be reassigned to point to a different object.
- Member variables marked
finalmust be explicitly initialized during object creation; otherwise, a compilation error occurs.
- Method: A
finalmethod cannot be overridden by subclasses, though it can still be inherited. - Class: A
finalclass cannot be extended (e.g., the standardStringclass is final).
4. What is the output of Math.round(-1.5) in Java?
The result is -1.
Java’s Math class provides three key rounding functions:
ceil(Round Up / Toward Positive Infinity):Math.ceil(11.3)→12.0Math.ceil(-11.3)→-11.0
floor(Round Down / Toward Negative Infinity):Math.floor(11.3)→11.0Math.floor(-11.3)→-12.0
round(Round to Nearest Neighbor): Works by adding 0.5 and taking the floor.Math.round(11.3)→11Math.round(11.8)→12Math.round(-11.3)→-11Math.round(-11.8)→-12Math.round(-1.5)→
5. Is String a primitive data type in Java?
No. The 8 primitive data types in Java are byte, short, int, long, float, double, char, and boolean. String is a reference type (an object).
6. Are String str = "i" and String str = new String("i") equivalent?
No, they allocate memory differently:
String str = "i": Uses string literal syntax. Java checks the String Constant Pool. If"i"exists, it assigns the pooled reference; if not, it creates"i"in the pool first.String str = new String("i"): Explicitly allocates a newStringobject on the Heap, creating a distinct memory reference even if"i"already exists in the pool.
7. How do you reverse a String?
Wrap the string in a StringBuilder (or StringBuffer) and invoke its reverse() method.
8. What are common methods of the String class?
Accessors & Search:
length(): Returns string length.charAt(int index): Returns the character at the specified index.indexOf(int ch): Returns the index of the first occurrence of a character.substring(int beginIndex)/substring(int beginIndex, int endIndex): Extracts a substring.
Validation & Comparison:
equals(Object obj): Case-sensitive content comparison.contains(CharSequence s): Checks if a sequence is present.startsWith(String prefix)/endsWith(String suffix): Prefix/suffix verification.isEmpty(): Checks if length is zero ("").
Conversion:
getBytes()/toCharArray(): Converts string into a byte array or character array.String.valueOf(...): Converts arbitrary types to string representation.toLowerCase()/toUpperCase(): Case conversions.concat(String str): Appends strings.
Formatting & Utilities:
replace(char oldChar, char newChar)/replace(CharSequence target, CharSequence replacement): Replaces characters or substrings.trim(): Strips leading and trailing whitespace.compareTo(String anotherString): Lexicographically compares strings by character codes; returns 0 if identical.
9. How many objects are created by new String("a") + new String("b")?
Up to 6 objects are instantiated during execution:
StringBuilderinstance (created implicitly for string concatenation).- Heap
Stringobject for"a". - String Constant Pool entry for
"a". - Heap
Stringobject for"b". - String Constant Pool entry for
"b". - Final Heap
Stringobject for"ab"(generated whenStringBuilder.toString()is invoked).
Note: Calling StringBuilder.toString() creates a new heap string without adding "ab" to the String Constant Pool.
Deep-Dive Analysis:
String s1 = new String("1") + new String("1"); // s1 holds heap reference for new String("11")s1.intern();String s2 = "11";System.out.println(s1 == s2);- JDK 6: Outputs
false.intern()creates a separate"11"instance inside the permanent generation string pool with its own distinct reference. - JDK 7+: Outputs
true. The pool moves to the heap;intern()simply stores the existing heap memory address ofs1inside the pool rather than copying the object.
10. How do you reverse a String? (alternate phrasing)
Pass the string to a StringBuilder instance and call .reverse().toString().
11. Summary of essential String methods
equals, length, contains, replace, split, hashCode, indexOf, substring, trim, toUpperCase, toLowerCase, and isEmpty.
12. What are the differences between a concrete class and an abstract class?
- Abstract classes cannot be instantiated directly using
new. - Abstract classes may declare abstract methods (method signatures without implementations).
- Any class containing at least one abstract method must be declared abstract.
- Non-abstract subclasses must implement all inherited abstract methods; otherwise, the subclass must also be declared abstract.
- Abstract methods cannot be marked
staticorfinal.
13. What is the difference between an Interface and an Abstract Class?
Interface (interface):
- Cannot be instantiated.
- Supports multiple inheritance (a class can implement multiple interfaces).
- Java 8+: Abstract by default, but supports
staticanddefaultmethods with concrete bodies.
Abstract Class (abstract class):
- Cannot be instantiated.
- Restricted to single inheritance (
extends). - Can declare state (instance fields) and contain both abstract and concrete methods.
- Subclasses must override abstract methods unless the subclass itself is abstract.
14. How are Java I/O Streams categorized?
- By Direction:
- Input Streams: Read data into the application.
- Output Streams: Write data out from the application.
- By Data Unit:
- Byte Streams (
InputStream,OutputStream): Handle raw 8-bit binary data. - Character Streams (
Reader,Writer): Handle 16-bit Unicode characters.
- Byte Streams (
15. What are the differences between BIO, NIO, and AIO?
- BIO (Blocking I/O): Synchronous & Blocking. One thread per connection model. Common prior to JDK 1.4. Threads block until data is ready, leading to resource exhaustion under high concurrency.
- NIO (Non-blocking I/O / New I/O): Synchronous & Non-blocking. Introduced in JDK 1.4. Uses selectors and channels to manage multiple short-lived connections efficiently via thread pooling. Ideal for high-concurrency systems like chat servers.
- AIO (Asynchronous I/O / NIO 2.0): Asynchronous & Non-blocking. Introduced in JDK 1.7. Uses OS-level event notification callbacks for long-lived, high-throughput connections (e.g., media streaming servers).