Scrivio Interview library

Primitive types, wrappers and numbers

42 questions in 14 subtopics.

Primitive types and sizes

ConceptFoundations6 min read
List Java's eight primitive types with their sizes and default field values. Why is the size of boolean not specified in bits, and what is char's range?
ScenarioIntermediate6 min read
A service stores ten million sensor readings in memory as List<Double>. Heap usage is far higher than expected. Explain why and what you would change.
ConceptPrincipal7 min read
Why did Java choose fixed-size primitives alongside objects instead of making everything an object, and how does Project Valhalla aim to change the trade-off? What should a long-lived codebase do today?

Wrapper classes and caching

CodingFoundations5 min read
What does this print and why?
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println((a == b) + " " + (c == d));
DebuggingIntermediate5 min read
A code review shows if (order.getQuantity() == limit.getMax()) where both getters return Integer. Tests pass, but production occasionally rejects valid orders. Diagnose it and say how you would stop this class of bug across the codebase.
LeadershipAdvanced6 min read
Your organization's code relies in places on synchronizing on Integer or Long wrapper objects and on == between wrappers. Recent JDKs warn about synchronization on value-based classes. How do you plan for future JDK changes in this area across many teams?

Autoboxing and unboxing costs

CodingFoundations5 min read
Spot the performance problem and rewrite it:
Long sum = 0L;
for (long i = 0; i < 1_000_000_000L; i++) {
sum += i;
}
DebuggingFoundations5 min read
This method throws NullPointerException on the return line in production. Why?
Map<String,Integer> counts = ...;
int get(String k) {
return counts.get(k);
}
ScenarioIntermediate7 min read
A profiler shows that a hot path spends significant time in Integer.valueOf and the allocation rate is high. The code uses Map<Integer, Integer> and Stream<Integer> heavily. What options do you weigh?

Widening, narrowing and casting

ConceptFoundations5 min read
Why does byte b = 10; b = b + 1; fail to compile while b += 1; and b++ compile?
CodingFoundations6 min read
What do these print?
int i = 130;
byte b = (byte) i;
long big = 3_000_000_000L;
int n = (int) big;
double d = 3.99;
int t = (int) d;
System.out.println(b + " " + n + " " + t);
DebuggingIntermediate6 min read
A billing job converts long cents to float for a report: float f = cents;. Totals in the report differ from the database by a few cents for large accounts. Explain the cause.

Integer overflow and Math.*Exact

CodingFoundations6 min read
A method computes int total = price * quantity; and sometimes returns a negative number. Explain and show two fixes.
DebuggingIntermediate6 min read
A binary search in a legacy library fails for arrays with more than about a billion elements. The midpoint line is int mid = (low + high) / 2;. What is wrong and how do you fix it?
DesignAdvanced6 min read
You are writing guidelines for a payments platform used by twenty teams. How should they handle arithmetic overflow and numeric types for amounts, counts and identifiers?

Floating point precision

CodingFoundations6 min read
Why does System.out.println(0.1 + 0.2 == 0.3); print false, and how should you compare doubles?
ConceptIntermediate7 min read
Explain how NaN and -0.0 behave in ==, Double.equals, Double.compare and in a HashSet<Double>. Why does this matter when sorting or deduplicating measurement data?
LeadershipPrincipal6 min read
Engineers keep introducing float and double for monetary and quantity fields across many services, causing reconciliation incidents. What would you put in place organization-wide, and why does Java make this mistake easy?

BigDecimal and BigInteger

CodingFoundations6 min read
What is wrong with each line?
new BigDecimal(0.1)
new BigDecimal("2.50").equals(new BigDecimal("2.5"))
BigDecimal.ONE.divide(BigDecimal.valueOf(3))
InternalsIntermediate7 min read
How does BigInteger represent values, what makes its operations expensive, and when would you use it in a backend service?
DesignIntermediate6 min read
Design the rounding policy for an invoicing service that computes tax per line and a total. Which BigDecimal choices do you make and what trade-offs do they carry?
ScenarioAdvanced7 min read
Two services exchange monetary amounts. One serializes BigDecimal as a JSON number, the other parses JSON numbers as double by default, and amounts drift. How do you fix it across the system and prevent it in new services?

Var and local type inference

ConceptFoundations6 min read
Where can you use var in Java, where can you not, and what type does var list = new ArrayList<>(); get?
LeadershipIntermediate6 min read
Your team argues about var in code reviews. Some want it everywhere, others want it banned. What guideline would you write and why?
LeadershipPrincipal7 min read
Ten years from now your codebase will have been written across Java 8 to Java 25 and beyond. Looking at features such as var, diamond and inferred lambda types, how do you decide how much type information code should state explicitly, and how do you keep that decision consistent across hundreds of engineers?

Literals and numeric underscores

CodingFoundations6 min read
What do these literals mean and which are compile errors? 1_000_000, 0x1F, 0b1010, 017, 08, 10L, 1e3, 3.0f, 1_000_, '\u0041'
DebuggingIntermediate6 min read
A constant is declared long timeoutMs = 24 * 60 * 60 * 1000 * 30; for 30 days, but timeouts happen almost immediately. Why?

Number parsing, conversion and radix

CodingFoundations6 min read
What do these return or throw, and why?
Integer.parseInt(" 42")
Integer.parseInt("+42")
Integer.parseInt("2147483648")
Integer.parseInt("ff", 16)
Integer.toBinaryString(-1)
Long.parseLong("42L")
Integer.valueOf("042")
DebuggingFoundations7 min read
A service parses prices from a CSV with Double.parseDouble(field). It works in tests but fails in production with NumberFormatException for values like "1,234.50" and gives wrong results for "12,5" from a German supplier after someone switched to NumberFormat.getInstance().parse. Explain and fix.
ScenarioIntermediate7 min read
An external API sends 64-bit unsigned identifiers and big integer amounts in JSON, and a JavaScript front end also displays them. Some ids appear wrong in the UI, and Java parsing of a few ids throws. How would you handle parsing, conversion and serialisation end to end?
DesignAdvanced7 min read
Many services parse numbers from HTTP parameters, CSV files, message payloads and configuration with different rules, causing incidents with locales, overflow and silent truncation. Propose a standard approach for numeric input handling across the platform.

Random number generation

ConceptFoundations7 min read
Compare java.util.Random, ThreadLocalRandom, SplittableRandom, SecureRandom and the RandomGenerator interface added in Java 17. Which would you use for a session token and which for a simulation running on many threads?
DebuggingIntermediate7 min read
After moving to new Linux hosts, a service's startup sometimes hangs for minutes inside SecureRandom, and a load test also shows token generation is slower than expected. Explain the possible causes and fixes.
LeadershipAdvanced7 min read
A security audit found predictable random numbers used for password reset tokens and coupon codes in several services, and test randomness making some tests flaky. Set the rules and tooling for random number use across the organisation.

Math rounding methods

CodingFoundations6 min read
What do these print? Math.round(2.5), Math.round(-2.5), Math.rint(2.5), Math.floor(-2.1), Math.ceil(-2.1), (int) -2.9, Math.floorDiv(-7, 2), -7 / 2, Math.floorMod(-7, 3), -7 % 3
DebuggingIntermediate7 min read
A report shows totals that differ by one cent from the accounting system. The code computes Math.round(amount * 100) / 100.0 on double values, and accounting uses half-even rounding on decimal amounts. Explain the differences and fix the code.

UUID generation

ConceptFoundations7 min read
How does UUID.randomUUID() work, what version does it produce, and how would you create a name-based UUID? Why are random UUIDs a poor choice as clustered primary keys in MySQL InnoDB?
DesignIntermediate7 min read
A new order service must generate ids in the application (no database round trip), keep them sortable by creation time, and expose them in URLs. Compare UUIDv4, UUIDv7, ULID and Snowflake-style 64-bit ids, and choose one.
LeadershipPrincipal7 min read
Your company has used auto-increment integers, random UUIDs, composite natural keys and several custom id formats across 20 years of systems, which now makes data integration and mergers painful. What identifier strategy would you set for the next decade?

Variables and scope

DebuggingFoundations7 min read
Why does this not compile, and how do you fix it?
int count = 0;
list.forEach(item -> {
if (item.isActive()) count++;
});
Also, what is printed by:
for (int i = 0; i < 3; i++) { }
System.out.println(i);
ConceptIntermediate8 min read
Explain the different kinds of variables in Java: local variables, parameters, instance fields, static fields, and pattern variables from instanceof and switch patterns. Where is each stored, when is it initialised, and what scoping rules apply to pattern variables?
LeadershipAdvanced7 min read
Code reviews in your organisation often argue about mutable shared state: static caches, singletons holding request data, and long methods with many reassigned local variables. What coding guidelines on variables and scope would you set, and how would you enforce them?