-
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.
-
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
newkeyword, 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.
- 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
-
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
example2so it points to its own reference, and changing its value doesn’t affectexample1:Example example1 = new Example();example1.x = 100;Example example2 = new Example();example2.x = 500;System.out.print(example1.value); // remains 100System.out.print(example2.value); // prints 500
- 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:
-
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.
-
What is the difference between a
constructorand amethodof 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.
-
What is the
thiskeyword 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,thisdistinguishes the field from the local parameter (without it, the constructor would try to set the parameter to itself, which doesn’t work). -
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
Enemyclass 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 markEnemyas abstract so you can’t create anewobject of it, but you can still inherit from it. -
What is the
superkeyword in Java? Refers to the superclass. Used in a child class to refer to something in its parent/super class. -
How is the
finalkeyword 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).
-
What is
protectedin Java? Allows access to a method, class, or variable within a package, but not outside it — likeprivate, but scoped to the package instead of the class. -
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.
-
Is Java “Pass by Reference” or “Pass by Value”? Java is pass by value.
-
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.
-
What are composition and aggregation? State the difference. Composition is having an object inside a class — a has-a relationship.
-
What is a static block? Code that runs at class-loading time, before
main()runs. Put any logic that needs to execute beforemain()in a static block. -
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. -
What is a
ComparatorandComparablein Java? Both specify how to sort collections of data.Comparableis an interface you implement in your class, overridingcompareTo(). -
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.
-
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.
-
How do you create and start a thread in Java? Either extend the
Threadclass and overriderun(), or implement theRunnableinterface and pass it to a newThreadobject. Callstart()to begin execution. -
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.
-
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.
-
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. -
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.
-
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.
-
What is the difference between the “throw” and “throws” keywords?
throwmanually throws an exception;throwsis used in method declarations to specify the method may throw certain exception types. -
What is the difference between an ArrayList and a LinkedList? An
ArrayListis a resizable array — fast random access, slower insertion/removal. ALinkedListis a doubly-linked list — fast insertion/removal, slower random access. -
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 likeHashMap. -
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.
-
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.
-
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.
-
What is the difference between a
BufferedReaderand aScanner?BufferedReaderreads text from a character stream with efficient buffering.Scannercan parse different types of data from various sources (files, strings, stdin). -
What is the purpose of the
StringBuilderclass? Creates and manipulates mutable sequences of characters — more efficient than concatenating with+, since it avoids unnecessary object creation. -
What is the difference between
ComparableandComparator?Comparabledefines a class’s natural ordering viacompareTo().Comparatordefines custom ordering viacompare(), independent of the class being compared. -
What is the purpose of the
transientkeyword? Indicates a variable shouldn’t be serialized — on deserialization, transient fields are set to their default values. -
What is the purpose of the
enumkeyword? Defines an enumeration — a special type representing a fixed set of constants, for structured, type-safe representation of predefined values. -
What is the purpose of the “try-with-resources” statement? Automatically closes resources implementing
AutoCloseable, ensuring proper cleanup even if an exception occurs. -
What is the difference between pre-increment and post-increment?
++iincrements and returns the incremented value;i++increments but returns the original value before the increment. -
What is the purpose of
StringBuffer? LikeStringBuilder, but synchronized and thread-safe, suited to multi-threaded environments. -
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. -
What is
ArrayIndexOutOfBoundsException? Thrown when an invalid (negative or out-of-bounds) index is used to access an array. -
What is the purpose of the
HashSetclass? An implementation ofSetthat stores unique elements in no particular order, with constant-time performance for basic operations. -
What is the purpose of the
HashMapclass? An implementation ofMapstoring key-value pairs, with fast retrieval and insertion based on keys. -
What is the purpose of the
LinkedListclass? An implementation ofListusing a doubly-linked list, giving efficient insertion/removal at both ends but slower random access. -
What is the purpose of the
Comparableinterface? Defines the natural ordering of objects of a class, viacompareTo(). -
What is the purpose of the
Comparatorinterface? Defines custom ordering based on criteria other than the natural ordering fromComparable.
- We need
ComparableandComparatorbecause Java can’t sort custom objects the way it sorts primitives. - Implementing
Comparablerequires overridingcompareTo(). - To sort a class differently in different contexts, define a
Comparatorwith acompare()method for the custom criteria.
-
What is the purpose of the
throwkeyword? Manually throws an exception, typically when encountering an error that can’t be handled and should be transferred to an exception handler. -
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.
-
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
- Check if the object is null, or not an instance of the specified class — return false if so.
- Check if the object is the same reference as
this— if so, return true. - 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}-
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.
-
Explain the Collection Hierarchy.
java.util.Collectionis the root of the Java collection framework — most collections inherit from it, except the Map interface.- The 3 basic interfaces implementing
CollectionareList,Queue, andSet. - 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.
Mapdoesn’t implementCollection. Keys are unique; values can have duplicates.
- The 3 basic interfaces implementing