Advertisement

Java Fundamentals: Syntax, Data Types & Operators interview questions and answers

15 Java Fundamentals: Syntax, Data Types & Operators interview questions for Java roles, each with a model answer, examples and likely follow-ups.

15 questions
Advertisement

15 questions

Q1 Beginner Save

What are the eight primitive data types in Java, and how do they differ fundamentally from reference types like String or a custom class?

The eight primitives are byte, short, int, long (integer types of increasing size), float, double (floating-point types), char (a single 16-bit Unicode character), and boolean (true/false) -- primitives store their actual value directly in the variable's own memory location (whether a stack frame slot or as part of an object's fields), have a fixed, well-defined size and value range, and always have a sensible zero-equivalent default, while reference types store a reference (pointer) to an object's data located elsewhere on the heap, default to null, and can be arbitrarily complex, custom-defined, or even represent primitive-like values via boxing (Integer wrapping an int).
int primitiveInt = 42;           // stores the value 42 directly
Integer boxedInt = 42;            // stores a REFERENCE to a heap-allocated Integer object holding 42

boolean isActive = true;          // direct value
String name = "Alice";            // reference to a heap-allocated String object
String nullName = null;           // reference types can be null; primitives never can
Real-world example
A performance-sensitive numerical calculation loop deliberately uses primitive int and double variables rather than their boxed Integer/Double wrapper equivalents, avoiding both the memory overhead of heap-allocated wrapper objects and the CPU cost of repeated auto-boxing/unboxing across millions of loop iterations.
Likely follow-ups
  • Why can't a primitive type ever be null, unlike every reference type?
  • What's the memory size in bytes of each of the eight primitive types?
Arrays & Multidimensional Arrays Garbage Collection
Q2 Intermediate Save

How does Java's operator precedence and associativity determine the evaluation order of a complex expression, and what are some common precedence-related mistakes?

Operator precedence determines which operators bind more tightly (evaluated first) in an expression with multiple different operators (multiplication/division bind tighter than addition/subtraction, matching standard mathematical convention), and associativity determines the evaluation order among operators of the SAME precedence level (most binary operators are left-to-right associative, but assignment and unary operators are right-to-left) -- a common mistake involves bitwise operators (&, |) having LOWER precedence than comparison operators (==, <), meaning an expression like `if (a == b & c == d)` actually parses correctly by coincidence in that specific case, but a similar expression relying on unparenthesized mixing of bitwise and comparison operators without careful attention to precedence rules can easily produce surprising, unintended results.
int result = 2 + 3 * 4;  // 14, not 20 -- multiplication (*) binds tighter than addition (+)

// A classic precedence pitfall: bitwise AND (&) has LOWER precedence than equality (==)
boolean flag = (a == 1) & (b == 2);  // parentheses needed to make intent unambiguous and correct
// boolean confusing = a == 1 & b == 2;  // technically works due to precedence rules, but far less readable
Real-world example
A code review flags an expression mixing bitwise and comparison operators without explicit parentheses as a readability and correctness risk, even though the code happens to produce the intended result given Java's specific precedence rules, recommending explicit parentheses purely for clarity regardless of technical correctness.
Likely follow-ups
  • Why does Java prioritize consistency with mathematical convention for arithmetic operator precedence specifically?
  • What's the specific precedence relationship between the ternary conditional operator (?:) and simple assignment (=)?
OOP & Classes Exceptions
Q3 Advanced Save

How does Java's autoboxing and unboxing mechanism work at the bytecode level, and what specific performance and correctness pitfalls does it introduce in seemingly innocuous code, such as within a loop?

Autoboxing automatically converts a primitive value to its corresponding wrapper object (int to Integer via Integer.valueOf(), which the JVM's small-integer cache -128 to 127 may satisfy from a pre-existing cached instance rather than allocating a new one) when a primitive is used where an object reference is expected (like adding to a generic collection), and unboxing does the reverse (calling .intValue() automatically) when an object is used where a primitive is expected -- a notorious performance pitfall occurs when this boxing/unboxing happens repeatedly and invisibly inside a tight loop (like accumulating a sum into a boxed Long inside a loop, where each += operation unboxes, adds, and reboxes a brand new Long object every single iteration), and a notorious correctness pitfall occurs when comparing boxed values with == (as covered earlier regarding Integer caching) rather than .equals().
// Hidden performance cost: repeated unboxing/reboxing inside a loop
Long sum = 0L;  // boxed type
for (int i = 0; i < 1_000_000; i++) {
    sum += i;  // each iteration: unbox sum, add, REBOX into a brand new Long object -- expensive!
}

// Better: use the primitive type directly for accumulation
long sum2 = 0L;
for (int i = 0; i < 1_000_000; i++) {
    sum2 += i;  // no boxing overhead at all
}
Real-world example
A performance profiling session on a data-aggregation service reveals an unexpectedly large number of Long object allocations, traced to an accumulator variable being declared as the boxed Long type instead of the primitive long, causing a new Long object to be allocated on literally every single iteration of a hot summation loop, fixed with a one-line type change.
Likely follow-ups
  • What is the Integer cache, and why does it only apply to a specific range of small integer values rather than all integers?
  • How would you detect excessive autoboxing-related allocation in a profiler's output?
Diagnostics & Performance Garbage Collection
Q4 Intermediate Save

What is the difference between the == operator and the .equals() method when comparing String objects, and why does String's string pool (interning) behavior sometimes make == appear to 'work' for strings?

== on String references compares object identity (whether both references point to the literal same object instance), while .equals() compares actual character content -- Java's string pool (a special area of the heap, or since Java 7 part of the regular heap conceptually) automatically interns String LITERALS (two string literals with identical content, like "hello" appearing twice in source code, are guaranteed to reference the exact same pooled object), which is why == sometimes coincidentally 'works' for comparing string literals specifically, but this same guarantee does NOT extend to Strings constructed via `new String(...)` or built dynamically at runtime (like via concatenation of variables), making == fundamentally unreliable for String comparison in general and .equals() the only genuinely correct approach.
String a = "hello";
String b = "hello";
System.out.println(a == b);  // true -- both literals, interned to the SAME pooled object

String c = new String("hello");
System.out.println(a == c);  // false! 'new String(...)' explicitly creates a NEW, separate object
System.out.println(a.equals(c));  // true -- correctly compares actual content, regardless of identity
Real-world example
A subtle bug where a string comparison using == worked correctly in unit tests (using string literals) but failed unpredictably in production (comparing a string literal against a string built via concatenation, which is NOT automatically interned) is traced directly to this exact == versus .equals() distinction, resolved by consistently using .equals() for all String content comparisons.
Likely follow-ups
  • What does String.intern() do, and when might you deliberately call it on a dynamically-constructed String?
  • Why doesn't Java automatically intern every String, given the string pool exists specifically for this purpose?
equals() hashCode() & toString() Contracts Collections Framework
Q5 Advanced Save

How does Java's implicit numeric type promotion and narrowing/widening conversion rules work, and what specific data-loss or precision risks does an implicit narrowing conversion (requiring an explicit cast) guard against?

Widening conversions (byte to short to int to long to float to double, roughly in that order of increasing range) happen automatically/implicitly since they cannot lose information (every value representable in the smaller type is also representable in the larger type, EXCEPT for a subtle precision loss risk when widening a large long value to float/double, since floating-point types trade some integer precision for a vastly larger representable range); narrowing conversions (the reverse direction) require an EXPLICIT cast specifically because they genuinely CAN lose information (a large int value narrowed to byte will have its high-order bits silently truncated, producing a completely different, unexpected value) -- Java requiring an explicit cast for narrowing is a deliberate safety measure forcing the developer to consciously acknowledge and accept this potential data loss, rather than it happening silently and unnoticed.
int largeValue = 300;
byte narrowedValue = (byte) largeValue;  // explicit cast REQUIRED -- silently loses information!
System.out.println(narrowedValue);  // -12, NOT 300 -- high-order bits were truncated, unexpected result

long bigLong = 123456789012345L;
float asFloat = bigLong;  // implicit widening, but MAY lose some precision despite no cast being required
System.out.println(asFloat);  // may not exactly equal the original long value, due to float's precision limits
Real-world example
A bug where a calculated value became unexpectedly negative and nonsensical after being assigned to a byte-typed field is traced to an unnoticed implicit narrowing bug (actually an explicit but incorrect cast the developer added to silence a compiler error without understanding its consequences), truncating a value that had grown larger than byte's -128 to 127 range could actually represent.
Likely follow-ups
  • Why does widening a long to a float NOT require an explicit cast despite potentially losing some precision, while narrowing conversions always do?
  • What compile-time versus runtime behavior differs between an implicit widening conversion and an explicit narrowing cast?
Exceptions Diagnostics & Performance
Q6 Intermediate Save

What is the difference between a Java text block (introduced as a standard feature in Java 15) and a traditional String literal, and what specific syntax rules govern indentation handling?

A text block (delimited by triple double-quotes """) lets you write multi-line String literals directly in source code without needing explicit \n escape sequences or string concatenation across lines, automatically handling incidental leading whitespace stripping based on the closing delimiter's own indentation (the 'minimal indentation' across all lines, including the closing delimiter's position, is stripped uniformly from every line) -- this dramatically improves readability for embedded multi-line content like JSON, SQL queries, or HTML snippets directly within Java source code, compared to the older approach of manually concatenating multiple string literals with explicit newline escapes.
// Old approach: verbose, error-prone concatenation with explicit \n
String oldJson = "{\n" +
    "  \"name\": \"Alice\",\n" +
    "  \"age\": 30\n" +
    "}";

// Modern text block: clean, readable, matches how the content actually looks
String newJson = """
    {
      "name": "Alice",
      "age": 30
    }
    """;
Real-world example
A codebase embedding SQL queries directly in Java source switches from painfully concatenated multi-line string literals (requiring manual \n and string-plus-string concatenation for every line) to text blocks, immediately improving readability and making the embedded SQL look and format almost exactly as it would in a standalone .sql file.
Likely follow-ups
  • How exactly does the text block's automatic indentation-stripping algorithm determine how much leading whitespace to remove from each line?
  • Can you still use escape sequences like \n or \" within a text block if genuinely needed?
Java Networking & HTTP Client OOP & Classes
Q7 Advanced Save

How does the var keyword (local variable type inference, introduced in Java 10) work, and what specific restrictions apply to where it can and cannot be used, given Java remains a statically-typed language?

var lets the compiler infer a local variable's static type from its initializer expression at compile time (NOT a dynamic/untyped variable the way JavaScript's var behaves -- the inferred type is fixed permanently at compile time, and the variable remains just as strictly, statically typed as if you'd written the type explicitly) -- var is restricted to local variables with an initializer present (var x; with no initializer is illegal, since there'd be nothing to infer the type FROM), cannot be used for method parameters, return types, or fields, and using it with certain expressions (like a lambda or an array initializer without an explicit type context) can be ambiguous or disallowed since the compiler needs enough contextual information to actually determine a concrete type.
var list = new ArrayList<String>();  // inferred as ArrayList<String>, fully statically typed thereafter
list.add("hello");
// list.add(42);  // still a COMPILE ERROR -- var doesn't remove type safety, only removes explicit type-writing

// var x;  // ILLEGAL -- no initializer to infer the type from
// var lambda = () -> System.out.println("hi");  // ILLEGAL -- ambiguous, no concrete inferable type
Real-world example
A team adopts var consistently for local variables with sufficiently descriptive right-hand-side expressions (like var customers = customerRepository.findAll()), improving code conciseness and reducing redundant type-name repetition, while deliberately avoiding var where the inferred type wouldn't be immediately obvious from context alone (like var result = someMethod(), where the actual returned type isn't clear without checking the method signature).
Likely follow-ups
  • What's the JDK style guideline recommendation for when var actually improves versus hurts code readability?
  • Why can't var be used for a lambda expression's target variable directly, given lambdas already require a target type for other purposes?
Generics Functional Interfaces & Method References
Q8 Intermediate Save

What is the difference between the ++ (increment) and -- (decrement) operators used in prefix versus postfix position, and what subtle bug can arise from using them within a complex expression?

The prefix form (++x) increments the variable FIRST, then evaluates to the NEW, already-incremented value; the postfix form (x++) evaluates to the ORIGINAL, pre-increment value FIRST, then increments the variable afterward -- using either form within a larger, complex expression that also references the same variable elsewhere (like `int result = x++ + x++;` or worse, combining pre/post-increment of the same variable with an assignment to that same variable in one statement) can produce genuinely confusing, easy-to-misjudge results, and is generally considered poor practice specifically because the exact evaluation order and timing, while technically well-defined by the language specification, is difficult for most readers (and even experienced developers) to correctly reason about at a glance.
int x = 5;
int a = x++;  // a = 5 (original value), x becomes 6 afterward

int y = 5;
int b = ++y;  // y becomes 6 FIRST, b = 6 (the new, incremented value)

// Confusing, discouraged: mixing multiple increments of the SAME variable in one expression
int z = 1;
int confusing = z++ + ++z;  // technically well-defined (results in 1 + 3 = 4), but genuinely hard to read correctly
Real-world example
A code review flags a statement combining both prefix and postfix increment of the same variable within a single complex expression as a readability hazard, recommending it be split into multiple separate, clearer statements even though the original code was technically correct according to Java's well-defined evaluation order rules.
Likely follow-ups
  • Why does the Java Language Specification define such precise evaluation order rules for these operators if using them this way is discouraged anyway?
  • Is there ever a genuinely good, readable reason to prefer prefix over postfix increment (or vice versa) in ordinary, non-confusing code?
OOP & Classes Exceptions
Q9 Advanced Save

How does Java's integer division and modulo operator behave with negative operands, and how does this differ from the mathematical definition of modulo used in some other contexts (like array indexing wraparound)?

Java's integer division truncates toward zero (rather than always rounding down/toward negative infinity, which is how some other languages and pure mathematics define integer division), and the % (remainder/modulo) operator's result takes the SAME SIGN as the dividend (the left operand), not necessarily the same sign as the divisor -- this means Java's % operator is more accurately described as a 'remainder' operator rather than a true mathematical modulo operator, and naively using % for something like wraparound array indexing with a potentially negative index will NOT produce the always-non-negative result a true mathematical modulo would, requiring an explicit adjustment (adding the divisor and taking % again) to achieve genuine non-negative wraparound behavior.
System.out.println(-7 / 2);   // -3, truncated toward zero (not -4, which flooring would give)
System.out.println(-7 % 2);   // -1, takes the sign of the DIVIDEND (-7), not always positive

// Naive wraparound indexing FAILS for negative indices
int index = -1;
int size = 5;
// int wrapped = index % size;  // -1, NOT the intended 4!

// Correct wraparound requires an explicit adjustment
int correctlyWrapped = ((index % size) + size) % size;  // 4, genuinely non-negative
Real-world example
A circular buffer implementation using naive % for wraparound indexing produces an ArrayIndexOutOfBoundsException when a computed index happens to go negative, traced to Java's % operator not behaving like true mathematical modulo for negative operands, fixed by adding the explicit ((x % n) + n) % n adjustment pattern.
Likely follow-ups
  • Why did Java choose truncating division/remainder-style modulo rather than flooring division/true modulo, given the latter avoids this specific pitfall?
  • How does Math.floorMod() differ from the % operator, and when should you prefer it?
Arrays & Multidimensional Arrays Diagnostics & Performance
Q10 Intermediate Save

What is the difference between a compile-time constant expression and a regular final variable, and why does this distinction matter for switch statement case labels and certain compiler optimizations?

A compile-time constant is a final variable of a primitive type or String, initialized with a constant expression that the compiler can fully evaluate AT COMPILE TIME (not depending on any runtime computation, method call, or non-final variable) -- this specific category matters because traditional switch statement case labels require genuine compile-time constants (a final variable initialized from a method call, even if effectively constant at runtime, does NOT qualify), and the compiler can also perform certain optimizations (like inlining the constant's value directly at each usage site) specifically for true compile-time constants that it cannot safely perform for an ordinary final variable whose value merely happens to never change after initialization but wasn't determinable purely at compile time.
final int COMPILE_TIME_CONST = 5;              // compile-time constant -- computed purely from a literal
final int RUNTIME_FINAL = computeValue();        // final, but NOT a compile-time constant -- depends on a method call

switch (x) {
    case COMPILE_TIME_CONST:  // LEGAL -- genuine compile-time constant
        break;
    // case RUNTIME_FINAL:    // COMPILE ERROR -- not a compile-time constant, even though it's final!
}
Real-world example
A developer's attempt to use a final variable (initialized by calling a configuration-loading method) as a switch statement case label results in a confusing compile error, resolved once they understand the specific 'compile-time constant expression' requirement distinct from simply being final, which their runtime-computed value doesn't satisfy despite otherwise never changing.
Likely follow-ups
  • Why does a switch statement specifically require this stricter compile-time-constant guarantee rather than simply requiring the value be final?
  • How does this same compile-time-constant concept relate to what values are legal in an annotation's element assignments?
Pattern Matching & Switch Expressions Annotations

Showing 1–10 of 15