skip to content

Java Standard Library / APIs

The JDK library surface an interviewee is expected to know: date and time, precise arithmetic, wrappers, regex, reflection and method handles, annotations, serialization, the module system, and the small utility classes. Interviewers dip in here to check you use the standard library rather than reinvent it.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

232 · 9 sections

What is the spring-forward gap in DST, and what happens in java.time when you create a ZonedDateTime at a local time that does not exist?

level: juniorimportance: must knowfreq 62%
basics
~20 s

In spring, clocks jump forward (e.g. 02:00 to 03:00), so an hour of local time never happens. If you ask java.time for a ZonedDateTime in that missing hour, it pushes the time forward by the gap (the missing hour) instead of failing.

open as a page

What is the difference between Duration and Period in java.time, and when would you use each?

level: juniorimportance: must knowfreq 78%
basics
~10 s

Duration measures an exact amount of time in seconds and nanoseconds (good for hours/minutes/seconds). Period measures an amount of dates in years, months and days. Use Duration for machine time, Period for calendar time.

open as a page

Why is DateTimeFormatter preferred over SimpleDateFormat, and what makes it safe to share across threads?

level: juniorimportance: must knowfreq 70%
basics
~10 s

DateTimeFormatter is immutable and thread-safe, so one instance can be shared everywhere. The old SimpleDateFormat keeps mutable state during parsing, so sharing it between threads corrupts results.

open as a page

Why is java.util.Date discouraged in modern Java code, and what do you use instead?

level: juniorimportance: must knowfreq 70%
basics
~10 s

java.util.Date is mutable, not thread-safe, mixes a date and a time together, and has confusing deprecated methods. Use the java.time package (LocalDate, LocalDateTime, Instant) instead, which is clearer and immutable.

open as a page

What are LocalDate, LocalTime, and LocalDateTime, and when would you use each?

level: juniorimportance: must knowfreq 80%
basics
~10 s

LocalDate is a date only (year-month-day), LocalTime is a time only (hour-minute-second), and LocalDateTime is both together. None of them carries a time zone. Use whichever matches the data you have.

open as a page

What is the difference between BigDecimal.equals() and BigDecimal.compareTo() when comparing two values, and which should you use to test numeric equality?

level: juniorimportance: must knowfreq 70%
basics
~20 s

equals() also checks scale, so 2.0 is not equal to 2.00. compareTo() ignores scale and compares the actual number, so 2.0 compareTo 2.00 returns 0. To check if two numbers are numerically equal, use compareTo() == 0.

open as a page

Why should you use BigDecimal instead of double or float for monetary values?

level: juniorimportance: must knowfreq 78%
basics
~10 s

double and float store numbers in binary, so many decimals like 0.1 can't be represented exactly and small errors creep in. BigDecimal stores decimals exactly, so it's the right choice for money.

open as a page

What is BigInteger in Java, when would you use it instead of long, and what does it mean that it is immutable?

level: juniorimportance: must knowfreq 62%
basics
~10 s

BigInteger holds whole numbers of any size, so it never overflows like long does. It is immutable: every operation returns a new BigInteger instead of changing the original.

open as a page

What are the most common methods on java.lang.Math, and what do they compute (abs, pow, sqrt, max/min, log/exp, trig)?

level: juniorimportance: must knowfreq 55%
basics
~10 s

Math is a utility class of static math functions: abs (magnitude), pow (x to a power), sqrt (square root), max/min (larger/smaller of two), log/exp (natural log and e^x), and sin/cos/tan (trigonometry, in radians).

open as a page

How do you format a number for display in Java using NumberFormat, and why is the Locale important?

level: juniorimportance: must knowfreq 62%
basics
~20 s

Use NumberFormat factory methods like NumberFormat.getInstance(locale), then call format(value). The Locale decides things like whether the decimal point is a dot or a comma and which grouping separator is used, so the output looks right for that region.

open as a page

Why do wrapper classes like Integer and Double exist in Java when there are already primitive types like int and double?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Primitives like int are not objects, so they can't be stored in collections (e.g. List) or used as generic types, and can't be null. Wrapper classes turn a primitive into an object so it can.

open as a page

What is the difference between Integer.parseInt("42") and Integer.valueOf("42")?

level: middleimportance: must knowfreq 75%
basics
~10 s

parseInt returns a primitive int. valueOf returns an Integer object (a wrapper). Both parse the text the same way, but you get different return types.

open as a page

What hidden costs and pitfalls does autoboxing of wrapper classes introduce, and how would you avoid them in performance-sensitive or correctness-sensitive code?

level: seniorimportance: must knowfreq 60%
basics
~20 s

Autoboxing silently turns primitives into objects, which can (1) throw NullPointerException when a null wrapper is unboxed, (2) allocate many objects in loops hurting performance, and (3) make == compare object identity instead of value. Use primitives where possible and equals() to compare.

open as a page

Why is new Integer(5) deprecated, and what should you use instead?

level: middleimportance: should knowfreq 55%
basics
~10 s

new Integer(5) always creates a brand-new object and wastes memory. Use Integer.valueOf(5) (or just autoboxing, Integer x = 5;) instead, which can reuse cached objects.

open as a page

What static utility methods and constants do wrapper classes provide, and why use Integer.compare(a, b) instead of writing your own comparison?

level: seniorimportance: should knowfreq 50%
basics
~10 s

Wrappers offer static helpers (parseInt, valueOf, toString, compare, min/max, toBinaryString) and constants like Integer.MIN_VALUE and Integer.MAX_VALUE. Integer.compare(a, b) safely returns negative/zero/positive without the overflow bug of a - b.

open as a page

What do the ^ and $ anchors match in a Java regular expression, and why are they called zero-width?

level: juniorimportance: must knowfreq 72%
basics
~10 s

^ matches the start of the text and $ matches the end. They are zero-width because they match a position, not an actual character, so they consume no part of the string.

open as a page

What is a character class in a Java regular expression, and what does [abc] match?

level: juniorimportance: must knowfreq 78%
basics
~10 s

A character class is a set in square brackets that matches exactly ONE character from that set. [abc] matches a single 'a', 'b', or 'c' (not the word "abc").

open as a page

How do you make a Java regex match case-insensitively, and what is the difference between the CASE_INSENSITIVE flag and the (?i) inline flag?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Pass Pattern.CASE_INSENSITIVE when compiling the pattern, or put (?i) at the start of the pattern string. Both make letters match regardless of upper or lower case, so "abc" matches "ABC".

open as a page

What is a capturing group in a Java regular expression, and how do you retrieve what it matched?

level: juniorimportance: must knowfreq 78%
basics
~20 s

A capturing group is the part of a pattern wrapped in parentheses (). After a successful match you read what it captured with matcher.group(n), where n is the group's number. group(0) is the whole match.

open as a page

What is a lookaround assertion in a Java regular expression, and what does "zero-width" mean?

level: juniorimportance: must knowfreq 60%
basics
~20 s

A lookaround is a regex condition that checks whether text around the current spot matches a pattern, without including that text in the match. "Zero-width" means it consumes no characters - the position does not move.

open as a page

What are the three ways to obtain a java.lang.Class object in Java, and how do they differ?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Use the .class literal (e.g. String.class) when you know the type at compile time, obj.getClass() to get the real runtime type of an existing object, and Class.forName("name") to look up a class by its String name at runtime.

open as a page

Why does an annotation need RUNTIME retention to be readable via reflection, and what happens if it doesn't have it?

level: juniorimportance: must knowfreq 70%
basics
~10 s

Reflection can only see annotations marked to survive into the running program. If an annotation isn't kept at runtime, reflection methods like getAnnotation return nothing, even though the annotation was in the source.

open as a page

How do you call a method on an object dynamically at runtime using reflection, and what does Method.invoke return?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Get a Method object from the class (e.g. clazz.getMethod("name", paramTypes)), then call method.invoke(target, args). The first argument is the object to call it on (null for static methods); it returns the method's result as an Object.

open as a page

What is a dynamic proxy in Java, and how do you create one with java.lang.reflect.Proxy?

level: middleimportance: must knowfreq 55%
basics
~20 s

A dynamic proxy is a class Java builds at runtime that implements one or more interfaces. You create it with Proxy.newProxyInstance, passing a class loader, the interfaces, and an InvocationHandler whose invoke method runs for every call.

open as a page

When does setAccessible(true) throw InaccessibleObjectException, and how do you fix it?

level: middleimportance: must knowfreq 60%
basics
~20 s

Since Java 9, setAccessible(true) throws InaccessibleObjectException when the target type lives in a module whose package isn't opened for deep reflection. You fix it by opening that package — via an 'opens' directive in module-info or an --add-opens flag at launch.

open as a page

What is annotation processing (APT) in Java, and what can and cannot a processor do during compilation?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Annotation processing is a hook in the Java compiler that runs your code during compilation. It reads annotations in the source, and can generate brand-new source files. It cannot change existing files.

open as a page

What does the @Override annotation do, and why should you use it even though it's optional?

level: juniorimportance: must knowfreq 78%
basics
~20 s

@Override tells the compiler a method is meant to replace one from a parent class or interface. If it doesn't actually match a parent method, you get a compile error. It catches typos and wrong signatures early.

open as a page

How do you declare a custom annotation in Java, and what makes its syntax different from a regular interface?

level: juniorimportance: must knowfreq 70%
basics
~10 s

You declare a custom annotation with the @interface keyword instead of interface. Inside, each method (with no body) becomes a configurable element you can set when you use the annotation, like @MyAnno(name = "x").

open as a page

Walk through how you implement a processor with AbstractProcessor: which annotations/methods configure it, and how process() and RoundEnvironment drive the work?

level: middleimportance: must knowfreq 58%
basics
~10 s

Extend AbstractProcessor, declare which annotations you handle with @SupportedAnnotationTypes and the Java version with @SupportedSourceVersion. Override process(), where RoundEnvironment.getElementsAnnotatedWith() gives you the annotated code to read and generate from.

open as a page

What types are allowed for annotation elements, and what restrictions apply to them?

level: middleimportance: must knowfreq 60%
basics
~10 s

An element's type can be a primitive, String, Class, an enum, another annotation, or a single-dimension array of those. You can't use arbitrary objects, collections like List, or nested arrays.

open as a page

Why does an Externalizable class require a public no-arg constructor, and what happens at deserialization?

level: middleimportance: must knowfreq 50%
basics
~10 s

When restoring an Externalizable object, Java first creates an empty instance by calling its public no-arg constructor, then calls readExternal to fill in the data. Without that constructor, deserialization fails with InvalidClassException.

open as a page

If a Serializable class extends a non-serializable superclass, what extra requirement must the superclass meet, and why?

level: middleimportance: must knowfreq 55%
basics
~20 s

The non-serializable parent must have an accessible no-argument constructor. During deserialization Java does not read the parent's fields from the stream; instead it calls that no-arg constructor to set up the parent part of the object.

open as a page

What is Externalizable in Java, and how does it differ from Serializable?

level: juniorimportance: should knowfreq 45%
basics
~10 s

Both let an object be saved as bytes and restored. Serializable saves fields automatically; Externalizable makes you write the saving and loading code yourself in writeExternal and readExternal, giving full control of the format.

open as a page

What changes if you make the previously non-serializable superclass implement Serializable too?

level: juniorimportance: should knowfreq 30%
basics
~20 s

Once the parent also implements Serializable, its fields get written to and restored from the stream like the child's. Java no longer needs to call the parent's no-arg constructor, so that constructor is no longer required and the parent's constructors are skipped during deserialization.

open as a page

How do you correctly implement writeExternal and readExternal, and what are the common pitfalls?

level: middleimportance: should knowfreq 40%
basics
~20 s

In writeExternal you write each value you want to keep; in readExternal you read them back in exactly the same order and assign them to fields. The biggest pitfall is reading in a different order or count than you wrote.

open as a page

What do the `requires` and `exports` directives do in a `module-info.java`, and why are they fundamental to the Java module system?

level: juniorimportance: must knowfreq 72%
basics
~20 s

requires says your module depends on another module so you can use its code. exports makes one of your packages visible to other modules. Without an export, a package stays internal and other modules cannot use it, even if it is public.

open as a page

What is the difference between the classpath and the module path, and how does the same plain JAR behave on each?

level: juniorimportance: must knowfreq 50%
basics
~20 s

The classpath (-cp) is the old flat list of JARs where everything is visible to everything; code there forms the unnamed module. The module path (-p) is the JPMS list where each JAR is a module. A plain JAR is part of the unnamed module on the classpath, but an automatic module on the module path.

open as a page

What is the difference between the classpath and the module path in Java, and how does each find and load classes?

level: juniorimportance: must knowfreq 60%
basics
~20 s

The classpath is a flat list of JARs/folders the JVM scans to find classes, with no boundaries between them. The module path holds modules that declare their names and dependencies in module-info, so the JVM resolves and enforces them.

open as a page

What is 'reliable configuration' in JPMS, and which classpath failures does it eliminate?

level: middleimportance: must knowfreq 60%
basics
~20 s

Reliable configuration means the module system checks all dependencies up front. Each module declares what it needs with 'requires', so missing or duplicate modules are caught when the program starts instead of failing later with a runtime error.

open as a page

What is 'strong encapsulation' in JPMS, and how does it change the meaning of 'public'?

level: middleimportance: must knowfreq 62%
basics
~20 s

Strong encapsulation means only the packages a module explicitly exports are usable by other modules. A public class in a non-exported package is hidden, so 'public' no longer means 'visible to everyone' — it means visible only within the module unless the package is exported.

open as a page

What does Objects.equals(a, b) do, and why prefer it over a.equals(b)?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Objects.equals(a, b) compares two values for equality but won't crash if either is null. It returns true if both are null, false if only one is, and otherwise calls a.equals(b). Plain a.equals(b) throws if a is null.

open as a page

What is Objects.requireNonNull and when should you use it for fail-fast null checks?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Objects.requireNonNull(x) throws a NullPointerException immediately if x is null, otherwise returns x. You use it to validate arguments early - usually in constructors - so a bad null fails right away with a clear message instead of later somewhere confusing.

open as a page

How do you implement hashCode() using Objects.hash(...), and what are its caveats?

level: middleimportance: must knowfreq 68%
basics
~10 s

Objects.hash(field1, field2, ...) takes the fields that define equality and combines them into one int hash code. You return it from hashCode(): return Objects.hash(name, email);. It handles nulls automatically.

open as a page

How do Objects.requireNonNullElse and Objects.toString(obj, default) provide null-safe defaults, and how do they differ from requireNonNull?

level: middleimportance: should knowfreq 50%
basics
~20 s

requireNonNullElse(x, fallback) returns x if it's not null, otherwise the fallback - so you get a default instead of an exception. Objects.toString(obj, nullDefault) returns obj.toString() if obj isn't null, otherwise the given default string. Both substitute a value for null instead of throwing like requireNonNull does.

open as a page

Given nullable values, how do you decide between Objects.requireNonNull, requireNonNullElse, Objects.equals/hash, and Optional? Discuss the design trade-offs.

level: seniorimportance: should knowfreq 42%
basics
~20 s

Use requireNonNull when null means a bug and you want to fail fast; use requireNonNullElse when null is fine and you just want a default; use Objects.equals/hash to safely compare and hash nullable fields; use Optional mainly for return values that may be absent, not for parameters or fields.

open as a page