Java Core Concepts
• Variables & Data Types: Java is a statically-typed language. Each variable has a type (primitive or
reference) determining what values it can hold and what operations are allowed. There are eight
primitive types: byte, short, int, long (integral), float, double (floating-point),
boolean , and char 1 . For example, declaring int gear = 1; tells the compiler gear
holds an integer 2. Java also has reference types (classes, interfaces, arrays), which can be
null or point to objects.
• OOP Principles: Java is object-oriented. Key principles include:
• Abstraction: Hiding complex details and exposing only the essential features. For example, an
abstract class or interface defines what operations are available, not how they’re implemented
3 .
• Encapsulation: Binding data (fields) and code (methods) together, and restricting direct access
to an object’s internals. Typically private fields with public getters/setters implement
encapsulation 4 .
• Inheritance: A class can inherit fields and methods from a parent class (using extends ),
enabling code reuse. For instance, a Car class can inherit from a Vehicle class. Inheritance
supports hierarchical classification 5 .
• Polymorphism: The ability for objects to take many forms. In Java, this means a subclass
instance can be treated as an instance of its superclass (subtype polymorphism), and a single
method name can have multiple implementations (method overriding or overloading). At
runtime, the JVM binds calls to the correct overridden method implementation 6 .
• Interfaces & Abstract Classes: An interface is a reference type that can declare abstract
methods (as of Java 8, also default and static methods). Classes implement interfaces. An abstract
class is a class marked abstract that cannot be instantiated and may contain both abstract
methods (without body) and concrete methods. Abstract classes are used to define a common
base behavior for subclasses. For example, an abstract class defines a template for subclasses to
fill in. Interfaces (especially functional interfaces) and abstract classes help achieve abstraction
and define contracts 7 8 .
• Exception Handling: Java uses exceptions to handle runtime errors. You use try , catch ,
finally , throw , and throws to manage exceptions. A try block encloses code that
might throw exceptions; catch blocks handle specific exception types; finally runs cleanup
code. Java divides exceptions into checked (must be caught or declared) and unchecked
(runtime) exceptions. Checked exceptions (subclasses of Exception excluding
RuntimeException ) are caught at compile time 9 ; e.g., IOException must be handled.
Unchecked exceptions (subclasses of RuntimeException , like NullPointerException )
need not be explicitly caught. Using PreparedStatement in JDBC (see below) is an example of
catching SQL exceptions.
try {
int result = 10 / x;
1
} catch (ArithmeticException e) {
System.out.println("Division by zero!");
} finally {
System.out.println("Cleanup if needed");
}
Java Collections Framework
• Core Interfaces: The Java Collections Framework provides common data structures via
interfaces:
• Collection<E> : root interface for collections of objects.
• List<E> : ordered collections (can have duplicates). Implementations include ArrayList ,
LinkedList , Vector .
• Set<E> : unordered collections with no duplicates. Implementations: HashSet ,
LinkedHashSet , TreeSet .
• Queue<E> : ordered FIFO collections. Implementations: LinkedList , ArrayDeque ,
PriorityQueue .
• Map<K,V> : key–value mappings. Implementations: HashMap , TreeMap , LinkedHashMap ,
ConcurrentHashMap , etc. (Note: Map is not a Collection ).
• List vs LinkedList: An ArrayList uses a dynamic array internally. It provides fast random
access (get by index is O(1)) but slow insertions/removals in the middle (O(n) due to shifting) 10
11 . A LinkedList uses a doubly linked list: insertions/removals are cheap (O(1) if position
known), but random access is slow (O(n) to traverse) 10 11 . In practice:
• Use ArrayList when you need fast access and mostly append operations.
• Use LinkedList when you frequently add/remove from ends or middle and don’t need fast
random access.
• Both implement List . Additionally, LinkedList also implements Deque , so it supports
queue/deque operations.
Feature ArrayList LinkedList
Data structure Resizable array Doubly-linked list
Access time Fast O(1) random access Slow O(n) access (traverse nodes)
Insert/Delete at index Slow (elements shifted) Fast if position known (change links)
Memory overhead Lower (just array) Higher (nodes have pointers)
Implements List List , Deque
10 11
• Map Implementations: HashMap (hash table) provides O(1) average-time get/put , but no
ordering 12 13 . It allows one null key. TreeMap (red-black tree) maintains keys in sorted
order (natural order or via comparator) and offers O(log n) operations 14 . It does not allow
null keys. Example:
2
Map<String,Integer> hashMap = new HashMap<>();
Map<String,Integer> treeMap = new TreeMap<>();
hashMap.put("b", 2);
treeMap.put("a", 1);
treeMap.put("b", 2);
// Iterating hashMap (unordered), treeMap (sorted by key)
• Other Collections: HashSet vs TreeSet mirror HashMap vs TreeMap behavior (unsorted
vs sorted, unique elements). PriorityQueue implements Queue with elements ordered by
natural order or custom comparator. For thread-safety, use concurrent collections (e.g.
ConcurrentHashMap , CopyOnWriteArrayList ) 15 .
Java Streams & Lambda Expressions
• Lambda Expressions: Introduced in Java 8, lambdas enable passing behavior (functions) as
method arguments. A lambda is a compact way to implement a functional interface (an interface
with one abstract method). For example, (x,y) -> x+y is a lambda expression for an
interface like BiFunction<Integer,Integer,Integer> . Lambdas make code concise
(replacing many anonymous classes) 16 . They are often used with the Streams API.
• Streams API: A Stream is a pipeline of data (from a collection, array, etc.) that supports
functional-style operations like filter , map , reduce , and collect . Streams do not
modify the source; they apply operations to generate a result. For example, to double even
numbers in a list:
List<Integer> result = numbers.stream()
.filter(e -> e % 2 == 0)
.map(e -> e * 2)
.collect(Collectors.toList());
Here filter selects elements, map transforms them, and collect gathers results into a
list 17 . Java streams enable concise, readable data processing pipelines. They support parallel
execution ( parallelStream() ) and lazy evaluation (intermediate operations are evaluated
on-demand) 18 .
• Functional Interfaces: Common ones include Consumer<T> (accepts T, returns void),
Function<T,R> (maps T to R), Predicate<T> (boolean test), and Supplier<T> . For
example, list.forEach(x -> System.out.println(x)); uses a Consumer . Method
references ( String::length ) are shorthand lambdas.
Multithreading & Concurrency
• Threads vs Runnable: In Java, you create a new thread by either subclassing Thread or
implementing Runnable . The Runnable interface has a single run() method. You can
pass a Runnable to a Thread constructor and call start() to execute in a new thread 19 .
Alternatively, extend Thread and override run() 20 . Example:
3
// Using Runnable
class MyTask implements Runnable {
public void run() { /* code */ }
}
new Thread(new MyTask()).start();
// Extending Thread
class MyThread extends Thread {
public void run() { /* code */ }
}
new MyThread().start();
• Synchronization: When multiple threads access shared data, use synchronization to avoid race
conditions. Java provides the synchronized keyword (methods or blocks), locks
( ReentrantLock ), and atomic variables ( AtomicInteger , etc.). Also, high-level utilities like
CountDownLatch , Semaphore , and the java.util.concurrent library help manage
concurrency.
• Executors & Futures: Instead of manually creating Thread objects, use ExecutorService
(thread pools) from java.util.concurrent . For example:
ExecutorService exec = Executors.newFixedThreadPool(4);
Future<Integer> future = exec.submit(() -> {
// long-running computation
return 42;
});
Here submit() takes a Callable (lambda) that returns a result. It runs in a thread and
returns a Future representing the pending result 21 22 . You can use future.get() to
retrieve the result (blocking if necessary). Executors cleanly manage threads and tasks, and
Future enables asynchronous computation. The concurrency utilities also include thread-safe
collections (e.g., ConcurrentHashMap , CopyOnWriteArrayList ) and higher-level constructs
(e.g., ForkJoinPool ) 15 .
• Example – Thread Pool:
ExecutorService pool = Executors.newSingleThreadExecutor();
Callable<Integer> task = () -> { Thread.sleep(1000); return 123; };
Future<Integer> f = pool.submit(task);
System.out.println("Result: " + f.get()); // waits for task
pool.shutdown();
4
Data Structures & Algorithms in Java
• Common Data Structures (Java Collections and custom):
• Stack: Use Deque<E> (e.g. ArrayDeque ) or the legacy Stack<E> . Both support push() ,
pop() , peek() . Deque is preferred (LIFO via addFirst/removeFirst ) 23 .
• Queue: Use Queue<E> interface (e.g. LinkedList , ArrayDeque ) for FIFO; or
PriorityQueue for a priority-based queue.
• Linked List: Use java.util.LinkedList<E> (doubly linked). You can also implement a
custom singly linked list with node classes for practice.
• Trees: Use TreeSet<E> or TreeMap<K,V> for balanced BST functionality. For explicit binary
tree operations, write a TreeNode class and implement traversals (preorder, inorder, etc.). For
example, a basic tree node: class Node { int val; Node left, right; } .
• Graphs: Represent a graph with adjacency lists, e.g., a Map<Vertex, List<Vertex>> or
List<List<Integer>> (for numeric nodes). Perform BFS/DFS with queues or recursion as
usual.
• Algorithms:
• Sorting: Java’s Collections.sort(List) uses a tuned merge sort (TimSort) for objects 24 .
It runs in O(n log n) time. For arrays, Arrays.sort uses dual-pivot quicksort for primitives and
TimSort for objects. You can also implement classic sorts (bubble, quicksort, merge sort) if asked.
• Searching: Use Collections.binarySearch(list, key) on a sorted list (O(log n)) 25 . For
unsorted data, linear search is O(n). For example:
int idx = Collections.binarySearch(sortedList, target);
if (idx >= 0) { /* found */ }
• Example – Stack usage:
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10); stack.push(20);
int top = stack.pop(); // 20
int peek = stack.peek(); // 10
• Complexities: Typically, mention big-O costs of operations (e.g., add/remove at front vs back,
search costs, etc.). Knowing algorithmic complexity for common operations (O(1) vs O(n) vs O(n
log n)) is important for interviews.
Java 17+ Features
• Records (Java 16/17): A record is a special final class for immutable data carriers, reducing
boilerplate. Defining record Point(int x, int y){} automatically creates private final
fields, accessors, equals() , hashCode() , and toString() 26 . Records are transparent
holders for immutable data 26 .
5
• Sealed Classes (Java 17): A sealed class or interface restricts which types can extend/
implement it. For example:
public abstract sealed class Shape permits Circle, Square, Rectangle {
… }
Here only Circle , Square , and Rectangle can extend Shape . This improves control over
class hierarchies 27 .
• Pattern Matching for instanceof (Java 16): Simplifies type checks and casts. Instead of:
if (obj instanceof String) {
String s = (String) obj;
// use s
}
You can write:
if (obj instanceof String s) {
// use s directly
}
This binds obj to s if the check succeeds, making code more concise 28 .
• Text Blocks (Java 15): Multi-line string literals using triple quotes ( """ ). They allow writing
strings like JSON or HTML without messy escape sequences 29 . Example:
String html = """
<html>
<body>
<p>Hello</p>
</body>
</html>
""";
This was introduced by JEP 378 29 .
• Other Enhancements: Later Java versions (17+) added many improvements: new switch
expressions, new utility methods ( String.strip() , isBlank() , repeat() , etc.),
enhanced Pattern matching (for switch in preview), and better garbage collectors (e.g.
ZGC). Staying up-to-date means learning the features of Java 17, 18, 19, and so on as needed.
6
Java for Application Development
• JDBC (Database Connectivity): Java uses JDBC to connect to databases. Key steps: load a driver,
get a Connection (via DriverManager.getConnection(url, user, pass) ), create a
Statement or PreparedStatement , execute SQL, and process ResultSet 30 . Use try-
with-resources to auto-close connections/statements. For example:
String sql = "INSERT INTO users(name,age) VALUES(?,?)";
try (Connection con = DriverManager.getConnection(url,user,pass);
PreparedStatement ps = con.prepareStatement(sql)) {
ps.setString(1, "Alice");
ps.setInt(2, 30);
ps.executeUpdate();
}
PreparedStatement is preferred for repeated queries and safety: it is precompiled (faster)
and protects against SQL injection 30 31 .
• Spring Boot: A framework for quickly building Java applications (often web services). Spring Boot
uses convention-over-configuration and auto-configuration. Main features:
• Starter Application: Annotate your main class with @SpringBootApplication , which is a
convenience meta-annotation combining @Configuration , @EnableAutoConfiguration ,
and @ComponentScan 32 . For example:
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args);
}
}
This sets up the application context and starts an embedded server (e.g., Tomcat) without XML
configuration.
• Dependency Injection & Annotations: Use annotations like @RestController (to define a
web controller), @RequestMapping / @GetMapping (to map HTTP routes), and @Autowired
(to inject beans) to build your application. Spring Boot automatically configures beans based on
what's on the classpath 32 33 .
• Configuration: Spring Boot can be configured via application.properties /
application.yml or annotations. It provides a flexible annotation-driven model (e.g.
@Bean , @Value , @ConfigurationProperties ).
• Development Convenience: Spring Boot embeds a server (no need for external Tomcat) and
provides “starter” dependencies (e.g. spring-boot-starter-web ) so adding features is
simple. It “looks at your classpath” and auto-adds beans and settings (e.g. enabling MVC,
security, etc. if relevant) 33 . This lets developers focus on business logic.
Example: A simple REST controller in Spring Boot:
7
@RestController
public class HelloController {
@GetMapping("/")
public String greet() {
return "Hello, Spring Boot!";
}
}
Running the app and accessing http://localhost:8080/ would return the greeting. Spring Boot
manages the server and routes automatically.
Java Interview Preparation
• Coding Patterns: Practice common algorithms and data structure problems using Java. Typical
tasks include:
• String/Array Problems: e.g. reverse a string (use a loop or StringBuilder ) 34 , check for
palindromes, merge sorted arrays, find duplicates, etc.
• Math/Logic Puzzles: e.g. swap two numbers without a temp variable (using addition/
subtraction) 35 , compute factorial, Fibonacci, prime check.
• Data Structures: manipulate lists and trees (e.g. reverse a linked list, traverse a binary tree,
detect cycles in a graph).
• Concurrency: e.g. write a deadlock scenario (two threads locking resources in opposite order).
• Collection Usage: e.g. sort a collection, remove duplicates, count frequencies. Many interview
questions (especially MCQs) test knowledge of core collections, generics, and language features.
• Design Patterns: Understand creational patterns (Singleton, Factory), structural (Adapter,
Decorator), behavioral (Observer). Often you may be asked to identify or implement a simple
pattern.
• Java-specific MCQs: Be ready to answer conceptual multiple-choice questions on topics like:
• OOP vs procedural, static/dynamic binding, equals() vs == , string immutability, autoboxing,
generics wildcards, exception hierarchy, threading and synchronization nuances, garbage
collection, and Java 8+ features.
• E.g., “How many primitive types are there?”, “What’s the difference between HashMap and
TreeMap ?”, “What does volatile mean?”. (Online resources like InterviewBit and
GeeksforGeeks provide lists of Java MCQs for practice.)
• Behavioral Questions: In interviews, you may be asked about teamwork, challenges, or project
experiences. Use the STAR method (Situation, Task, Action, Result) to structure responses. For
example, describe a challenging bug (Situation), what your responsibility was (Task), how you
diagnosed/fixed it (Action), and what the outcome was (Result). Practice articulating your Java
projects: what you built, which frameworks you used, and the impact. Demonstrating clear
communication and problem-solving is as important as technical knowledge.
• Continuous Learning: Finally, interviews often test up-to-date knowledge. Mention any recent
Java versions or tools you use (e.g. Java 17 features, or familiarity with build tools like Maven/
8
Gradle). Show enthusiasm for learning new features (e.g. streams, modules, etc.), as this reflects
well in a technical interview.
Sources: Authoritative tutorials and references were used to ensure accuracy and currency in this
overview 36 3 7 9 10 12 18 19 21 23 24 26 27 28 30 32 34 35 , reflecting up-to-date
Java standards.
1 2 36 Primitive Data Types (The Java™ Tutorials > Learning the Java Language > Language Basics)
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
3 4 5 6 OOPs in Java: Encapsulation, Inheritance, Polymorphism, Abstraction
https://beginnersbook.com/2013/03/oops-in-java-encapsulation-inheritance-polymorphism-abstraction/
7 8 Difference Between Abstract Class and Interface in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/difference-between-abstract-class-and-interface-in-java/
9 Java Checked vs Unchecked Exceptions - GeeksforGeeks
https://www.geeksforgeeks.org/java/java-checked-vs-unchecked-exceptions/
10 11 ArrayList vs LinkedList in Java - GeeksforGeeks
https://www.geeksforgeeks.org/java/arraylist-vs-linkedlist-java/
12 13 14 HashMap vs TreeMap in Java | Stack a Byte
https://stackabyte.com/tutorials/java/java-hashmap-treemap-comparison
15 Collections in Java - Everything You MUST Know | DigitalOcean
https://www.digitalocean.com/community/tutorials/collections-in-java-tutorial
16 Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
17 18 Using Java Streams in Java 8 and Beyond | JRebel by Perforce
https://www.jrebel.com/blog/java-streams-in-java-8
19 20 Defining and Starting a Thread (The Java™ Tutorials > Essential Java Classes > Concurrency)
https://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html
21 22 Guide to java.util.concurrent.Future | Baeldung
https://www.baeldung.com/java-future
23 Java Deque vs. Stack | Baeldung
https://www.baeldung.com/java-deque-vs-stack
24 25Collections (Java(TM) ME Connected Limited Device Configuration, Version 8 (JSR360 Final
Release))
https://docs.oracle.com/javame/8.0/api/cldc/api/java/util/Collections.html
26 27 28 29 Java 17 New Features: Here's a Juicy Update in JDK17
https://www.ideas2it.com/blogs/java-17-heres-a-juicy-update-on-everything-thats-new
30 31 Using Prepared Statements (The Java™ Tutorials > JDBC Database Access > JDBC Basics)
https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
32 33 Getting Started | Building an Application with Spring Boot
https://spring.io/guides/gs/spring-boot/
34 35 Top Java Coding Interview Questions (With Answers) | DigitalOcean
https://www.digitalocean.com/community/tutorials/java-programming-interview-questions