- What primitive types are there in Java?
- What is autoboxing in Java and what are the rules for wrapping primitive types?
- In what order does Java choose an overloaded method for a primitive argument?
- What is an array in Java?
- What sorting algorithms are used for arrays in Java?
- What is the result of
int[] array = {8, -3, 10, 4}; int result = Arrays.binarySearch(array, 8);? - What is the result of
int result = Arrays.binarySearch([-3, 4, 8, 10], 9)? - What modifiers exist?
- What is the difference between
intrinsicandnativemethods? - What does the keyword
varmean? - What does the keyword
finalmean? - What default values do variables have?
- What do you know about
main()function? - What logical operations and operators do you know?
- What is the ternary selection operator?
- What bitwise operations do you know?
- Are parameters passed by value or by reference?
- Where and why is the
abstractmodifier used? - Define "interface". What default modifiers do interface fields and methods have?
- How does an abstract class differ from an interface? When should you use each one?
- Why do some interfaces have no methods?
- Why can't you declare an interface method with the
finalmodifier? - Which has a higher level of abstraction: class, abstract class, or interface?
- Can an object access a class member declared as
private? If so, how? - What is the order of constructor and initialization block calls, considering class hierarchy?
- Why do we need initialization blocks and what types are there?
- To which Java constructs is the
staticmodifier applicable? - Why are static initialization blocks used in Java?
- What happens if an exception occurs in an initialization block?
- What exception is thrown if an error occurs in a class initialization block?
- Can a static method be overridden or overloaded?
- Can non-static methods overload static methods?
- Can you narrow access level/return type when overriding a method?
- Is it possible to change access modifier, return type, argument type/count/names/order, or elements of the
throwssection when overriding a method? - How do you access an overridden method of a parent class?
- Can a method be both abstract and static?
- What is the difference between instance and static class members?
- Where is initialization of static/non-static fields allowed?
- What are the types of classes in Java?
- Tell about nested classes. In what cases are they used?
- What is a "static class"?
- What are particularities of static and inner nested classes? What is the difference between them?
- What is a "local class"? What are its features?
- What are "anonymous classes"? Where are they used?
- How can a nested class access a field of the outer class?
- Why is the
assertoperator used? - What are Heap and Stack memory in Java? What is the difference?
- Is it true that primitive data types are always stored on the stack, and objects on the heap?
- How are variables passed to methods: by value or by reference?
- What is the "string pool"?
- What is
finalize()? Why is it needed? - What happens if
finalize()takes a long time or throws an exception for the garbage collector? - How do
final,finally, andfinalize()differ? - Tell about type casting. What are widening and narrowing?
- When can a
ClassCastExceptionbe thrown? - What are the features of the
Stringclass? - Why is
Stringimmutable and final? - Why is
char[]preferred overStringfor storing a password? - Why is
Stringa popular key inHashMapin Java? - What does the
intern()method do in theStringclass? - Can you use strings in a
switchstatement? - What is the main difference between
String,StringBuffer, andStringBuilder? - What is the
Objectclass? What methods does it have? - Define "constructor"
- What is a "default constructor"?
- What is the difference between a default constructor, copy constructor, and parameterized constructor?
- Where and how can you use a private constructor?
- Tell about classloaders and dynamic class loading
- What is Reflection?
- Why do we need
equals()? How does it differ from==? - If you want to override
equals(), what conditions must be met? - What properties does the equivalence relation of
equals()generate? - Rules for overriding
Object.equals() - If
equals()is overridden, are there other methods you should override? - What happens if you override
equals()but nothashCode()? What problems can arise? - How are
hashCode()andequals()implemented in theObjectclass? - Why is the
hashCode()method needed? - What are the rules for overriding
Object.hashCode()? - Are there recommendations on which fields to use in
hashCode()? - Can different objects have the same
hashCode()? - If
Point{int x, y;}implementsequals(Object that) {return this.x == that.x && this.y == that.y;}, butint hashCode() {return x;}, will such points be properly stored/retrieved from aHashSet? - Can
ref0 != ref1butref0.equals(ref1) == true? - Can two references to the same object (
ref0 == ref1) haveref0.equals(ref1) == false? - Can you implement
equals(Object that) {return this.hashCode() == that.hashCode();}? - In
equals(), what's the difference betweenthis.getClass() == that.getClass()andthat instanceof MyClass? - Can you implement
equals()forMyClassaspublic boolean equals(MyClass that) {return this == that;}? - For the class
Point{int x, y;}, why is31 * x + ypreferable as a hash code thanx + y? - Tell about object cloning
- What's the difference between shallow and deep cloning?
- Which cloning method is preferable?
- Why is
clone()declared inObjectand not in theCloneableinterface? - Describe the exception hierarchy
- What types of exceptions are there in Java and how do they differ?
- What are checked and unchecked exceptions?
- What operator allows you to throw an exception?
- What does the
throwskeyword mean? - How do you write your own (user-defined) exception?
- What unchecked exceptions exist?
- What does the
Errorclass represent? - What do you know about
OutOfMemoryError? - Describe how the
try-catch-finallyblock works - What is the try-with-resources mechanism?
- Is it possible to use
try-finallyblock (withoutcatch)? - Can one
catchblock catch several exceptions? - Does the
finallyblock always execute? - Are there situations when the
finallyblock will not be executed? - Can the
main()method throw an exception outwards and where will it be handled? - If a method might throw
IOExceptionandFileNotFoundException, in what order should catch blocks go? How many catch blocks will be executed? - What are generics?
- Describe the difference between
? extends ...and? super ...with generics - How is
java.lang.Comparabledifferent fromjava.util.Comparator?
"Void" type: void.
Boolean type:
| Type | Size | Default value | Min value | Max value |
|---|---|---|---|---|
| boolean | 1 bit | false | false | true |
Integer types:
| Type | Size | Default | Min value | Max value |
|---|---|---|---|---|
| byte | 8 bits | 0 | (-2^7) | (2^7-1) |
| short | 16 bits | 0 | (-2^{15}) | (2^{15}-1) |
| int | 32 bits | 0 | (-2^{31}) | (2^{31}-1) |
| long | 64 bits | 0L | (-2^{63}) | (2^{63}-1) |
Floating point numbers: e.g. float f = -45.05f;
| Type | Size | Default | Standard |
|---|---|---|---|
| float | 32 bits | 0.0f | IEEE 754, 32 bits |
| double | 64 bits | 0.0d | IEEE 754, 64 bits |
Characters: For storing literals, e.g. char c = 'A';
Autoboxing is the mechanism by which Java automatically wraps primitive types (byte, int, etc.) into their corresponding wrapper classes (Byte, Integer, and so on) without explicit use of the constructor.
Examples:
- Assigning a primitive to a wrapper variable (with
=), or passing a primitive as a parameter where a wrapper is required.
Autoboxing of primitive variables requires the type of the primitive and the wrapper to match exactly. For example, wrapping a byte in a Short without an explicit cast will result in a compilation error.
Autoboxing constants allows for more flexible type matches. The compiler can implicitly widen/narrow the primitive to match the wrapper's type as long as the cast is safe. However:
- You can only assign such a primitive to a wrapper with
=, not as a method parameter. - The type on the left must not "exceed"
Character, and the type on the right not "exceed"int. Some matchings work only in limited cases.
Another important feature: wrapper objects for integer values in the range [-128...127] are cached in the JVM. Thus, wrappers created by autoboxing of constants in that range will point to the same object.
Suppose you call myMethod(10), where 10 is an int. The choices are:
myMethod(int i)— method with exact type match (exact).myMethod(float i)— method with a "widened" primitive argument (widening). (For primitives:byte < short < int < long < float < double;char < int < long < float < double)myMethod(Integer i)— method with wrapper argument type (autoboxing).myMethod(int... i)— method with variadic parameter (varargs).
An array is a data structure containing elements of the same type. It’s like a numbered set of cells, each holding a value. Access is via its index. Indexing starts at 0; the last element index is length - 1.
Arrays inherit from java.lang.Object. Java supports N-dimensional arrays and the Arrays utility class for common operations.
Examples:
int[] myArray; // Java style, preferred
int myArray[]; // C++ style, also works
String[] array = (String[]) Array.newInstance(String.class, 3);
int[] myArray = new int[5]; // Array of 5 zeros
int[] myArray = {1, 2, 3}; // Array with 3 elements
myArray[2] // index-based access| Version | Array.sort(primitives) | Array.sort(objects) |
|---|---|---|
| Java ...-6 | Quicksort | MergeSort |
| Java 7-... | DualPivotQuicksort | TimSort |
The result is "undefined," since the array is not sorted. If you add Arrays.sort(array), the result is 2, because in the sorted array {-3, 4, 8, 10} the element 8 has index 2.
The result is -4. It's negative because the element is not present; the absolute value minus one is the index (plus one) where it would fit.
- abstract – declares an abstract method or class.
- default – (since Java 8) to declare default behavior in interfaces.
- final – means no further overriding.
- native – implemented in platform-native code (e.g. C++,
Object.hashCode). - static – static method or member.
- strictfp – restricts floating-point precision (IEEE 754).
- synchronized – for synchronization in methods/blocks.
- transient – fields marked aren't serialized/deserialized.
- volatile – disables optimization for variable, forcing all threads to see updates.
Access modifiers:
- private – visible only in the class.
- package-private (default) – visible within the package.
- protected – visible in the package and subclasses.
- public – visible everywhere.
Modifiers must be widened (e.g. private→protected→public) when overriding according to the Liskov Substitution Principle.
- native: Declared with the
nativemodifier; implemented in native code (e.g. C++), e.g.Object.hashCode. - intrinsic: Not marked native, but replaced at runtime with a platform-specific implementation, e.g.
String.equals; potentially much faster.
Since Java 9, HotSpot provides the @HotSpotIntrinsicCandidate annotation, showing the method may eventually become intrinsic.
The var keyword (since Java 10) allows for local variable type inference. The compiler infers the type from the initializing expression on the right.
Example:
var x = 100; // int
var y = "hello"; // String
var z = List.of(1); // List<Integer>Limitations:
- Works only for local variables (not fields, parameters, or return types).
- The type must be clear at compile time (cannot be
nullwithout context).
The final modifier can be applied to variables, methods, and classes.
- A final variable cannot be changed after being assigned.
- A final method cannot be overridden in subclasses.
- A final class cannot be subclassed.
- Local variables (inside methods/blocks): No default value! Must be explicitly assigned before use.
- Fields (class members):
- Objects:
null - Boolean:
false - Numeric types:
0,0.0, etc. - Char:
\u0000(null character)
- Objects:
The main method serves as the entry point for Java applications:
public static void main(String[] args)Characteristics:
- Must be
public,static,void, with a singleString[]parameter (name can be anything). - The JVM looks for this method to begin execution.
- You can have other overloaded
mainmethods, but only the exact signature above is used as an entry point.
Java supports:
- Logical AND:
&&(short-circuit),&(bitwise/logical, no short-circuit) - Logical OR:
||(short-circuit),|(bitwise/logical, no short-circuit) - Logical NOT:
! - XOR:
^(bitwise and logical) - Equality:
==,!= - Relational:
>,<,>=,<=
The ternary operator is a shortcut for conditional expressions:
[ \text{condition} ? \text{value if true} : \text{value if false} ]
Example:
int min = a < b ? a : b; // assigns the smaller of a and bFor integer types:
- AND:
& - OR:
| - XOR:
^ - NOT:
~(bit complement) - Left shift:
<< - Arithmetic right shift (with sign):
>> - Logical right shift (zero fill):
>>>
All parameters in Java are passed by value!
- For primitives: the actual value is copied to the method.
- For objects: the value of the reference (pointer) is copied (the reference itself is passed by value). The called method can change the object’s contents, but can't change what the caller reference points to.
- Abstract classes: Can't be instantiated directly; used as base types.
- Abstract methods: No implementation, must be overridden by subclasses.
Use the abstract modifier when you want to force subclasses to implement a method, or when the class itself is not meant to be instantiated.
An interface is a reference type, like a class, that can contain:
- Method signatures (abstract by default)
- Constants (public static final fields)
Modifiers:
- Fields:
public static finalby default - Methods:
public abstractby default
From Java 8, interfaces can also contain default methods (with implementation) and static methods.
Abstract class:
- Can have fields, methods (abstract and implemented), constructors.
- Can provide state (fields).
- Subclasses extend at most one abstract class (single inheritance).
Interface:
- Cannot have instance fields (except constants).
- Only method signatures by default (though Java 8+ allows static/default methods).
- Classes can implement multiple interfaces.
When to use:
- Use an interface when you want to specify a contract for unrelated classes or need multiple inheritance of behavior.
- Use an abstract class when you want to share code among closely related classes and provide base implementation or state.
These are marker interfaces (tag interfaces), used to mark a class as having a special property—e.g., Serializable, Cloneable. The presence of such an interface is detected via reflection or at runtime.
finalmeans "cannot be overridden."- All interface methods are implicitly abstract and must be implemented in subclasses; thus, they must be overridden, so declaring them
finalwould be a contradiction.
Interface is the most abstract, then abstract class, then concrete class.
No. Private members are only accessible within the same class. They are not visible outside the class, not even to subclasses or other instances.
Inside the same class, any method (static or instance) can access all private members of any instance of that class.
Initialization of an object follows this order:
- Static initializers in parent classes (top-down)
- Static initializers in the current class
- Instance initializers in parent classes (top-down)
- Parent constructor
- Instance initializers in current class
- Current class constructor
Initialization blocks allow you to run code during object/class initialization (not tied to any specific method). Types:
- Static blocks:
static { }Runs once when class is loaded. - Instance blocks:
{ }Runs every time when the object is created, before the constructor.
- Fields (static variables)
- Methods (static methods)
- Initialization blocks (
static { ... }) - Nested classes (
static class Inner { ... }) — note: only for inner static classes!
- To perform one-time initialization when the class loads, especially when initialization is complex or cannot be done via field assignment.
Example:
static {
// Code run ONCE at class load time
}- If an error or unchecked exception is thrown during static initialization, the JVM will prohibit the class from loading, and all further attempts to use the class result in a
NoClassDefFoundError.
- If a checked exception occurs: Compilation error! Only unchecked exceptions and errors can be thrown.
- If unchecked exception/error occurs: The JVM wraps the exception in an
ExceptionInInitializerError.
- Overridden: No; static methods are hidden, not overridden—method dispatch is based on reference type, not object type.
- Overloaded: Yes; static methods can be overloaded within the same class.
Yes. Overloading is only by signature, not by static-ness.
You can have:
static void foo() {}
void foo(int x) {}But overriding requires "static" or "non-static" to match.
- Access level: You can only widen (make less restrictive). For example:
protected→publicis allowed;public→protectedis not. - Return type: Can specify a more specific (covariant) return type of a subclass of the overridden method’s return type.
Is it possible to change access modifier, return type, argument type/count/names/order, or elements of the throws section when overriding a method?
- Access modifier: Can only widen access (see previous).
- Return type: Must match, or be covariant for object types.
- Argument type/count/order: Must be identical. If not, it becomes an overloaded method, not an override.
- Argument names: Can change; names don’t matter for override.
- Throws clause: You can only specify the same, or narrower exception types (checked) in the
throwsclause.
Use super:
super.methodName();This calls the parent class’s method from the child/overriding method.
No.
abstractmethods have no body and must be overridden/implemented in subclasses.staticmethods belong to the class, not instances—and cannot be abstract, as static methods cannot be overridden.
- Instance members: Belong to individual objects, require an object to access.
- Static members: Belong to the class as a whole, shared by all instances, can be accessed without creating an object.
- Static fields: Can be initialized at declaration, or within
staticinitialization blocks. - Non-static fields (instance fields): Can be initialized at declaration, in instance initializer blocks, or in constructors.
- Top-level (outer) classes
- Inner (nested non-static) classes
- Static nested classes
- Local classes (declared within a method/block)
- Anonymous classes (expression-defined, no name)
- Nested classes (inner, static, local, anonymous) are declared within another class.
- They are used for grouping logically related classes, increasing encapsulation, and can access outer class members depending on their kind.
In Java, the phrase "static class" means static nested class—a class declared as static inside another class.
- It can't access non-static members of the enclosing class directly.
- Declared as:
static class Helper { ... }-
Static nested class:
- Declared with
staticmodifier. - Can access only the
staticmembers of the outer class. - Exists without an instance of the outer class.
- Declared with
-
Inner class (non-static):
- Has a reference to an instance of the outer class.
- Can access all (including private) members of the outer class.
- Needs an object of the outer class to be instantiated.
A local class is a class defined within a method or a block.
- Its scope is limited to the method/block.
- Can access
finalor effectively final variables from its enclosing scope.
- Anonymous classes are unnamed classes declared and instantiated in a single expression.
- Used for concise implementation of interfaces/abstractions for single-use cases, typically as arguments to methods or when implementing event handlers/callbacks.
Example:
Runnable r = new Runnable() {
public void run() { /* code */ }
};- Inner (non-static) nested class: Can access all members (even private) of the outer class—
OuterClass.this.fieldName. - Static nested class: Can only access
staticfields of the outer class directly.
- Used for assertions—statement that a condition should always be true. If false, an
AssertionErroris thrown (only if assertions are enabled at runtime). - Typical for debugging, invariants, and development; not usually for production error handling.
Example:
assert x > 0 : "x must be positive";- Stack: Stores local variables and method call frames; memory is managed in LIFO order, is fast and thread-local.
- Heap: Stores objects and arrays; used for dynamic memory allocation, shared across threads, cleaned by garbage collection.
- Local variables of primitive types: Generally reside on the stack as part of the method frame.
- Objects: Always on the heap, references are passed via the stack.
- Primitive fields of objects: Stored as part of the object, thus in heap.
Already answered above: Always by value.
- Primitives: value is copied.
- Objects: reference is copied (so object can be mutated, but the reference itself cannot be changed by the method).
- The "string pool" is a special area of the heap where Java stores interned string literals.
- This enables reuse of immutable string objects and saves memory.
Example:
String a = "hello";
String b = "hello";
System.out.println(a == b); // trueBoth point to the same interned string.
finalize()is a method inObjectthat can be overridden to run cleanup code just before the object is garbage collected.- However: It’s deprecated and unreliable for managing resources—don’t depend on it.
- Long-running
finalize()can delay garbage collection and increase memory use (object can’t be reclaimed until it finishes). - If
finalize()throws an unhandled exception, it’s ignored, and finalization terminates—GC continues as usual.
- final: Modifier—applied to variables, methods, or classes.
- finally: Block in try-catch-finally—executes regardless of exception.
- finalize(): Method for cleanup before GC (deprecated/legacy).
- Widening (implicit cast): Conversion from a smaller to a larger type (e.g.
inttolong).- Safe, no data loss.
- Narrowing (explicit cast): Larger to smaller type (e.g.
longtoint).- Not always safe; may cause data loss; requires explicit cast.
Example:
int i = 5;
long l = i; // widening
long l2 = 10;
int i2 = (int) l2; // narrowing- When you try to cast an object’s reference to an incompatible type at runtime.
Example:
Object o = "string";
Integer i = (Integer) o; // Throws ClassCastException at runtime- Immutable (cannot be changed after creation).
- Has many useful methods for comparison, search, substring, case, etc.
- Supports Unicode.
- Implemented as
final. - Stores characters in a
char[]internally.
- For security (e.g. safe for keys in maps, parameters in networking).
- For thread safety.
- To allow sharing (string pool) and caching hash codes.
Stringis immutable; its contents can't be cleared from memory until GC runs, and may remain in memory as a pool.- With
char[], you can zero out the array after use, improving security.
- Immutable (hashCode doesn't change, critical for maps)
- Precomputed, cached hashCode (fast)
- String provides good hash function and collides infrequently
- Returns the canonical, pooled version of a string.
- If the string is already in the pool, returns its reference; else, adds it to the pool and returns it.
- Yes, since Java 7 (before then, only
int,enum,char, or short).
- String: Immutable, thread-safe.
- StringBuffer: Mutable, thread-safe (synchronized).
- StringBuilder: Mutable, not thread-safe (not synchronized), faster for single-threaded use.
Objectis the top (root) class in Java—all classes inherit from it.- Important methods:
toString(),equals(),hashCode(),clone(),getClass(),finalize(),wait(),notify(),notifyAll().
- A constructor is a special method that initializes a new object instance.
- It has the same name as the class, no return type.
- Can be overloaded.
- A constructor with no parameters.
- If you do not define any constructors, Java adds a default constructor (no-args, calls parent’s no-arg constructor).
What is the difference between a default constructor, copy constructor, and parameterized constructor?
- Default constructor: No parameters.
- Parameterized constructor: Takes arguments—lets you control how objects are initialized.
- Copy constructor: Takes another instance of the same class as parameter and makes a copy (not generated by Java, but can be implemented).
- To prevent direct instantiation (e.g. singleton patterns).
- To control how objects are created (like static factory methods).
- To make utility classes (classes with only static members).
Classloaders load Java classes into the JVM at runtime.
Types:
- Bootstrap (loads core Java classes)
- Extension
- Application (System) classloader
You can create custom classloaders to load classes dynamically at runtime, for example, from the network or plugins.
Reflection is a feature that allows a Java program to examine and modify classes, methods, and fields at runtime.
It’s used in frameworks, dependency injection, serialization, and testing.
Example:
Class<?> clz = Class.forName("java.lang.String");
Method[] methods = clz.getDeclaredMethods();==checks if references point to the same object in memory.equals()checks for logical equality (do objects represent the same value/content).
- Reflexive:
a.equals(a)is true - Symmetric:
a.equals(b)is true ⇔b.equals(a)is true - Transitive: if
a.equals(b)andb.equals(c), thena.equals(c) - Consistent: multiple invocations give the same result if objects are unchanged
a.equals(null)is always false
They are:
- Reflexivity
- Symmetry
- Transitivity
- Consistency
- Null comparison always returns false
- Use
@Overrideannotation. - Use
instanceoforgetClass()for type check. - Check all significant fields for equality.
- Handle
nulls safely. - Maintain the contract above (reflexive/symmetric/transitive/consistent/null).
- Yes, you must also override
hashCode()to maintain the general contract: equal objects must have equal hash codes.
- Collections based on hashing (
HashMap,HashSet) may behave incorrectly. - Equal objects could go into different buckets, causing duplicates or lookup failures.
equals()uses==(compares references).hashCode()usually returns a value based on the memory address.
- To efficiently store and retrieve objects in hash-based collections (e.g.,
HashMap,HashSet). - It allows objects to be quickly located using their hash code.
- Equal objects must have the same hash code.
- Unequal objects can have the same hash code but should be minimized.
- The hash code should remain the same while the object is unchanged.
- Use the same fields you check in
equals(). - Use fields that are stable (not likely to change).
- Yes, this is a hash collision and is allowed, but should be minimized.
If Point{int x, y;} implements equals(Object that) {return this.x == that.x && this.y == that.y;}, but int hashCode() {return x;}, will such points be properly stored/retrieved from a HashSet?
- No, different points like
(2, 3)and(2, 4)will have the same hash code but are not equal, leading to poor performance.
- Yes, if they are two references to equal objects but not the same object.
- No, according to the contract, this is not possible.
- No; it breaks the
equals()contract because equal hash codes don’t guarantee logical equality.
In equals(), what's the difference between this.getClass() == that.getClass() and that instanceof MyClass?
getClass()is stricter and only allows exact type matches.instanceofallows subclasses to be equal to superclasses if you choose (depends on your needs).
Can you implement equals() for MyClass as public boolean equals(MyClass that) {return this == that;}?
- This compares references, not values. It effectively disables logical equality.
- Multiplying by 31 helps spread out hash codes better, reducing hash collisions.
- Cloning is creating a new object with the same state as the original.
- Mark the class with
implements Cloneable - Override
protected Object clone() throws CloneNotSupportedException
- Shallow copy: copies values of fields, but for objects, only the reference (not the object itself).
- Deep copy: full recursive copy; all fields and objects are duplicated.
- Usually deep copy for independent copies.
- Shallow copy is default and allows shared mutable state (can be unsafe).
- To provide a default implementation, but only classes that implement
Cloneableshould allow cloning; otherwise,clone()throws.
ThrowableError(serious problems, generally not caught)ExceptionRuntimeException(unchecked)- Other subclasses (checked)
- Checked exceptions: Must be declared or handled (subclasses of
ExceptionexceptRuntimeException) - Unchecked exceptions: Subclasses of
RuntimeExceptionandError, no need to declare or catch
- Checked: Checked at compile time; must be handled.
- Unchecked: Not checked at compile time; often programming errors.
- The
throwoperator.
- Used in method signatures to declare what checked exceptions can be thrown.
- Extend
Exception(for checked) orRuntimeException(for unchecked).
Example:
public class MyException extends Exception {
public MyException(String message) { super(message); }
}- Subclasses of
RuntimeException(NullPointerException, IllegalArgumentException, IndexOutOfBoundsException, etc.)
- Critical errors in the JVM (e.g.,
OutOfMemoryError,StackOverflowError), not intended to be caught.
- JVM cannot allocate memory. Often means a memory leak or insufficient heap size.
try: code to run, may throw exceptions.catch: handles specific exceptions.finally: always runs, cleanup (regardless of exception).
- Used to automatically close resources (classes implementing
AutoCloseable) after use. - Syntax:
try (FileInputStream in = new FileInputStream("file.txt")) { ... }Resource is closed automatically.
- Yes, to ensure resource cleanup even if there is no exception handling.
- Yes, since Java 7, using
|(multi-catch):
catch (IOException | SQLException ex) { ... }- It executes except when
System.exit()is called, or a fatal error occurs, or JVM crashes.
- JVM terminated abruptly (e.g.
System.exit()), power failure, or fatal JVM errors.
- Yes; unhandled exceptions in
main()terminate the program and print the stack trace to the console.
If a method might throw IOException and FileNotFoundException, in what order should catch blocks go? How many catch blocks will be executed?
- Catch
FileNotFoundException(subclass) beforeIOException(superclass). - Only one matching catch block is executed.
- Generics allow classes and methods to operate on parameterized types (type-safe containers, like
List<String>).
? extends T: unknown type that is a subclass of T (covariant: can read, not add).? super T: unknown type that is a superclass of T (contravariant: can write, not guaranteed to read as T).
Comparable: implemented by a class to define its "natural" ordering (compareTo()method, single sort order).Comparator: separate object that defines external order, can define multiple sort orders (compare(o1, o2)).