Primitive types, wrappers and numbers
42 questions in 14 subtopics.
Primitive types and sizes
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?A service stores ten million sensor readings in memory asList<Double>. Heap usage is far higher than expected. Explain why and what you would change.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
What does this print and why?Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println((a == b) + " " + (c == d));
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.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
Spot the performance problem and rewrite it:Long sum = 0L;
for (long i = 0; i < 1_000_000_000L; i++) {
sum += i;
}
NullPointerException on the return line in production. Why?Map<String,Integer> counts = ...;
int get(String k) {
return counts.get(k);
}
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
Why doesbyte b = 10; b = b + 1; fail to compile while b += 1; and b++ compile?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);
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
A method computesint total = price * quantity; and sometimes returns a negative number. Explain and show two fixes.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?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
Why doesSystem.out.println(0.1 + 0.2 == 0.3); print false, and how should you compare doubles?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?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
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))
BigInteger represent values, what makes its operations expensive, and when would you use it in a backend service?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?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
Where can you use var in Java, where can you not, and what type doesvar list = new ArrayList<>(); get?Your team argues about var in code reviews. Some want it everywhere, others want it banned. What guideline would you write and why?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
What do these literals mean and which are compile errors? 1_000_000, 0x1F, 0b1010, 017, 08, 10L, 1e3, 3.0f, 1_000_, '\u0041'A constant is declaredlong timeoutMs = 24 * 60 * 60 * 1000 * 30; for 30 days, but timeouts happen almost immediately. Why?Number parsing, conversion and radix
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")
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.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?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
Comparejava.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?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.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
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 % 3A 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
How doesUUID.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?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.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
Why does this not compile, and how do you fix it?int count = 0;
list.forEach(item -> {
if (item.isActive()) count++;
});
for (int i = 0; i < 3; i++) { }
System.out.println(i);
No question matches these choices.