java one liner revision
Sure! Here’s a crisp and focused list of Java Interview One-Liners for fast recall and last-minute revision — perfect before interviews.
⚡ Java Interview One-Liners (Fast Recall)
🔹 General Core Java
- Java is platform-independent due to the JVM.
- Java is pass-by-value, even for objects (references are passed by value).
- String is immutable and stored in the String pool.
- StringBuilder is not thread-safe; StringBuffer is.
- == checks reference equality, .equals() checks content equality.
- Wrapper classes are immutable and provide utility methods.
- ArrayList is backed by a dynamic array, LinkedList by nodes.
🔹 OOP & Class Basics
- Java supports single inheritance only (classes).
- Interfaces support multiple inheritance of type.
- Constructors can be overloaded, not overridden.
- A class with at least one abstract method must be abstract.
- Polymorphism = Overloading (compile-time) + Overriding (runtime).
🔹 Exception Handling
- Checked exceptions must be handled or declared.
- Unchecked exceptions are RuntimeException and its subclasses.
- finally block always executes, even after return.
🔹 Collections
- HashMap allows one null key and multiple null values.
- Hashtable is synchronized, HashMap is not.
- TreeMap maintains sorted order, LinkedHashMap maintains insertion order.
- Set doesn’t allow duplicate elements.
- List allows duplicates and nulls.
🔹 Multithreading
- synchronized ensures mutual exclusion.
- volatile ensures visibility of changes across threads.
- Thread.sleep() pauses thread, wait() releases lock.
- Use ExecutorService to manage thread pools.
🔹 Java 8 & Functional
- Optional helps avoid NullPointerException.
- Lambda expression is a shorter way to implement functional interfaces.
- Stream API supports lazy and parallel processing.
- Functional interfaces have exactly one abstract method.
- Common functional interfaces: Predicate, Function, Consumer, Supplier.
🔹 Keywords & Concepts
- final → cannot change (value, method override, class extend).
- static → belongs to class, not instance.
- this → current object; super → parent object.
- transient → skips field in serialization.
- instanceof → checks type at runtime.
🔹 Memory & JVM
- Heap stores objects; stack stores method calls and local variables.
- Garbage Collection reclaims unreachable objects.
- System.gc() is a suggestion, not a command.
- ClassLoader loads .class files into JVM.
🔹 Design Patterns
- Singleton: One instance per JVM.
- Factory: Delegates object creation to subclasses.
- Observer: Notify observers on state change.
- Decorator: Add behavior dynamically.
🔹 Miscellaneous
- Comparable → natural ordering; Comparator → custom ordering.
- hashCode() + equals() → used in HashSet, HashMap.
- Serialization allows object to be converted to byte stream.
- enum is a special class for constants.
- JAR = Java Archive, WAR = Web Application Archive.
Absolutely! Here’s an extended list of Java Interview One-Liners, covering any missed or often-overlooked areas in interviews — especially useful for experienced developers (3–6 years):
⚡ Extended Java Interview One-Liners (Complete Recall)
🔹 JVM & Memory
- PermGen was replaced by Metaspace in Java 8.
- StackOverflowError = too deep recursion; OutOfMemoryError = heap full.
- Garbage Collector types: Serial, Parallel, CMS (deprecated), G1 (default).
- Java uses just-in-time (JIT) compilation to optimize performance.
🔹 Keywords & Concepts
- abstract → method without body or class with at least one abstract method.
- native → method implemented in non-Java (native) code.
- strictfp → enforces IEEE floating-point calculations.
- default method in interfaces was introduced in Java 8.
- sealed classes (Java 15+) restrict which classes can extend them.
🔹 Strings
- "abc" is a string literal, new String("abc") creates a new object in heap.
- Interned strings refer to values in the String constant pool.
- String.join(), repeat(), strip() are added in Java 11.
🔹 Collections (Advanced)
- ConcurrentHashMap divides map into segments (Java 7), bucket-wise locking (Java 8).
- EnumMap is optimized for enum keys.
- WeakHashMap allows garbage collection of keys when not referenced elsewhere.
- CopyOnWriteArrayList is good for frequent reads, rare writes.
🔹 Synchronization & Concurrency
- ThreadLocal provides thread-confined variables.
- Callable returns a result and can throw exception.
- Future.get() blocks until the result is available.
- CountDownLatch allows threads to wait until latch reaches 0.
- CyclicBarrier is reusable, unlike CountDownLatch.
🔹 Streams (Java 8+)
- Streams are lazy and don’t execute until a terminal operation is called.
- Intermediate ops: map, filter, sorted, distinct
- Terminal ops: collect, forEach, count, reduce
🔹 Optional (Java 8)
- Optional.empty() → returns empty Optional.
- Optional.ofNullable(value) → handles null safely.
- orElse() vs orElseGet() — former always evaluates, latter is lazy.
🔹 Functional Programming
- Method reference: ClassName::methodName
- Collectors.toList(), toSet(), groupingBy(), partitioningBy()
- flatMap() is used to flatten nested streams
🔹 Exception Handling (Deep)
- Multi-catch introduced in Java 7: catch (IOException | SQLException e)
- try-with-resources auto-closes resources implementing AutoCloseable
- Custom exceptions should extend Exception or RuntimeException.
🔹 I/O & NIO
- BufferedReader, BufferedWriter wrap I/O for performance.
- Files.readAllLines(path) reads all lines as List.
- Paths.get() + Files = Java NIO (non-blocking I/O)
🔹 Serialization
- transient → field not serialized.
- serialVersionUID ensures compatibility during deserialization.
- Externalizable gives full control over what to serialize.
🔹 Reflection & Annotations
- Reflection allows inspection and modification of classes at runtime.
- Used in frameworks like Spring, Hibernate.
- @Retention(RUNTIME) → annotation is available at runtime.
- @Target(ElementType.METHOD) → restricts where annotation can be applied.
🔹 Java Modules (Java 9+)
- Defined via module-info.java
- exports exposes packages, requires includes dependencies.
- Helps with encapsulation and versioning in large applications.
🔹 Streams vs Collections
- Collections are in-memory, eager, and mutable.
- Streams are computed on demand, lazy, and can be parallelized.
🔹 Lambdas vs Anonymous Class
- Lambdas have no state and are more concise.
- Lambdas capture effectively final variables only.
🔹 Common Tricky Facts
- Integer.valueOf() uses Integer cache between -128 to 127.
- final reference = cannot point elsewhere, but object state can change.
- HashSet uses HashMap internally.
- PriorityQueue does not guarantee order of iteration.
Absolutely! Let’s add even more expert-level Java one-liners that are frequently asked in interviews, especially for 3–6 years of experience in backend roles involving Java, Spring Boot, Microservices, and performance optimization.
⚡ More Java Interview One-Liners (Final Power Pack)
🔹 Spring Framework (if you’re using Spring/Spring Boot)
- @Component, @Service, @Repository, @Controller are stereotype annotations.
- @Autowired does dependency injection automatically.
- @Qualifier is used to resolve bean ambiguity.
- Spring beans are singleton by default.
- @Transactional ensures ACID properties for methods.
🔹 Microservices (Java/Spring)
- REST uses HTTP methods: GET, POST, PUT, DELETE.
- Use @RestController + @RequestMapping in Spring Boot for REST APIs.
- @PathVariable maps URL segments, @RequestParam maps query params.
- Circuit breakers (like Resilience4j) help avoid cascading failures.
- Service discovery is handled by tools like Eureka.
🔹 Spring Boot Extras
- application.properties / .yml contains configurable values.
- Embedded servers like Tomcat are used by default in Spring Boot.
- @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan
- Spring Boot follows convention over configuration.
🔹 Performance & Optimization
- Use StringBuilder in loops to avoid creating many string objects.
- Prefer ArrayList over LinkedList for fast random access.
- Minimize object creation in loops.
- Use equals() + hashCode() together to avoid duplicate keys in HashMap.
🔹 Java 8+ Enhancements (Misc)
- Optional.of() throws NullPointerException if input is null.
- Use Collectors.groupingBy() for classification/grouping.
- flatMap() converts Stream<Stream> → Stream
- Avoid null — prefer Optional.empty() over returning null.
- Use Comparator.comparing() + thenComparing() for multi-level sorting.
🔹 Garbage Collection & Memory
- GC cleans unreachable objects from heap.
- Objects are created in Young Gen, promoted to Old Gen if survived multiple GCs.
- Use -Xmx and -Xms to set heap size.
- Tools like VisualVM, JConsole, Flight Recorder monitor memory and GC.
🔹 Java Modules (Java 9+)
- module-info.java controls what’s exported and required.
- Helps in encapsulation, performance, and security.
- Replaces the monolithic JAR structure.
🔹 JDK Tools You Should Know
|
Tool |
Use |
|
javac |
Compile Java source code |
|
java |
Run compiled Java class |
|
jps |
Java process listing |
|
jstack |
Prints thread dump |
|
jmap |
Prints memory heap details |
|
jconsole |
Monitoring JVM in real time |
|
jvisualvm |
Profiling and memory analysis |
🔹 JDBC Quick Recall
- DriverManager handles JDBC drivers.
- Always close Connection, Statement, and ResultSet.
- Use PreparedStatement to prevent SQL Injection.
- Connection pooling improves performance (HikariCP, Apache DBCP).
🔹 Java Tips to Avoid Interview Mistakes
- Always override both equals() and hashCode() for custom objects used in collections.
- Avoid == for object comparison; use .equals().
- Remember: static methods can’t access instance variables directly.
- Exception hierarchy: Throwable → Error and Exception.
- Prefer final and immutable where possible for thread safety.
🔹 Real-World Project One-Liners
- Use DTO to transfer data between layers.
- Use Mapper classes to convert Entity ↔ DTO.
- In microservices, never expose database entities directly via REST APIs.
- Always handle timeouts, retries, and fallbacks in remote API calls.
✅ This cheat sheet is now interview-complete, covering:
- Core Java
- Java 8+
- Multithreading
- Collections
- JVM
- Exception handling
- OOP
- Spring + Spring Boot
- Microservices
- Performance
- Tooling
- well
Comments
Post a Comment