Fundamentals 42 min read

Common Java Interview Questions and Core Language Concepts Explained

This article provides concise explanations of key Java concepts—including object‑oriented features, access modifiers, primitive types, autoboxing, memory areas, garbage collection, class loading, inner classes, cloning, and common interview code snippets—offering a comprehensive reference for Java developers and interview preparation.

Java Captain
Java Captain
Java Captain
Common Java Interview Questions and Core Language Concepts Explained

1. What are the features of object‑oriented programming?

Abstraction: Summarizes common characteristics of a group of objects into a class, covering data and behavior abstraction. It focuses on what attributes and actions an object has, not on implementation details.

Inheritance: Creates a new class by reusing an existing class’s information. The existing class is the superclass (parent), the new class is the subclass (child). Inheritance promotes software continuity and encapsulates variability.

Encapsulation: Binds data and the methods that operate on the data, exposing only defined interfaces. It hides internal details, providing a simple programming interface.

Polymorphism: Allows objects of different sub‑types to respond differently to the same message. It includes compile‑time (method overloading) and run‑time (method overriding) polymorphism.

2. Differences among public, protected, default, and private modifiers?

Modifier

Same class

Same package

Subclass

Other packages

public

y

y

y

y

protected

y

y

y

x

default

y

y

x

x

private

y

x

x

x

When no modifier is specified, the default behaves like public within the same package and like private outside the package.

3. Is String a primitive type?

No. Java has eight primitive types (byte, short, int, long, float, double, char, boolean). All other types, including String, are reference types.

4. Is float f = 3.4; correct?

No. 3.4 is a double literal. Use either float f = (float)3.4; or float f = 3.4F; to assign to a float.

5. Does short s1 = 1; s1 = s1 + 1; cause an error? What about s1 += 1; ?

The expression s1 + 1 yields an int, so an explicit cast is required. The compound assignment s1 += 1 includes an implicit cast and compiles.

6. Does Java have a goto keyword?

goto

is a reserved word but not used in any Java version.

7. Difference between int and Integer ?

int

is a primitive; Integer is its wrapper class. Autoboxing/unboxing (since Java 5) automatically converts between them.

Example of autoboxing/unboxing:

class AutoUnboxingTest {
    public static void main(String[] args) {
        Integer a = new Integer(3);
        Integer b = 3; // autoboxing
        int c = 3;
        System.out.println(a == b); // false
        System.out.println(a == c); // true
    }
}

Another interview example demonstrates IntegerCache for values –128 to 127.

8. Difference between & and && ?

&

can be a bitwise AND or a logical AND that evaluates both operands. && is a short‑circuit logical AND; the right operand is evaluated only if the left is true.

9. Uses of stack, heap, and static area in memory?

Variables of primitive types and method call frames use the stack. Objects created with new reside on the heap. Literals and constant strings are stored in the static (method‑area) region.

String str = new String("hello"); // str reference on stack, object on heap, "hello" literal in static area

10. Results of Math.round(11.5) and Math.round(-11.5) ?

They return 12 and -11 respectively (add 0.5 then floor).

11. Can switch work on byte , long , and String ?

Before Java 5, switch supported byte, short, char, int. From Java 5, enum types are allowed; from Java 7, String is allowed. long is never allowed.

12. Most efficient way to compute 2 × 8?

Use left shift: 2 << 3.

13. Does an array have a length() method? Does String have one?

Arrays have a length field (no parentheses). String has a length() method.

14. How to break out of a multi‑level nested loop in Java?

Label the outer loop (e.g., A:) and use break A; to exit all inner loops.

15. Can a constructor be overridden?

No. Constructors are not inherited, so they cannot be overridden, though they can be overloaded.

16. If x.equals(y) == true , can x and y have different hash codes?

No. Equal objects must have identical hash codes; unequal objects may share hash codes.

17. Can String be subclassed?

No. String is final.

18. Is Java pass‑by‑value or pass‑by‑reference?

Java is pass‑by‑value; the value passed for objects is the reference itself, allowing the method to modify the object's state but not reassign the caller’s reference.

19. Difference between String , StringBuilder , and StringBuffer ?

String

is immutable. StringBuilder is mutable and not thread‑safe (single‑thread use). StringBuffer is mutable and synchronized (thread‑safe).

When concatenating compile‑time constants, the compiler optimizes the expression into a single String literal, making it faster than using StringBuilder.

String S1 = "This is only a" + " simple" + " test"; // optimized to a single literal
StringBuffer Sb = new StringBuilder("This is only a").append(" simple").append(" test");

20. Difference between overload and override; can overload be distinguished by return type?

Overloading occurs within the same class with different parameter lists; it is compile‑time polymorphism. Overriding occurs in a subclass with the same signature; it is run‑time polymorphism. Return type alone cannot differentiate overloaded methods.

21. How does the JVM load a class file?

Class loading is performed by class loaders (Bootstrap, Extension, System, custom). The process includes loading the .class bytes, linking (verification, preparation, resolution), and initialization (static initializers and static fields). The parent‑delegation model ensures security and consistency.

22. Can a char store a Chinese character?

Yes. Java uses Unicode; a char is 16 bits and can represent most Chinese characters.

23. Similarities and differences between abstract classes and interfaces.

Both cannot be instantiated and can be used as reference types. Interfaces cannot have constructors, all members are implicitly public, and fields are constants. Abstract classes can have constructors, fields with any access level, and both abstract and concrete methods.

24. Difference between static nested class and inner class.

A static nested class does not require an instance of the outer class. A non‑static inner class is tied to an outer instance and must be created via outer.new Inner().

package com.javadu.innerClass;
public class Poker {
    private static String[] suites = {"Spades","Hearts","Clubs","Diamonds"};
    private static int[] faces = {1,2,3,4,5,6,7,8,9,10,11,12,13};
    private Card[] cards;
    public Poker() { /* initialize cards */ }
    public class Card { /* non‑static inner class */ }
}

25. Does Java have memory leaks?

Although Java has garbage collection, "memory leaks" can occur when objects remain reachable (e.g., via static collections or caches) even though they are no longer needed.

26. Can an abstract method be static, native, or synchronized?

No. Abstract methods have no implementation, so they cannot be static, native, or synchronized.

27. Difference between static (class) variables and instance variables.

Static variables belong to the class and are shared across all instances. Instance variables belong to each object separately.

28. Can a static method call a non‑static method?

No. A static method can only directly access static members; it must obtain an instance to invoke a non‑static method.

29. How to implement object cloning?

Two common ways: (1) Implement Cloneable and override clone(). (2) Serialize the object and deserialize it to obtain a deep copy.

public static <T> T clone(T obj) throws Exception {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bout);
    oos.writeObject(obj);
    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bin);
    return (T) ois.readObject();
}

30. What is GC and why is it needed?

GC (Garbage Collection) automatically reclaims memory occupied by objects that are no longer reachable, preventing memory leaks and reducing the burden on developers.

31. How many objects are created by String s = new String("xyz"); ?

Two objects: the literal "xyz" in the static area and a distinct String object on the heap.

32. Can an interface extend another interface? Can an abstract class implement an interface? Can an abstract class extend a concrete class?

Yes to all three.

33. Can a .java file contain multiple classes?

Yes, but at most one can be public, and the file name must match that public class.

34. Can an anonymous inner class extend a class or implement an interface?

Yes; it can extend a class or implement one or more interfaces.

35. Can an inner class access members of its outer class?

Yes, including private members.

36. Uses of the final keyword in Java.

It can modify a class (prevent inheritance), a method (prevent overriding), or a variable (make it a constant).

37. Output of the given class‑initialization program.

The output is 1a2b2b (static initializer of A, static initializer of B, then constructors).

38. Conversions between data types.

String → primitive: use wrapper class parseXXX or valueOf. Primitive → String: concatenate with "" or use String.valueOf().

39. How to reverse a string?

public static String reverse(String originStr) {
    if (originStr == null || originStr.length() <= 1) return originStr;
    return reverse(originStr.substring(1)) + originStr.charAt(0);
}

40. Convert a GB2312 encoded string to ISO‑8859‑1.

String s1 = "你好";
String s2 = new String(s1.getBytes("GB2312"), "ISO-8859-1");
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJVMMemory ManagementprogramminginterviewOOP
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.