← All topics
Start ▶
Core Java
OOP, String, equals/hashCode, exceptions — where every interview starts.
100 questions
Level:
No questions match — try other words or turn a level back on.
1
What is the difference between a primitive type and a reference type in Java?
A primitive variable stores the value itself (int x = 5), while a reference variable stores a reference to an object on the heap. A primitive can't be null, but a reference can.
2
In Java, are arguments passed to a method "by value" or "by reference"?
Always by value. When you pass an object, a copy of the reference is passed: the method can change the inside of the object, but it can't make the caller's variable point to a different object.
3
What is the difference between == and equals()?
== compares values for primitives, and for objects it compares references: whether both are the very same object. equals() compares the contents of objects, if the class overrides it correctly.
4
What does it give you in practice that String is immutable?
A String, once created, never changes. Because of that, it can be shared safely between threads, reused in the String pool, have its hash cached, and be used freely as a HashMap key.
5
What is the difference between String, StringBuilder and StringBuffer?
String is immutable. StringBuilder is mutable and fast, but not thread-safe. StringBuffer is mutable and synchronized, so it's slower; today it's hardly used.
6
What does the final keyword mean on a variable, a method and a class?
On a variable, the value (or reference) can be assigned only once; on a method, a subclass can't override it; on a class, it can't be extended.
7
What are static fields and static methods, and when do you use them?
A static member belongs to the class itself, not to an object: there's one copy of it, and you access it with ClassName.member without creating an object. It's handy for utility methods, constants and factory methods.
8
What is the difference between checked and unchecked exceptions?
The compiler enforces checked exceptions (IOException, SQLException): you must either catch them or declare them with throws. Unchecked ones, which are RuntimeException and its descendants (NullPointerException, IllegalArgumentException), aren't required.
9
What is try-with-resources, and why do you need it?
Resources opened in the try (...) parentheses (anything that's AutoCloseable) are closed automatically when the block ends, even if there's an error. The problem of writing close() by hand in finally, and forgetting it, goes away.
10
What are autoboxing and unboxing, and what problems can they cause?
Autoboxing is the automatic conversion of a primitive into its wrapper class (int to Integer), and unboxing is the reverse. It's convenient, but it causes an NPE when unboxing null, extra objects in loops, and wrong results when you compare with ==.
11
Why does comparing two Integers with == sometimes give true and sometimes false?
Integer.valueOf caches values from -128 to 127 and returns the same object, so == gives true. Outside that range a new object is created each time, and == compares references and gives false.
12
What happens when an int value goes past its limit (overflow)?
No exception is thrown: the value silently "wraps around" to a negative (or the opposite) number. For example, Integer.MAX_VALUE + 1 equals Integer.MIN_VALUE. For important calculations, use Math.addExact or a long.
13
Why do you use BigDecimal and not double when calculating with money?
A double is stored in binary and can't represent decimal fractions like 0.1 exactly, so rounding errors pile up. BigDecimal stores the decimal number exactly, and you set the rounding rule yourself.
14
What is an enum, and what makes it better than plain int or String constants?
An enum is a special class for a limited, known-in-advance set of values. The compiler accepts only the allowed values, it works nicely with switch, and you can add fields and methods to an enum.
15
What does the var keyword do, and when should you not use it?
var (Java 10+) lets the compiler infer a local variable's type from the expression on the right. The type is still static and doesn't change; it only shortens the code. When the type isn't obvious from the expression, it makes the code harder to read.
16
What is a record, and how does it differ from an ordinary class?
A record (Java 16+) is a short way to write an immutable data-carrier class. The compiler generates the constructor, the private final fields, the accessors, equals, hashCode and toString for you.
17
What makes the switch expression in Java 14+ better than the old switch?
The new switch returns a value, is written with -> and needs no break, so "fall-through" bugs go away. If an enum or sealed type isn't fully covered, the compiler gives an error.
18
What is a text block (""" ... """), and where is it handy?
A text block (Java 15+) is a way to write a multi-line string without escape characters (\n, \"). It's handy for text like SQL, JSON and HTML; the common leading whitespace is stripped automatically.
19
Why do you need Optional, and what's the right way to use it?
Optional<T> is a container that states "there might be no value" openly in the method signature. It's mainly used as a return type: the caller can't walk past the "no value" case without thinking about it.
20
Why does the main method look like public static void main(String[] args)?
The JVM calls it without creating an object (static), from outside the class (public), doesn't expect a result (void), and passes the command-line arguments as a String[]. In Java 21+ a simpler void main() also appeared, as a preview.
21
What happens if equals() is overridden but hashCode() isn't?
Hash-based collections like HashMap and HashSet break: equal objects land in different buckets, so contains and get don't find them, and duplicates show up in a Set.
22
What is the String pool, and what's the difference between "abc" and new String("abc")?
The String pool is a special table on the heap where literal strings are kept as a single copy. "abc" gets the object from the pool, while new String("abc") always creates a new object. intern() replaces a string with the copy in the pool.
23
What does this method return, and why is writing return inside finally dangerous?
It returns 2. A return in finally overrides the value returned from try, and it even silently swallows an exception thrown inside try.
24
Why is "swallowing" an error with catch (Exception e) {} dangerous?
The error disappears: the system keeps running in a wrong state, there's no trace in the log, and the problem shows up somewhere else, much later, in a form whose cause you can't find.
25
Why does new BigDecimal("2.0").equals(new BigDecimal("2.00")) return false?
BigDecimal.equals compares the scale (the number of digits in the fractional part) along with the value: 2.0 (scale 1) and 2.00 (scale 2) are not equal. To compare only the numeric value, use compareTo(...) == 0.
26
What is type erasure in generics, and what limitations does it bring?
Generic type parameters exist only at compile time; in the bytecode they're erased (List<String> becomes List). So at runtime there's no information about T: you can't do new T(), instanceof List<String>, or create a T[].
27
How does varargs (String... args) work, and what traps does it have?
A varargs parameter is an ordinary array inside the method, and the caller can pass 0 or more arguments. The traps: an array is created on every call, passing null is confusing, and generic varargs gives a heap pollution warning.
28
Why does this code throw a NullPointerException?
One side of the ternary operator is the primitive int (0), so the whole expression stays an int and the Integer side gets unboxed. When map.get(...) returns null, the unboxing throws an NPE.
29
What does this code print, and why?
parent static, child static, parent instance, parent ctor, child instance, child ctor. First the classes are loaded (parent, then child) and their static blocks run. Then, when the object is created, each class runs its instance initializer first and its constructor after, going from parent to child.
30
How do you write an immutable class?
Make the class final, make all fields private final, provide no setters, and make defensive copies of mutable fields (a list, an array, a Date) in the constructor and in the getter. "Modifying" methods should return a new object.
31
What is the difference between ? extends T and ? super T in generics? Explain the PECS rule.
? extends T means "T or its descendant": you read from it but can't write to it (a producer). ? super T means "T or its ancestor": you can write a T into it, but what you read back is only Object (a consumer). PECS: Producer Extends, Consumer Super.
32
Why do you need sealed classes and interfaces?
sealed (Java 17) limits who can extend a class or implement an interface, with an explicit list. That gives you a closed hierarchy, and the compiler itself checks that a switch covers every case.
33
How does pattern matching in Java 21 (instanceof and switch) simplify code?
The instanceof check and the cast happen in one step, and switch can work by type, unpack a record (a record pattern) and take an extra condition (when). Casts and long if-else chains go away.
34
How do you add validation to a record's constructor, and what limitations do records have?
In a "compact" constructor you can validate and normalize the parameters, and the record assigns the fields itself. The limitations: the fields are immutable, it can't extend another class, and you can't add extra instance fields.
35
How do you design your own exception hierarchy for an application?
I create a few meaningful unchecked domain exceptions (extending RuntimeException): for example "not found", "business rule violated", "conflict", "external service failed". Each one makes it clear how the caller or the global handler should react, and keeps the original cause.
36
What are the typical ways to misuse Optional?
Calling get() without a check, making Optional a field or a parameter, returning null instead of an Optional, wrapping a collection in Optional, and doing expensive computation inside orElse.
37
How expensive is joining Strings with + in a loop, and what has modern Java changed about it?
In a loop, s += x creates a new String on every iteration and copies the whole text, which makes it O(n²). Since Java 9, a single-expression + runs fast through invokedynamic (StringConcatFactory), but that doesn't fix the loop: there you need StringBuilder.
38
What problems come with char, byte and text encoding (UTF-8) in Java?
In Java, char is a 16-bit UTF-16 code unit and byte is 8 bits. When you convert text to bytes and back without naming the encoding, the platform's default encoding is used, and Uzbek o', g' or emoji come out broken. Always pass StandardCharsets.UTF_8 explicitly.
39
What is the difference between Instant, LocalDateTime, ZonedDateTime and OffsetDateTime in java.time, and when do you use each?
Example / When — Instant: 2026-11-01T09:00:00Z / logs, audit, "when did it happen"; LocalDate: 2026-11-01 / a birthday, a holiday; LocalDateTime: 2026-11-01T14:00 / "class every day at 14:00" (a plan with no time zone); ZonedDateTime: ...T14:00+05:00[Asia/Tashkent] / showing to the user, calculating with zone rules…
40
Why were default methods added to interfaces, and what happens if two interfaces have the same default method?
Default methods (Java 8) were added so you can add a new method to an old interface without breaking the classes that implement it. If two interfaces have a default method with the same signature, the class must override it itself and, if needed, pick with InterfaceName.super.method().
41
An object put into a HashMap can't be found later. What could be wrong in the key class?
Most likely the key is mutable: the field that hashCode() is computed from changed after put. The object stays in the old bucket, while get looks in a different bucket using the new hash.
42
When writing equals() where inheritance is involved, which do you choose, getClass() or instanceof?
An equals written with instanceof breaks symmetry when parent and child classes are mixed. getClass() keeps symmetry, but it never considers a subclass equal, such as a Hibernate proxy.
43
What are compact strings in Java 9, and how is data stored inside a String?
Since Java 9, a String holds a byte[] and a coder instead of a char[]. If every character fits in Latin-1, it's 1 byte per character; if not, it's 2 bytes in UTF-16.
44
Why is creating an exception expensive, and how can you reduce that in high-load code?
Most of the cost goes to fillInStackTrace(): the constructor walks the whole stack. Don't use exceptions for ordinary control flow (instead of if/else), and if you need to, create an exception without a stack trace.
45
In try-with-resources, if both the try block and close() throw an exception, which one is lost?
Neither is lost. The main one is the one thrown out of the try block, and the one from close() is attached to it as suppressed; you get it with getSuppressed().
46
What should you do when you catch InterruptedException, and what does swallowing it lead to?
Either you pass the exception up, or you put the interrupt flag back with Thread.currentThread().interrupt(). If you swallow it, the stop request is lost and the executor shutdown hangs.
47
What is heap pollution, and when is it right to put @SafeVarargs on a method?
Heap pollution is a situation where a variable of a parameterized type actually points to an object of a different type. Generic varargs create a T[] array, which is why the compiler warns; you add @SafeVarargs if the method doesn't write into the array and doesn't hand it out.
48
What is a bridge method, and when does the compiler create one?
It's a synthetic method that the compiler adds on its own when you inherit from a generic type or narrow a return type. It routes the post-erasure signature to your method, so polymorphism doesn't break.
49
On which line does the ClassCastException occur in this code, and why exactly there?
Not at add, but in the for loop. An Integer got into the List<String> through a raw type, and the compiler put the cast at the place where elements are read.
50
Why can't you write new T[], and what are the ways to create a generic array correctly?
Because of erasure, T is unknown at runtime, but an array has to know its element type at runtime. The way out is to pass a Class<T> or an IntFunction<T[]>, or to keep an Object[] inside and return a List to the outside.
51
What do signatures like <T extends Comparable<? super T>> mean, and why is Enum<E extends Enum<E>> written that way?
The first one means a T can be compared with itself or with its supertype. The second is a recursive generic, so that methods like compareTo work with exactly that concrete enum type.
52
What is the internal structure of EnumMap and EnumSet, and why are they faster than HashMap/HashSet?
Both are built on ordinal(): EnumMap is a plain array indexed by ordinal, and EnumSet is a bit vector (a single long for up to 64 constants). There's no hash, no bucket, and no boxing.
53
Why is a singleton written as an enum more resistant to reflection and serialization?
The JVM creates an enum constant exactly once and doesn't allow any other creation: Constructor.newInstance fails on an enum, and deserialization returns that very constant by name.
54
When are constant-specific bodies for enum constants useful?
When each constant has to behave in its own way: for example, each commission type has its own formula. You declare an abstract method in the enum and each constant overrides it; if you add a new constant, the compiler asks for an implementation.
55
A record is convenient as a DTO, so why doesn't it work for a JPA entity?
An entity needs a no-args constructor, mutable fields and a subclass for lazy proxies. A record has none of these: the class is final, the fields are final, and there's no no-args constructor.
56
What are record patterns in Java 21, and how do they unpack nested data?
A record pattern unpacks a record into its parts inside instanceof or switch: case Point(int x, int y). You can nest a pattern inside a pattern, and getter chains and casts go away.
57
What happens to pattern switches when a new subtype is added to a sealed interface, and why is it better not to write default?
Without default, the compiler flags every switch that doesn't cover the new subtype as an error. With default, the new case quietly falls into it, and the bug only shows up at runtime.
58
How do case null, guards (when) and case order work in a pattern switch?
In Java 21, a switch throws an NPE on null unless there's a case null. when is an extra condition. Cases are checked from top to bottom; if a broad pattern comes before a narrow one, the compiler reports a "dominance" error.
59
An annotation I wrote isn't visible through reflection at runtime. What could be the reason?
Most often @Retention(RUNTIME) was forgotten: the default is CLASS, so the annotation is in the bytecode but reflection doesn't see it. Or the lookup is going through a proxy class or a bridge method.
60
How does an annotation processor (Lombok, MapStruct) differ from runtime reflection?
An annotation processor runs inside javac at build time and writes new source code, so there's no cost at runtime. Reflection reads the annotation while the application is running: it's flexible, but slower, and errors show up later.
61
After moving to Java 17, InaccessibleObjectException started appearing. What is it and how do you fix it?
Since Java 16, the JDK's internal packages are strictly closed: setAccessible(true) on a private member of a package that isn't opened no longer works. You upgrade the library, or otherwise temporarily pass --add-opens.
62
What is the difference between exports and opens in module-info.java, and which one do Spring or Hibernate need?
exports makes a package's public types visible to other modules, both at compile time and at runtime. opens opens the way to deep reflection (private members, setAccessible) at runtime. Frameworks usually need opens.
63
How does java.lang.reflect.Proxy work, and what is its limitation?
Proxy.newProxyInstance builds a class at runtime that implements the given interfaces and sends every call to InvocationHandler.invoke. The limitation is that it works only with interfaces: it can't proxy an ordinary class.
64
Is there only a syntax difference between a lambda and an anonymous class?
Anonymous class / Lambda — this: the anonymous object itself / the enclosing class's object; Scope: new: it can "shadow" an outer variable / not new: you can't declare a variable with the same name; Bytecode: Outer$1.class / invokedynamic + LambdaMetafactory, created at runtime; Instances: a new object on every new /…
65
Why is Java's standard serialization mechanism (Serializable) dangerous, and what is serialVersionUID for?
readObject can create any class on the classpath from untrusted bytes and call its methods, and through gadget chains this has gone as far as RCE. serialVersionUID checks that class versions are compatible.
66
What problems does Object.clone() have, and what's better to use for copying?
clone() doesn't call a constructor, makes a shallow copy by default, Cloneable is an odd marker with no method, and it doesn't get along with final fields either. A copy constructor or a static factory is simpler and safer.
67
What does this code print? What happens when an overridable method is called from a constructor?
It prints null. The Base constructor calls Child.init(), and at that moment Child's fields haven't been assigned yet. That's why you shouldn't call an overridable method from a constructor.
68
What traps are there with NaN, -0.0 and Double.compare() when working with double?
NaN == NaN is false, but Double.valueOf(NaN).equals(NaN) is true; 0.0 == -0.0 is true, but equals says false. == follows IEEE 754, while equals/compare look at the bits, and in collections and sorting that difference causes bugs.
69
How do you call a method that throws a checked exception inside a stream or a lambda?
Standard interfaces like Function and Consumer have no checked exceptions. You either wrap it in an unchecked exception inside the lambda, write your own functional interface, or return the error as a result.
70
How does the error "com.shop.User cannot be cast to com.shop.User" come about?
The same class was loaded by two different ClassLoaders. For the JVM, a class is its name plus the loader that loaded it, so these are two different types, and one can't be cast to the other.
71
On the prod server, "TITLE".toLowerCase() or String.format("%.2f", x) gave a different result than on my local machine. What locale-related traps are there?
toLowerCase(), toUpperCase(), String.format and NumberFormat called without a locale take the JVM's default locale. In the Turkish locale, I becomes a dotless ı in lowercase, and in the Russian locale the decimal separator is a comma. For machine-readable text, always pass Locale.ROOT.
72
Even with erasure, how do Jackson's TypeReference<List<User>> or Spring's ParameterizedTypeReference know the generic type?
They create an anonymous subclass: new TypeReference<List<User>>() {}. The generic arguments of the superclass are stored in the Signature attribute of the .class file and are read with getGenericSuperclass(). Erasure removes the type from objects, not from class declarations.
73
An endpoint with a regex that extracts emails from text pushed the CPU to 100% on large requests. How does regex backtracking turn into a DoS, and how do you protect against it in Java?
java.util.regex is a backtracking engine: on text that doesn't match, it retries many alternatives. Java 9+ softened the classic (a+)+ blow-up quite a bit, but quadratic and worse cases remain. The protection is to limit the input length, write the regex so it's unambiguous, and never run a user-supplied regex.
74
People say reflection is slow. How do MethodHandle and VarHandle solve this problem?
Method.invoke does checks and wraps the arguments in an array on every call. If a MethodHandle is looked up once and stored in a static final field, the JIT can inline it down to the level of an ordinary call. VarHandle gives atomic access to fields with memory ordering.
75
get(id) on a Map<Long, User> always returns null, but the entry is definitely in the map. What wrapper-type and equals trap could this be?
The parameter of Map.get is Object, not generic. An int id is silently boxed to Integer, and Integer.equals(Long) is always false, even when the values are equal. The compiler gives no error; only the IDE or Error Prone warns.
76
How do you store an enum in the database: ordinal, name, or a separate code?
ordinal is risky: if the enum order changes, all the old rows get a different meaning. name is readable, but renaming a constant requires a migration. In long-lived systems, a separate stable code plus a converter is the most reliable.
77
The legacy code has a static final SimpleDateFormat, and prod occasionally shows wrong dates. What's the cause, and how do you migrate from java.util.Date to java.time?
SimpleDateFormat is not thread-safe: it has a single shared Calendar inside, and parallel parse/format calls corrupt each other's state, giving a wrong date or a random NumberFormatException. DateTimeFormatter is immutable and thread-safe; I start the migration at the boundaries: JDBC, JSON, external APIs.
78
What's the difference between Collections.unmodifiableList(), List.copyOf() and List.of(), and when do you make a defensive copy?
unmodifiableList is a read-only "window" onto the original list: if the original changes, it changes too. List.copyOf and List.of create a truly immutable copy and don't accept null. You should copy a collection that comes in from outside and one that you hand out.
79
Why does list.remove(1) on a List<Integer> remove the element at index 1 and not the number 1? What traps are there in overload resolution, and how do you avoid them in an API?
The compiler picks an overload in phases: first without boxing and varargs, then with boxing, and last with varargs. remove(int) matches already in the first phase, so remove(Object) never gets its turn. That's why, in an API, it's better to give differently-meaning overloads different names.
80
If identical Strings take up a large part of memory in a heap dump, what do you do?
First find the source (JSON parsing, codes coming from the DB, logs). Then choose: your own canonical cache or intern(), G1's String deduplication, or using an enum/ID instead of a String. Java 9+ compact strings already store Latin-1 text twice as compactly.
81
Is it worth moving a large monolith to JPMS (module-info.java)? What criteria do you decide by?
JPMS gives strong encapsulation and explicit dependencies, but in a stack that relies on reflection, like Spring/Hibernate, opens and split-package problems take a lot of work. The benefit is often bigger at the library and platform level than for an application.
82
How do you plan moving 40 services running on Java 8 to Java 21?
First an inventory (jdeps, library versions), then get the build green on the new JDK, then swap the runtime, and finally adopt the new language features. The biggest obstacles: javax to jakarta, strong encapsulation, removed APIs, and outdated libraries.
83
How do you preserve binary and source compatibility when you change the API of a library that other teams use?
Source compatibility means the client code is recompiled; binary compatibility means an old compiled JAR works with the new library. Many changes are safe for one and not the other. You need rules, automated checks (japicmp, revapi) and a deprecation policy.
84
How do you choose between building the domain model with a sealed interface plus records and a classic polymorphic hierarchy?
Sealed + records are good when the set of types is closed and operations are many and often added: a switch gets an exhaustiveness check. Classic polymorphism fits when types keep getting added and the operations are stable. These are the two sides of the "expression problem".
85
Does returning errors with a Result/Either type instead of exceptions pay off in Java?
For expected business outcomes (validation, "not found", rejected), a sealed Result type gives a clearer contract and makes the compiler force you to handle every case. For infrastructure errors (DB, network), exceptions are better. Turning the whole codebase into Either usually does harm.
86
How do you build a strategy for systematically reducing NullPointerExceptions in a large codebase?
Optional alone isn't the answer. You need an agreed default ("everything is non-null, and if something can be null, it's marked"), annotations like JSpecify, NullAway/Error Prone to check them at build time, and explicit validation at the boundaries (DTOs, the DB, external APIs).
87
What problems come up when moving a reflection-heavy application to a GraalVM native image, and how does that affect the architecture?
Native image works on a "closed world" assumption: reflection, dynamic proxies, resources and class loading that aren't visible at build time don't work at runtime. You have to declare them with metadata or move to AOT code generation. In return, startup is in milliseconds and memory use is low.
88
If an "immutable" record contains a List or a mutable object, how do you get deep immutability, and what does it cost?
A record only makes the references final, which is shallow immutability. Deep immutability needs immutable types or defensive copies at every layer. The price is copying and GC pressure; for large structures that change often, what's left is persistent collections, or "immutable outside, builder inside".
89
What problems appear when custom annotations and AOP "magic" multiply in a team, and how do you set the boundary?
An annotation hides behavior: when you read the code, you can't see what will run, ordering and self-invocation bugs appear, and debugging and testing get harder. I keep annotations for cross-cutting, uniform and rarely changing work; business logic stays in explicit code.
90
What risks does using a record as a public API across many services or a library boundary create from an evolution standpoint?
Adding a component to a record changes the canonical constructor signature and equals/hashCode/toString, which breaks binary and source compatibility. If it's used at a boundary, you need to keep the old constructor as an extra constructor, use factory methods, or version at the serialization level.
91
What breaks when a new value is added to an enum passed between services, and how do you design for it?
A consumer that doesn't know the new value yet either fails in deserialization or lands in an unexpected state in an exhaustive switch. Since producers and consumers are deployed at different times, you need tolerance for an "unknown" value, to update consumers first, and to version the contract.
92
What is invokedynamic, and why do lambdas, String concatenation and record methods run through it?
invokedynamic is a bytecode instruction whose call target is linked on first execution through a bootstrap method. That lets the JDK move the strategy from the compiler to the runtime: the lambda class, String concat and the record equals/hashCode can get faster on a newer JDK without recompiling.
93
A new JDK comes out every 6 months, and an LTS every 2 years. How do you set the policy for choosing and updating the JDK version and distribution in an organization?
Production runs only LTS (17, 21, 25) and one or two agreed distributions (Temurin, Corretto, Zulu or Oracle, depending on license and support period). Quarterly security updates roll out automatically, and the move to the next LTS is planned within 6-12 months of its release.
94
After every redeploy Metaspace grows, and eventually we get OutOfMemoryError: Metaspace. How do you find the cause?
It's usually a classloader leak: someone (a ThreadLocal, a running thread, a JDBC driver registration, a static cache) holds a reference to the old application's ClassLoader, so all its classes can't be unloaded. In a heap dump you need to find the path from the old loader to a GC root.
95
If your library has to support Java 11 and Java 21 users at the same time, how do you set that up?
The main code is built with --release 11; for the places that need newer APIs, use a multi-release JAR (META-INF/versions/21/) or an optional implementation detected at runtime. Testing on every supported JDK in CI is mandatory.
96
The team wants to use preview features (--enable-preview) in production code. How do you decide?
Usually no. A preview API can change or be removed entirely in the next release (String templates were a preview in Java 21-22 and were removed in 23), and the bytecode only works on exactly that JDK version. Allow it for experiments, internal tools and prototypes; for production, wait for it to become final.
97
In an organization with many teams, how do you systematically prevent mistakes with equals/hashCode, null, mutable statics and the like without relying on code review?
Automate the rules: compiler warnings (-Xlint -Werror), Error Prone/NullAway, ArchUnit, SpotBugs, EqualsVerifier tests. Turn them on at the platform level (a shared build plugin), strict for new code and phased in with a baseline for old code.
98
What unexpected problems can the fact that the default charset became UTF-8 in Java 18 (JEP 400) cause when upgrading a large system?
Every FileReader, new String(bytes) and getBytes() with no charset specified now uses UTF-8 and not the OS setting. Files on Windows or on servers with an old Linux locale, exchanges with legacy systems, and some tests give different results. Console output depends on a separate setting.
99
Why is it dangerous to synchronize on, or use == with, value-based classes like Integer or LocalDate, and how does Valhalla relate to this?
The identity of value-based classes isn't guaranteed: the same value may or may not be one object, so tying a lock or == to them gives random behavior. In future Valhalla value classes there will be no identity at all, and that kind of code will stop working.
100
Can an attacker slow a service down by sending keys with the same hashCode (hash flooding)? How is Java protected against it?
Yes: HTTP parameters or JSON keys end up in a HashMap, and since String.hashCode can be computed ahead of time, it's easy to build colliding keys. Since Java 8, a colliding bucket turns into a tree (O(log n)), but that only works fully for Comparable keys. Limiting the input size is the main defense.
Sign up — studied questions get marked and your progress is saved.