Skip to content

Latest commit

 

History

History
1265 lines (821 loc) · 49.3 KB

File metadata and controls

1265 lines (821 loc) · 49.3 KB

Java Core



What primitive types are there in Java?

"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';

Back to contents


What is autoboxing in Java and what are the rules for wrapping primitive types?

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.

Back to contents


In what order does Java choose an overloaded method for a primitive argument?

Suppose you call myMethod(10), where 10 is an int. The choices are:

  1. myMethod(int i) — method with exact type match (exact).
  2. myMethod(float i) — method with a "widened" primitive argument (widening). (For primitives: byte < short < int < long < float < double; char < int < long < float < double)
  3. myMethod(Integer i) — method with wrapper argument type (autoboxing).
  4. myMethod(int... i) — method with variadic parameter (varargs).

Back to contents


What is an array in Java?

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

Back to contents


What sorting algorithms are used for arrays in Java?

Version Array.sort(primitives) Array.sort(objects)
Java ...-6 Quicksort MergeSort
Java 7-... DualPivotQuicksort TimSort

Back to contents


What is the result of int[] array = {8, -3, 10, 4}; int result = Arrays.binarySearch(array, 8);?

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.

Back to contents


What is the result of int result = Arrays.binarySearch([-3, 4, 8, 10], 9)?

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.

Back to contents


What modifiers exist?

  • 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.

Back to contents


What is the difference between intrinsic and native methods?

  • native: Declared with the native modifier; 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.

Back to contents


What does the keyword var mean?

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 null without context).

Back to contents


What does the keyword final mean?

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.

Back to contents


What default values do variables have?

  • 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)

Back to contents


What do you know about main() function?

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 single String[] parameter (name can be anything).
  • The JVM looks for this method to begin execution.
  • You can have other overloaded main methods, but only the exact signature above is used as an entry point.

Back to contents


What logical operations and operators do you know?

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: >, <, >=, <=

Back to contents


What is the ternary selection operator?

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 b

Back to contents


What bitwise operations do you know?

For integer types:

  • AND: &
  • OR: |
  • XOR: ^
  • NOT: ~ (bit complement)
  • Left shift: <<
  • Arithmetic right shift (with sign): >>
  • Logical right shift (zero fill): >>>

Back to contents


Are parameters passed by value or by reference?

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.

Back to contents


Where and why is the abstract modifier used?

  • 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.

Back to contents


Define "interface". What default modifiers do interface fields and methods have?

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 final by default
  • Methods: public abstract by default

From Java 8, interfaces can also contain default methods (with implementation) and static methods.

Back to contents


How does an abstract class differ from an interface? When should you use each one?

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.

Back to contents


Why do some interfaces have no methods?

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.

Back to contents


Why can't you declare an interface method with the final modifier?

  • final means "cannot be overridden."
  • All interface methods are implicitly abstract and must be implemented in subclasses; thus, they must be overridden, so declaring them final would be a contradiction.

Back to contents


Which has a higher level of abstraction: class, abstract class, or interface?

Interface is the most abstract, then abstract class, then concrete class.

Back to contents


Can an object access a class member declared as private? If so, how?

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.

Back to contents


What is the order of constructor and initialization block calls, considering class hierarchy?

Initialization of an object follows this order:

  1. Static initializers in parent classes (top-down)
  2. Static initializers in the current class
  3. Instance initializers in parent classes (top-down)
  4. Parent constructor
  5. Instance initializers in current class
  6. Current class constructor

Back to contents


Why do we need initialization blocks and what types are there?

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.

Back to contents


To which Java constructs is the static modifier applicable?

  • Fields (static variables)
  • Methods (static methods)
  • Initialization blocks (static { ... })
  • Nested classes (static class Inner { ... }) — note: only for inner static classes!

Back to contents


Why are static initialization blocks used in Java?

  • 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
}

Back to contents


What happens if an exception occurs in an initialization block?

  • 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.

Back to contents


What exception is thrown if an error occurs in a class initialization block?

  • 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.

Back to contents


Can a static method be overridden or overloaded?

  • 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.

Back to contents


Can non-static methods overload static methods?

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.

Back to contents


Can you narrow access level or return type when overriding a method?

  • Access level: You can only widen (make less restrictive). For example: protectedpublic is allowed; publicprotected is not.
  • Return type: Can specify a more specific (covariant) return type of a subclass of the overridden method’s return type.

Back to contents


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 throws clause.

Back to contents


How do you access an overridden method of a parent class?

Use super:

super.methodName();

This calls the parent class’s method from the child/overriding method.

Back to contents


Can a method be both abstract and static?

No.

  • abstract methods have no body and must be overridden/implemented in subclasses.
  • static methods belong to the class, not instances—and cannot be abstract, as static methods cannot be overridden.

Back to contents


What is the difference between instance and static class members?

  • 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.

Back to contents


Where is initialization of static/non-static fields allowed?

  • Static fields: Can be initialized at declaration, or within static initialization blocks.
  • Non-static fields (instance fields): Can be initialized at declaration, in instance initializer blocks, or in constructors.

Back to contents


What are the types of classes in Java?

  • 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)

Back to contents


Tell about nested classes. In what cases are they used?

  • 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.

Back to contents


What is a "static class"?

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 { ... }

Back to contents


What are particularities of static and inner nested classes? What is the difference between them?

  • Static nested class:

    • Declared with static modifier.
    • Can access only the static members of the outer class.
    • Exists without an instance of the outer class.
  • 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.

Back to contents


What is a "local class"? What are its features?

A local class is a class defined within a method or a block.

  • Its scope is limited to the method/block.
  • Can access final or effectively final variables from its enclosing scope.

Back to contents


What are "anonymous classes"? Where are they used?

  • 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 */ }
};

Back to contents


How can a nested class access a field of the outer class?

  • Inner (non-static) nested class: Can access all members (even private) of the outer class—OuterClass.this.fieldName.
  • Static nested class: Can only access static fields of the outer class directly.

Back to contents


Why is the assert operator used?

  • Used for assertions—statement that a condition should always be true. If false, an AssertionError is 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";

Back to contents


What are Heap and Stack memory in Java? What is the difference?

  • 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.

Back to contents


Is it true that primitive data types are always stored on the stack, and objects on the heap?

  • 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.

Back to contents


How are variables passed to methods: by value or by reference?

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).

Back to contents


What is the "string pool"?

  • 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); // true

Both point to the same interned string.

Back to contents


What is finalize()? Why is it needed?

  • finalize() is a method in Object that 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.

Back to contents


What happens if finalize() takes a long time or throws an exception for the garbage collector?

  • 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.

Back to contents


How do final, finally, and finalize() differ?

  • 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).

Back to contents


Tell about type casting. What are widening and narrowing?

  • Widening (implicit cast): Conversion from a smaller to a larger type (e.g. int to long).
    • Safe, no data loss.
  • Narrowing (explicit cast): Larger to smaller type (e.g. long to int).
    • 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

Back to contents


When can a ClassCastException be thrown?

  • 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

Back to contents


What are the features of the String class?

  • 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.

Back to contents


Why is String immutable and final?

  • For security (e.g. safe for keys in maps, parameters in networking).
  • For thread safety.
  • To allow sharing (string pool) and caching hash codes.

Back to contents


Why is char[] preferred over String for storing a password?

  • String is 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.

Back to contents


Why is String a popular key in HashMap in Java?

  • Immutable (hashCode doesn't change, critical for maps)
  • Precomputed, cached hashCode (fast)
  • String provides good hash function and collides infrequently

Back to contents


What does the intern() method do in the String class?

  • 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.

Back to contents


Can you use strings in a switch statement?

  • Yes, since Java 7 (before then, only int, enum, char, or short).

Back to contents


What is the main difference between String, StringBuffer, and StringBuilder?

  • String: Immutable, thread-safe.
  • StringBuffer: Mutable, thread-safe (synchronized).
  • StringBuilder: Mutable, not thread-safe (not synchronized), faster for single-threaded use.

Back to contents


What is the Object class? What methods does it have?

  • Object is the top (root) class in Java—all classes inherit from it.
  • Important methods: toString(), equals(), hashCode(), clone(), getClass(), finalize(), wait(), notify(), notifyAll().

Back to contents


Define "constructor"

  • 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.

Back to contents


What is a "default constructor"?

  • 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).

Back to contents


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).

Back to contents


Where and how can you use a private constructor?

  • 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).

Back to contents


Tell about classloaders and dynamic class loading

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.


What is Reflection?

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();

Why do we need equals()? How does it differ from ==?

  • == checks if references point to the same object in memory.
  • equals() checks for logical equality (do objects represent the same value/content).

If you want to override equals(), what conditions must be met?

  • Reflexive: a.equals(a) is true
  • Symmetric: a.equals(b) is true ⇔ b.equals(a) is true
  • Transitive: if a.equals(b) and b.equals(c), then a.equals(c)
  • Consistent: multiple invocations give the same result if objects are unchanged
  • a.equals(null) is always false

What properties does the equivalence relation of equals() generate?

They are:

  1. Reflexivity
  2. Symmetry
  3. Transitivity
  4. Consistency
  5. Null comparison always returns false

Rules for overriding Object.equals()

  • Use @Override annotation.
  • Use instanceof or getClass() for type check.
  • Check all significant fields for equality.
  • Handle nulls safely.
  • Maintain the contract above (reflexive/symmetric/transitive/consistent/null).

If equals() is overridden, are there other methods you should override?

  • Yes, you must also override hashCode() to maintain the general contract: equal objects must have equal hash codes.

What happens if you override equals() but not hashCode()? What problems can arise?

  • Collections based on hashing (HashMap, HashSet) may behave incorrectly.
  • Equal objects could go into different buckets, causing duplicates or lookup failures.

How are hashCode() and equals() implemented in the Object class?

  • equals() uses == (compares references).
  • hashCode() usually returns a value based on the memory address.

Why is the hashCode() method needed?

  • 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.

What are the rules for overriding Object.hashCode()?

  • 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.

Are there recommendations on which fields to use in hashCode()?

  • Use the same fields you check in equals().
  • Use fields that are stable (not likely to change).

Can different objects have the same hashCode()?

  • 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.

Can ref0 != ref1 but ref0.equals(ref1) == true?

  • Yes, if they are two references to equal objects but not the same object.

Can two references to the same object (ref0 == ref1) have ref0.equals(ref1) == false?

  • No, according to the contract, this is not possible.

Can you implement equals(Object that) {return this.hashCode() == that.hashCode();}?

  • 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.
  • instanceof allows 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.

For the class Point{int x, y;}, why is 31 * x + y preferable as a hash code than x + y?

  • Multiplying by 31 helps spread out hash codes better, reducing hash collisions.

Tell about object cloning

  • 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

What's the difference between shallow and deep cloning?

  • 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.

Which cloning method is preferable?

  • Usually deep copy for independent copies.
  • Shallow copy is default and allows shared mutable state (can be unsafe).

Why is clone() declared in Object and not in the Cloneable interface?

  • To provide a default implementation, but only classes that implement Cloneable should allow cloning; otherwise, clone() throws.

Describe the exception hierarchy

  • Throwable
    • Error (serious problems, generally not caught)
    • Exception
      • RuntimeException (unchecked)
      • Other subclasses (checked)

What types of exceptions are there in Java and how do they differ?

  • Checked exceptions: Must be declared or handled (subclasses of Exception except RuntimeException)
  • Unchecked exceptions: Subclasses of RuntimeException and Error, no need to declare or catch

What are checked and unchecked exceptions?

  • Checked: Checked at compile time; must be handled.
  • Unchecked: Not checked at compile time; often programming errors.

What operator allows you to throw an exception?

  • The throw operator.

What does the throws keyword mean?

  • Used in method signatures to declare what checked exceptions can be thrown.

How do you write your own (user-defined) exception?

  • Extend Exception (for checked) or RuntimeException (for unchecked).

Example:

public class MyException extends Exception {
    public MyException(String message) { super(message); }
}

What unchecked exceptions exist?

  • Subclasses of RuntimeException (NullPointerException, IllegalArgumentException, IndexOutOfBoundsException, etc.)

What does the Error class represent?

  • Critical errors in the JVM (e.g., OutOfMemoryError, StackOverflowError), not intended to be caught.

What do you know about OutOfMemoryError?

  • JVM cannot allocate memory. Often means a memory leak or insufficient heap size.

Describe how the try-catch-finally block works

  • try: code to run, may throw exceptions.
  • catch: handles specific exceptions.
  • finally: always runs, cleanup (regardless of exception).

What is the try-with-resources mechanism?

  • Used to automatically close resources (classes implementing AutoCloseable) after use.
  • Syntax:
try (FileInputStream in = new FileInputStream("file.txt")) { ... }

Resource is closed automatically.


Is it possible to use try-finally block (without catch)?

  • Yes, to ensure resource cleanup even if there is no exception handling.

Can one catch block catch several exceptions?

  • Yes, since Java 7, using | (multi-catch):
catch (IOException | SQLException ex) { ... }

Does the finally block always execute?

  • It executes except when System.exit() is called, or a fatal error occurs, or JVM crashes.

Are there situations when the finally block will not be executed?

  • JVM terminated abruptly (e.g. System.exit()), power failure, or fatal JVM errors.

Can the main() method throw an exception outwards and where will it be handled?

  • 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) before IOException (superclass).
  • Only one matching catch block is executed.

What are generics?

  • Generics allow classes and methods to operate on parameterized types (type-safe containers, like List<String>).

Describe the difference between ? extends ... and ? super ... with generics

  • ? 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).

How is java.lang.Comparable different from java.util.Comparator?

  • 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)).