Skip to content
thesarfo

Reference

Interview Prep: Java Core Concepts

Method overloading vs overriding, heap vs stack, shallow vs deep copy, garbage collection, equals/hashCode, collections hierarchy, and more Java fundamentals Q&A.

views 0
  1. What is Method Overloading vs Method Overriding?

    • Method overloading means in the same class, you can have multiple methods with the same name, but they have to have either different types of parameters, or a different number of parameters.
    • Method overriding has to do with inheritance, where a child class can implement a method it got from a parent class.
  2. What are the differences between Heap and Stack memory?

    • Stack memory is a fixed amount of memory allocated for each individual program — a dedicated part of memory where local variables, parameters, and similar things live. When you have a method call or recursive call, the program saves the local variables of the current method call into the stack. Too many method calls/recursive calls, or too much stored in the stack, causes a StackOverflowError.
    • Heap memory grows and shrinks dynamically as your program runs. When you allocate space with the new keyword, it checks if there’s space on the heap and stores the new object there. If the object goes out of scope, that memory is freed. Allocate too much, and the heap can also run out of memory, crashing your program.
  3. What are shallow copy and deep copy?

    • With a shallow copy, when you create another object that points to the first object, changing the value of the second object affects the value of the first, since both point to the same reference:
      Example example1 = new Example();
      example1.x = 100;
      Example example2 = example1;
      example2.x = 500;
      System.out.print(example1.value); // prints 500 because example2 points to the same reference as example1.
    • With a deep copy, it’s the opposite — you create a new object of example2 so it points to its own reference, and changing its value doesn’t affect example1:
      Example example1 = new Example();
      example1.x = 100;
      Example example2 = new Example();
      example2.x = 500;
      System.out.print(example1.value); // remains 100
      System.out.print(example2.value); // prints 500
  4. What is the garbage collector and how does it work? Its main objective is to free up memory space that’s no longer being used, ensuring efficient memory usage. When a value in allocated memory is no longer used, the garbage collector de-allocates the memory for that value, and the heap shrinks.

  5. What is the difference between a constructor and a method of a class in Java?

    • A constructor shares the class’s name and has no return type. It’s invoked implicitly when you create a new object. A subclass can’t inherit a parent’s constructor. A constructor is a method, but a method isn’t a constructor.
    • A method has a different name and a return type. Methods are only called when explicitly invoked. A child class can inherit a parent’s public methods.
  6. What is the this keyword in Java? Used within a class to call a method or reference a class-level variable. A practical use: when a constructor parameter shares a name with a class field, this distinguishes the field from the local parameter (without it, the constructor would try to set the parameter to itself, which doesn’t work).

  7. What is an abstract class? A class that cannot be instantiated. For example, in a game with different enemy types (ghosts, goblins, wizards) that each extend a common Enemy class and implement their own attack — you don’t want a generic enemy instantiated, since “enemy” is just an abstract concept used to define something in the game. You can mark Enemy as abstract so you can’t create a new object of it, but you can still inherit from it.

  8. What is the super keyword in Java? Refers to the superclass. Used in a child class to refer to something in its parent/super class.

  9. How is the final keyword applied differently between variables, methods, and classes?

    • Final methods cannot be overridden in child classes.
    • Final variables cannot be reassigned.
    • Final classes cannot be extended (no inheritance).
  10. What is protected in Java? Allows access to a method, class, or variable within a package, but not outside it — like private, but scoped to the package instead of the class.

  11. What is the difference between equals() and == in Java?

    • == is a comparison operator — checks if two entities are at the same reference/memory location.
    • .equals() is a method — evaluates the content of that reference/memory space.
  12. Is Java “Pass by Reference” or “Pass by Value”? Java is pass by value.

  13. What is a Singleton class and how do you ensure a class is a Singleton? A class that ensures only one instance can ever exist — typically done by making all constructors private and providing a method that returns a reference to the single instance.

  14. What are composition and aggregation? State the difference. Composition is having an object inside a class — a has-a relationship.

  15. What is a static block? Code that runs at class-loading time, before main() runs. Put any logic that needs to execute before main() in a static block.

  16. Why is the remove() method faster in a linked list than in an ArrayList? Removing from an ArrayList requires restructuring the positions of the remaining elements. A linked list just updates a pointer to another node.

  17. What is a Comparator and Comparable in Java? Both specify how to sort collections of data. Comparable is an interface you implement in your class, overriding compareTo().

  18. What is the difference between an abstract class and an interface? An abstract class can have both abstract and non-abstract methods and can be extended by other classes; an interface only contains abstract method declarations and can be implemented by classes.

  19. What is a thread in Java? A lightweight unit of execution within a program, allowing concurrent execution of multiple tasks and better utilization of system resources.

  20. How do you create and start a thread in Java? Either extend the Thread class and override run(), or implement the Runnable interface and pass it to a new Thread object. Call start() to begin execution.

  21. What is synchronization in Java? A technique to control access and execution of multiple threads, ensuring only one thread can access a shared resource or code block at a time.

  22. What is an exception in Java? An event during program execution that disrupts the normal flow of instructions — representing an error condition or exceptional circumstance.

  23. What is the difference between checked and unchecked exceptions? Checked exceptions are checked at compile-time, requiring the programmer to handle or declare them with throws. Unchecked exceptions aren’t checked at compile-time, and handling/declaring them isn’t mandatory.

  24. How do you handle exceptions in Java? Using try-catch blocks — code that may throw an exception goes in the try block, and if one occurs, it’s caught and handled in the catch block.

  25. What is the purpose of the “finally” block? Defines code that runs regardless of whether an exception occurs — often used to release resources or perform cleanup.

  26. What is the difference between the “throw” and “throws” keywords? throw manually throws an exception; throws is used in method declarations to specify the method may throw certain exception types.

  27. What is the difference between an ArrayList and a LinkedList? An ArrayList is a resizable array — fast random access, slower insertion/removal. A LinkedList is a doubly-linked list — fast insertion/removal, slower random access.

  28. What is the difference between “equals()” and “hashCode()”? equals() compares objects based on their values; hashCode() calculates a unique hash code for an object, typically used for efficient retrieval in hash-based structures like HashMap.

  29. What is a lambda expression in Java? An anonymous function that simplifies the syntax of functional interfaces, enabling more concise, readable code — especially for functional programming constructs.

  30. What are the Java 8 features for functional programming? Lambda expressions, functional interfaces, the Stream API for working with collections, and default methods in interfaces.

  31. What is the difference between an interface and an abstract class? An interface can only declare method signatures and constants, with no implementations; an abstract class can have both declarations and concrete implementations. A class can implement multiple interfaces but inherit from only one abstract class.

  32. What is the difference between a BufferedReader and a Scanner? BufferedReader reads text from a character stream with efficient buffering. Scanner can parse different types of data from various sources (files, strings, stdin).

  33. What is the purpose of the StringBuilder class? Creates and manipulates mutable sequences of characters — more efficient than concatenating with +, since it avoids unnecessary object creation.

  34. What is the difference between Comparable and Comparator? Comparable defines a class’s natural ordering via compareTo(). Comparator defines custom ordering via compare(), independent of the class being compared.

  35. What is the purpose of the transient keyword? Indicates a variable shouldn’t be serialized — on deserialization, transient fields are set to their default values.

  36. What is the purpose of the enum keyword? Defines an enumeration — a special type representing a fixed set of constants, for structured, type-safe representation of predefined values.

  37. What is the purpose of the “try-with-resources” statement? Automatically closes resources implementing AutoCloseable, ensuring proper cleanup even if an exception occurs.

  38. What is the difference between pre-increment and post-increment? ++i increments and returns the incremented value; i++ increments but returns the original value before the increment.

  39. What is the purpose of StringBuffer? Like StringBuilder, but synchronized and thread-safe, suited to multi-threaded environments.

  40. What is NullPointerException? Thrown when a null reference is accessed where an object reference is expected — indicates a programming error to be handled or prevented.

  41. What is ArrayIndexOutOfBoundsException? Thrown when an invalid (negative or out-of-bounds) index is used to access an array.

  42. What is the purpose of the HashSet class? An implementation of Set that stores unique elements in no particular order, with constant-time performance for basic operations.

  43. What is the purpose of the HashMap class? An implementation of Map storing key-value pairs, with fast retrieval and insertion based on keys.

  44. What is the purpose of the LinkedList class? An implementation of List using a doubly-linked list, giving efficient insertion/removal at both ends but slower random access.

  45. What is the purpose of the Comparable interface? Defines the natural ordering of objects of a class, via compareTo().

  46. What is the purpose of the Comparator interface? Defines custom ordering based on criteria other than the natural ordering from Comparable.

  • We need Comparable and Comparator because Java can’t sort custom objects the way it sorts primitives.
  • Implementing Comparable requires overriding compareTo().
  • To sort a class differently in different contexts, define a Comparator with a compare() method for the custom criteria.
  1. What is the purpose of the throw keyword? Manually throws an exception, typically when encountering an error that can’t be handled and should be transferred to an exception handler.

  2. Aggregation vs. Composition: Association depicts the relationship between two classes, with two types. Aggregation is a weak association/loose coupling — one object can exist without the other. Composition is a strong association/tight coupling — one object cannot exist without the other.

  3. Shallow vs. Deep comparison: Shallow comparison compares equality of memory locations (==). Deep comparison compares equality of state (.equals()).

Equals and HashCode Contract

  • If two objects are equal per equals(Object o), their hash codes must be the same integer value.
  • The reverse isn’t guaranteed — two objects with the same hash code aren’t necessarily equal (this is a collision; better hash functions reduce it).
  • Invoked multiple times on the same object during one execution, hashCode() must consistently return the same integer.
How to implement the equals method
  1. Check if the object is null, or not an instance of the specified class — return false if so.
  2. Check if the object is the same reference as this — if so, return true.
  3. Cast the object to the specified class and return true if its id matches this instance’s id.
public boolean equals(Object o){
if (o == null || getClass() != o.getClass()){ // step 1
return false; // they are not equal
}
if (o == this || getClass() != o.getClass()){ // step 2
return true;
}
Employee e = (Employee) o;
return (this.getId() == e.getId()); // step 3
}

Implementing a hashCode method

public int hashCode(){
return getId(); // this is probably the most simple way
}
  1. What is Garbage Collection in Java and what are its advantages? An automatic process that looks at heap memory, identifies which objects are in use vs. not, and deletes the unused ones. An “in use” (referenced) object still has a pointer maintained by some part of the program; an unreferenced object no longer has any references, so its memory can be reclaimed. The main advantage: it removes the burden of manual memory allocation/deallocation, letting developers focus on problem-solving.

    Whenever an object is created, it’s stored in the heap, and stack memory holds a reference to it.

    • Garbage collection always happens in the heap.
    • The JVM controls the garbage collector, running it when memory runs low.
  2. Explain the Collection Hierarchy. java.util.Collection is the root of the Java collection framework — most collections inherit from it, except the Map interface.

    • The 3 basic interfaces implementing Collection are List, Queue, and Set.
    • List — ordered elements, may include duplicates, supports index-based search and random access, with easy insertion regardless of position.
    • Set — doesn’t define an order, so index-based search isn’t supported. Doesn’t contain duplicates.
    • Queue — follows a FIFO approach. Elements added at the rear, removed from the front.
    • Map — represents a key-value pair. Map doesn’t implement Collection. Keys are unique; values can have duplicates.