Core Java is the foundation of every Java role. Before frameworks such as Spring Boot, interviewers check whether you understand objects, strings, collections, modern Java features and how to handle errors. This guide covers all of it in one place, with short code examples and the interview questions each topic usually leads to.
Contents
- 1. Classes, objects and the four pillars of OOP
- 2. Interfaces vs abstract classes
- 3. The static and final keywords
- 4. Strings: equals vs ==, immutability and StringBuilder
- 5. Collections: List, Set and Map
- 6. ArrayList vs LinkedList
- 7. How HashMap works
- 8. The equals and hashCode contract
- 9. Generics
- 10. Lambda expressions
- 11. Streams: filter, map and collect
- 12. Optional and NullPointerException
- 13. Records
- 14. Exception handling
- 15. try-with-resources
- 16. Multithreading basics
- 17. Debugging step by step
- 18. Unit testing with JUnit
1. Classes, objects and the four pillars of OOP
A class describes a type of thing, such as an Employee, with its data (fields) and behaviour (methods). An object is one real instance, created with new. A method is a block of code inside a class that performs an action, such as calculating a salary; it can take inputs and return a result.
Object-oriented programming rests on four ideas, which interviewers ask about early:
- Encapsulation: keep fields private and expose them through methods, so the data stays valid.
- Inheritance: a child class reuses and extends a parent, such as Car extending Vehicle.
- Polymorphism: one method call behaves differently for different objects, such as
draw()on a Circle and a Square. - Abstraction: hide detail and show only what a user needs, using an interface or abstract class.
Explain all four with one real-world example, such as a bank account; a clear example beats a memorised definition. Practice: write an Employee class with private fields, a constructor and a method returning a formatted description, then a Manager class that extends it.
2. Interfaces vs abstract classes
An abstract class cannot be instantiated. It can have fields, constructors, normal methods and abstract methods that subclasses must implement. An interface defines a contract of methods a class promises to provide; since Java 8 it can also have default and static methods, but no instance state.
public abstract class Payment {
protected double amount;
public Payment(double amount) { this.amount = amount; }
public abstract boolean process();
public String receipt() { return "Paid: " + amount; }
}
public interface Notifier {
void send(String message);
}- A class can extend only one class but implement many interfaces.
- Abstract classes can hold instance fields and constructors; interfaces cannot.
- Extending says “is a kind of”; implementing says “can do”.
Use an abstract class when related classes share real code and state, such as card, UPI and net-banking payments that all store an amount. Use an interface when unrelated classes need the same capability, such as email, SMS and WhatsApp notifiers. Spring Boot relies heavily on interfaces (repositories and service contracts), which makes code easy to test with fake implementations.
3. The static and final keywords
static: belongs to the class, not the object
- Static variable: one copy shared by all objects, such as a counter of Students created.
- Static method: called on the class, such as
Math.max(3, 7); it cannot use instance fields directly.mainis static because Java calls it before any object exists. - Static block: runs once when the class loads.
final: cannot be changed
- Final variable: assigned once. A final reference cannot point elsewhere, but the object itself can still change: a final List can still have items added.
- Final method: cannot be overridden. Final class: cannot be extended; String is final.
Constants combine both: public static final double GST_RATE = 0.18;. A classic interview question is final vs finally vs finalize: final is the keyword above, finally is a block after try-catch that always runs, and finalize is an old, deprecated garbage-collection hook. Avoid making everything static, and never hold per-user data in static fields in a web app, because all users would share it.
4. Strings: equals vs ==, immutability and StringBuilder
== checks whether two variables point to the same object; equals() checks whether two strings contain the same characters.
String a = "java";
String b = new String("java");
a == b // false: different objects
a.equals(b) // true: same textSometimes == appears to work because Java reuses identical literals from the string pool, so the bug passes a quick test and fails later with real input. Always compare text with equals() or equalsIgnoreCase(), and write "admin".equals(role) to avoid a NullPointerException.
Strings are immutable: methods like trim() return a new string, so name = name.trim(); is needed. Immutability makes strings safe to share between threads and to use as HashMap keys. Because of it, joining strings with + inside a long loop creates many temporary objects; use StringBuilder there, or String.join(", ", items). StringBuffer is the older synchronized version and is slower.
5. Collections: List, Set and Map
- List keeps items in order and allows duplicates. ArrayList is the usual choice.
- Set does not allow duplicates. HashSet is fast but unordered; TreeSet keeps items sorted.
- Map stores key-value pairs, such as employee ID to employee. HashMap is fast for lookups; TreeMap keeps keys sorted; LinkedHashMap keeps insertion order.
Need order and duplicates? A List. Unique items? A Set. Look-up by key? A Map.
6. ArrayList vs LinkedList
ArrayList stores elements in an internal array, so get(500) jumps straight to position 500. Adding at the end is usually fast; when the array fills, Java copies it to a bigger one, which is rare enough to stay efficient on average. Inserting or removing in the middle shifts every later element.
LinkedList stores each element in a node linked to the previous and next nodes. Changing links is cheap once you reach the node, but reaching position 500 means walking 500 nodes, and each node uses extra memory.
Use ArrayList by default; modern CPUs read arrays very efficiently, so it wins in most real programs. For a queue or stack, prefer ArrayDeque. Neither is thread-safe; use Collections.synchronizedList or CopyOnWriteArrayList when needed.
7. How HashMap works
A HashMap keeps an internal array of buckets. On put(key, value), Java calls key.hashCode(), turns it into a bucket index and stores the pair there. On get(key), it computes the same index and uses equals() to find the exact key, so lookups are close to constant time.
- Collisions: different keys can share a bucket, and equals() decides which matches. Since Java 8, crowded buckets become balanced trees.
- Resizing: at about 75% full (load factor 0.75) the bucket array doubles. Pass an initial capacity if you know you will store many items.
- Facts to remember: one null key and many null values are allowed; it is not thread-safe (use ConcurrentHashMap); it does not keep order; keys should be immutable, such as String or Integer.
8. The equals and hashCode contract
The default equals() compares references. For value objects you usually want equality based on fields, and then you must also override hashCode():
- If
a.equals(b)is true,a.hashCode() == b.hashCode()must be true. - The hash code must not change while the object is used as a key.
- Equal hash codes do not guarantee equal objects; that is why collisions happen.
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student s = (Student) o;
return id == s.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}If you override only equals(), two “equal” keys can land in different buckets and get() returns null for a key you just stored. Use the same fields in both methods, avoid mutable fields in hashCode, and let records or your IDE generate them.
9. Generics
Every List<String> uses generics: one class works with many types while the compiler checks you use them correctly, with no casting when reading.
public class ApiResponse<T> {
private final T data;
public ApiResponse(T data) { this.data = data; }
public T getData() { return data; }
}
public static <T> T firstOrDefault(List<T> items, T fallback) {
return items.isEmpty() ? fallback : items.get(0);
}- Bounded types:
<T extends Number>allows callingdoubleValue(), so one method can sum Integers, Doubles or Longs. - Wildcards:
List<? extends Number>for reading,List<? super Integer>for writing: “producer extends, consumer super” (PECS). - Type erasure: generic types are removed after compilation, so you cannot write
new T()or checkinstanceof List<String>, a common interview question.
10. Lambda expressions
Lambdas, added in Java 8, let you write short behaviour inline: (parameters) -> expression, such as x -> x * 2 or (a, b) -> a + b. Sorting names by length becomes names.sort((a, b) -> Integer.compare(a.length(), b.length()));.
A lambda can be used wherever Java expects a functional interface (exactly one abstract method). The common ones in java.util.function are Predicate (returns true or false, for filtering), Function (transforms a value), Consumer (uses a value, returns nothing) and Supplier (returns a value). When a lambda only calls an existing method, use a method reference: names.forEach(System.out::println). Lambdas can only use local variables that are effectively final, and should stay short.
11. Streams: filter, map and collect
Streams process a collection as a chain of steps instead of a loop with temporary variables:
List<String> toppers = students.stream()
.filter(s -> s.getScore() > 60)
.map(Student::getName)
.collect(Collectors.toList());filter keeps matching items, map transforms each item, and collect gathers the result. The chain reads top to bottom in the order data moves. Streams are not always faster than loops; use them when they make the code clearer, and avoid long chains that are hard to debug.
12. Optional and NullPointerException
NullPointerException is the most common runtime error in Java, usually because a method returned null and the caller forgot to check. Optional makes “there may be no value” visible in the method signature, and Spring Data repositories already use it: courseRepository.findById(id) returns Optional<Course>.
orElse(default)supplies a fallback;orElseGet(() -> createDefault())builds it only when needed.orElseThrow(() -> new CourseNotFoundException(id))fails with a clear error, the common choice in REST APIs.map()transforms the value if present:findById(id).map(Course::getTitle).orElse("Unknown").
Avoid calling get() without checking, using Optional for fields or parameters, returning null from an Optional method, and wrapping collections (return an empty list instead).
13. Records
Records, standard since Java 16, replace pages of boilerplate for simple data carriers:
public record CourseDto(Long id, String title, int durationMonths) {
public CourseDto {
if (durationMonths <= 0) throw new IllegalArgumentException("Duration must be positive");
}
}Java generates private final fields, a constructor, accessors named after the fields (dto.title()), and correct equals(), hashCode() and toString(). Records are immutable, so they are safe to share and to use as map keys. They suit DTOs for Spring Boot REST APIs, but keep JPA entities as normal classes, because entities need a no-argument constructor and changeable fields.
14. Exception handling
Put risky code in try, handle specific errors in catch, and use finally for clean-up that must always run.
- Checked exceptions must be handled or declared, such as IOException.
- Unchecked exceptions usually signal a bug, such as NullPointerException; fix the cause rather than only catching it.
Catch the most specific exception you can, never leave a catch block empty (log the error at least), and create custom exceptions for broken business rules, such as InsufficientBalanceException, so the failure is clear to anyone reading the code.
15. try-with-resources
Files, database connections and streams must be closed after use, or they leak. Before Java 7 that meant a long finally block; try-with-resources does it for you:
try (BufferedReader reader = new BufferedReader(new FileReader("courses.txt"))) {
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}The resource closes automatically when the block ends, even after an exception. Several resources can be listed, closing in reverse order. A resource must implement AutoCloseable, as most I/O classes and JDBC connections do. If both the block and the close fail, the close error is attached as a suppressed exception (e.getSuppressed()), whereas the old finally approach could hide the original error.
16. Multithreading basics
A thread is a separate path of execution, letting a program handle many tasks, such as user requests, at once. Create threads by implementing Runnable or, more commonly today, by submitting tasks to an ExecutorService.
The main risk is shared data: when two threads change the same data at once you get a race condition. Stay safe with synchronized blocks or locks around shared changes, thread-safe classes such as ConcurrentHashMap, and by avoiding shared mutable data where possible. Prepare for: the difference between a process and a thread, what a deadlock is and how to avoid one, and why ExecutorService beats creating threads by hand.
17. Debugging step by step
- Reproduce the problem with the exact steps and input.
- Read the stack trace, starting at the first line from your own code.
- Use breakpoints in IntelliJ or Eclipse, run in debug mode and watch variables change.
- Change one thing at a time and note the result.
- Write a test for the bug once fixed, so it does not come back.
18. Unit testing with JUnit
A unit test checks that one small piece of code works as expected, and JUnit is the standard library for it.
@Test
void addsTwoNumbers() {
assertEquals(5, Calculator.add(2, 3));
}Test the normal case, edge cases such as zero, empty lists or very large values, and error cases where an exception should be thrown (assertThrows). Name each test after what it checks, keep it focused on one behaviour, and run all tests before you push code. Interviewers often ask freshers whether they have written tests, so include them in every project.
For what is new in the language, read Java 27: the changes freshers should know.
Learn Java with ScholarLogic
Core Java is the first stage of the Java Full Stack course in Bangalore at ScholarLogic, BTM Layout, before Spring Boot, databases and front-end development. Book a free demo class and a counsellor will share the fee and the next batch dates. To book, call 78923 93639.

Spring Boot for Beginners: Build a REST API with JPA, MySQL, Security and Tests - ScholarLogic
[…] you are still learning the language itself, start with our Core Java guide; Spring Boot relies heavily on interfaces, generics, lambdas, Optional and […]