Java Language basics
Values, types, operators and control flow. The one idea that matters more than all the syntax is the difference between a primitive and a reference.
8 concepts · 23 interview questions
What this topic covers
Every concept in language basics, and the questions each one gets asked as. Where a question links, it has a full write-up.
Primitives and their ranges
Eight built-in types stored by value, each with a fixed size and a silent overflow at its boundary rather than an error.
- What are the eight primitive types and their sizes?
- What happens when an int overflows?
- Why is char 16 bits, and what does that mean for emoji?
References vs primitives
A variable holds either a value or an address. This single distinction explains null, equality, parameter passing and most beginner bugs.
- What is the difference between a primitive and a reference variable?
- Is Java pass-by-value or pass-by-reference?
- Where do primitives and objects actually live in memory?
Autoboxing and the Integer cache
The compiler converts between int and Integer silently, and valueOf caches -128..127, so == appears to work on small numbers and breaks above 127.
- Why does == work for Integer 127 but not 128?
- What is autoboxing, and where does it cost you performance?
- What happens when you unbox a null Integer?
Floating point and money
double is binary floating point, so decimal fractions are approximations — which makes it wrong for currency in a way that only shows up in totals.
- Why is 0.1 + 0.2 not equal to 0.3?
- What should you use for money, and why not double?
- What do Double.NaN and Infinity compare equal to?
Operators and precedence
Integer division truncates, % keeps the sign of the dividend, and && short-circuits — three behaviours that produce silent wrong answers rather than errors.
- What does 5 / 2 evaluate to, and why?
- What is the difference between & and &&?
- What does i++ + ++i evaluate to?
Control flow and switch
if, loops, and two different switches — the old fall-through statement and the modern arrow expression that returns a value and can be checked for exhaustiveness.
- What is the difference between a switch statement and a switch expression?
- Why does switch fall through, and when is that useful?
- What can you switch on, and what has changed by version?
Arrays
Fixed-length, zero-indexed objects with default-initialised elements and covariant typing that lets a store fail at runtime.
- What is the default value of an array element?
- Why does Object[] a = new String[1]; a[0] = 1; compile but fail at runtime?
- How do you copy an array, and what does shallow mean here?
var and type inference
A local-variable-only inference keyword. The type is still static and fixed at compile time; nothing about it is dynamic.
- Where can you use var, and where can you not?
- Does var make Java dynamically typed?