Primitives and references
TrapA local int sits in the stack frame. An int field sits inside its object on the heap.
b = a copies the reference, not the object.== compares references. equals() compares content, and equal objects must return the same hashCode().javac, compiles hot methods with the JIT, and frees unreachable objects with garbage collection.TrapA local int sits in the stack frame. An int field sits inside its object on the heap.
intInteger n = 100;a == ba.equals(b)TipString literals share one pooled object. new String always makes another.
Trap== on Integer only seems to work from -128 to 127, the cached range. Unboxing null throws Null.
new StringBuilder()new StringBuffer()String is immutableThe pool can share it, its hash never changes, and threads need no lock.Trap+= in a loop copies the text into a new String every time.
privateprotectedpublicstatic int count;super(name);super.save();TipA top-level class can only be public or package-private.
TrapA static method has no this, so it can't use instance fields directly.
Asked in interviews
AskedWhat are the four pillars of OOP?@Override. The object's class picks at runtime.TrapA different return type alone isn't an overload. Static, private and final methods can't be overridden.
final int MAX = 100;finalize()Deprecated. Use try-with-resources or Cleaner.Tipfinally runs after try and catch, whether or not something threw.
TrapA final reference isn't an immutable object. A final List can't point to another list, but add still works.
interface Flyableimplements A, Bprivate Engine e;TipPrefer composition. A change in a parent can break every subclass.
TrapAn interface holds no instance state, only public static final constants. default methods add behaviour without it.
ArrayList, duplicates allowed.HashSet, O(1) on average.TreeSet, O(log n).ArrayList is O(1), LinkedList is O(n).LinkedList is O(1), but ArrayDeque is often faster.TipMap doesn't extend Collection. The framework has two separate roots.
TrapInserting in the middle of a LinkedList is still O(n), unless an iterator already points there.
hash & (capacity - 1)0.75, it doubles and rehashes.TipA bucket only becomes a tree in a table of 64 or more. A smaller table resizes instead.
TrapOverride equals() without hashCode(), and a lookup with an equal key can return null.
Hashtable locks every method.ConcurrentHashMap . Reads take no lock.TipHashMap allows one null key. Hashtable and Concurrent reject null.
TrapCheck-then-put isn't atomic, even on a synchronized map. Use computeIfAbsent or merge.
compareTo(T other)Comparator.comparing(E::name) iter.remove()CopyOnWriteArrayList map.merge(w, 1, Integer::sum)List.of(1, 2)TipKeep natural order consistent with equals(). A TreeSet treats a compare result of 0 as a duplicate.
TrapAdding to an ArrayList in a loop throws Concurrent. The check is best-effort.
Trapcatch (Exception e) never catches an Error, and a normal application shouldn't try.
throw new E("x");throws IOExceptioncatch (A | B e)TrapA catch for a subclass after its superclass is a compile-time error. Order them from specific to general.
try (var r = open())close() failuree.getSuppressed() TipA resource implements AutoCloseable. Several close in reverse order.
TrapA throw or return in finally replaces the exception from try, and nothing records the lost one.
new Thread(r).start(); TipImplement Runnable, so your class can still extend another.
Traprun() executes on the current thread, so nothing new starts. A second start() throws Illegal.
synchronized (o) { }lock.tryLock()volatile boolean done;TipRelease a ReentrantLock in finally. AtomicInteger avoids locks for one counter.
Trapcount++ is a read, an add and a write. volatile doesn't make it atomic, so threads still lose updates.
obj.wait();Thread.sleep(1000); TrapA spurious wakeup needs no notify, so call wait() in a while loop that rechecks the condition.
Executors.newFixedThreadPool(4) Executors.newVirtualThreadPerTaskExecutor() Tipsubmit() returns a Future. Without shutdown(), the pool's threads keep the JVM running.
TrapVirtual threads are cheaper, not faster, so they help waiting work, not CPU work. Never pool them.
new CountDownLatch(3) new CyclicBarrier(4) RecursiveTask<T> TipFork/join uses work stealing. An idle worker takes tasks from a busy worker's queue.
TrapIf one thread at a barrier is interrupted or times out, the others get Broken.
TipSince Java 11, Oracle ships no separate JRE. jlink builds a trimmed runtime.
TipDeep recursion throws Stack. A full heap throws Out.
TrapHotSpot keeps static variables on the heap with the Class object, not in Metaspace.
-XX:+UseG1GC-XX:+UseParallelGC -XX:+UseZGCTipMost objects die young, so GC collects the young generation often. Java 14 removed CMS.
-XX:+HeapDumpOnOutOfMemoryError new SoftReference<>(v) new WeakReference<>(v) TipA phantom reference's get() always returns null, so it only schedules cleanup.
TrapRaise -Xmx only if the data really needs the space. If it's a leak, fix the reference.
-XX:StartFlightRecording C1 first, then C2 for the hottest code.TipMeasure before you optimize. Benchmarks need a warm-up, because the JIT compiles hot code after it runs.
x -> x * 2String::toUpperCase Optional.ofNullable(v) TipA functional interface has one abstract method, so a lambda can implement it.
TrapIntermediate steps do nothing until the terminal one runs, and a stream can be used only once.
record P(int x) {}TipErasure rules out List<int>, new T() and instanceof List<String>.
TrapRecords are only shallowly immutable. Store a list field with List.copyOf.
var n = 10;case SAT -> "Off";o instanceof Point psealed class A permits BAsked in interviews
AskedWhat are the key features added in Java since Java 8?exports com.app.api;@Retention(RUNTIME)method.invoke(obj) TipA package a module doesn't export stays hidden, even its public classes.
TrapSince Java 17, set throws Inaccessible where a module doesn't open the package.
InputStreamReaderSelectorTipThe default charset is UTF-8 since Java 18.
TrapReading an image through a Reader corrupts it, because it treats the bytes as text.
transientserialVersionUID = 1LTipA version mismatch throws Invalid.
TrapNever deserialize untrusted data. The Java documentation calls it inherently dangerous.
ds.getConnection() TipUse try-with-resources, because close() returns the connection to the pool.
TrapDriver opens a new physical connection every time.
ps.setString(1, name);setAutoCommit(false) TipIn Spring, @Transactional handles the commit and rollback.
TrapA Statement built by joining strings lets input like ' OR '1'='1 change the query.
@SpringBootApplication @ConditionalOnMissingBean TipStarters pull in tested libraries. An embedded server runs the app with java -jar.
@Repository@Controller@RestControllerTipAll are specializations of @Component. @Repository also translates data exceptions.
final.singleton, the default.prototype, with no destruction callbacks.TrapA singleton that needs a request-scoped bean needs a scoped proxy. Without one, startup fails.
findByLastName(name) .hasRole("ADMIN") TipSpring Security runs as a chain of servlet filters in front of your controllers.
TrapLoading a list can run one more query per entity to fetch a lazy relation, the N+1 select problem.
@Around("@annotation(Loggable)")TrapOnly calls through the proxy get advice. A call on this skips the aspect, and private methods never get it.
enum E { INSTANCE }Factory.create("dog") TrapDouble-checked locking needs a volatile field, or another thread can see a half-built object.
observer.update(msg) cart.setStrategy(s) TrapObservers that never detach leak memory, and one slow observer delays the rest.
@Test@SpringBootTestTipA common stack is JUnit, Mockito and AssertJ. JUnit 6 is the current generation.
when(s.pay()).thenReturn(true); verify(s).pay(); TrapA test that mocks everything only checks that the code calls its mocks.
Asked in interviews
AskedWhat is mocking and why is it useful?Nothing matches. Try a shorter word, or clear the search.
With Pro, you can:
Already have Pro? Sign in