Made with ScholarlyMake flashcards like these from your own notes
Question:What is Java primarily described as in terms of its typing, orientation, and platform independence?
Answer:Java is a strongly typed, object-oriented, platform-independent language compiled to bytecode.
Question:Describe the complete compilation and execution process of a Java program from source code.
Answer:Source (.java) → javac compiler → Bytecode (.class) → JVM interprets/JIT compiles → Machine code.
Question:What components are included in the Java Development Kit (JDK)?
Answer:JDK includes compiler (javac), debugger, javadoc, and JRE for developers.
Question:What does the Java Runtime Environment (JRE) provide for running Java programs?
Answer:JRE provides JVM plus standard libraries for running programs.
Question:How does the Java Virtual Machine (JVM) execute bytecode and ensure platform neutrality?
Answer:JVM executes bytecode and is platform-specific, but bytecode remains platform-neutral.
Question:What role does the Just-In-Time (JIT) Compiler play in JVM performance?
Answer:JIT compiles hot bytecode to native machine code at runtime for speed.
Question:What are the hierarchical classloaders in Java and their order?
Answer:Bootstrap → Extension → Application classloaders load .class files into JVM.
Question:What is bytecode in the context of Java compilation?
Answer:Bytecode is intermediate, platform-independent code, neither machine code nor source code.
Question:Why does 'Write Once Run Anywhere' refer specifically to bytecode in Java?
Answer:Bytecode is platform-independent; JVM is platform-dependent for different OS like Windows/Linux.
Question:What is the size and range of the byte primitive data type in Java?
Answer:Byte is 1 byte, range -128 to 127.
Question:What are the size and range limits for the short primitive type in Java?
Answer:Short is 2 bytes, range -32,768 to 32,767.
Question:Specify the size and range of the int primitive data type in Java.
Answer:Int is 4 bytes, range -2³¹ to 2³¹-1.
Question:How do you denote a long literal in Java, and what is its size?
Answer:Long is 8 bytes; use suffix L like 100L.
Question:What suffix is required for float literals in Java, and what is its precision?
Answer:Float is 4 bytes, single precision; use suffix F.
Question:What is the default floating-point type in Java and its size?
Answer:Double is 8 bytes, double precision; default for decimals.
Question:How does the char primitive differ from C in terms of size and encoding in Java?
Answer:Char is 2 bytes, Unicode (0 to 65535); unlike C's 1 byte.
Question:What values can the boolean primitive hold, and what is its conceptual size?
Answer:Boolean is true/false; size JVM-dependent, conceptually 1 bit.
Question:Name all the wrapper classes for Java primitive types.
Answer:Integer, Long, Double, Float, Character, Boolean, Byte, Short.
Question:What is autoboxing in Java, and provide an example of its behavior?
Answer:Autoboxing converts int to Integer automatically; unboxing reverses it.
Question:Explain Integer caching in Java with specific range and example outcomes.
Answer:Java caches Integers from -128 to 127; a=127; b=127; a==b true, but 128 false.
Question:What are widening and narrowing type casts in Java, including safety implications?
Answer:Widening: implicit, safe (int→long); Narrowing: explicit, may lose data (double→int).
Question:What is the result of adding two char primitives in Java, and how to concatenate instead?
Answer:'A' + 'B' = 131 (int); use String.valueOf() or empty string for concatenation.
Question:Where are String literals stored in Java, and what happens on reassignment?
Answer:Strings immutable, stored in String Constant Pool (SCP) in heap; String s="hello" checks/reuses SCP.
Question:How does new String("hello") differ from String s = "hello" in terms of object creation?
Answer:new String("hello") always creates new heap object, bypassing SCP; literal reuses SCP if exists.
Question:What does the intern() method do for String objects in Java?
Answer:intern() forces a String object to use the SCP version.
Question:Compare the properties of String, StringBuffer, and StringBuilder classes.
Answer:String: immutable, thread-safe, SCP, new object per mod. StringBuffer: mutable, synchronized/thread-safe, slower. StringBuilder: mutable, not thread-safe, faster.
Question:List key String methods for manipulation, case conversion, searching, and splitting.
Answer:length(), charAt(i), substring(start,end), indexOf(), lastIndexOf(), replace(), toUpperCase(), toLowerCase(), trim(), split(), equals(), equalsIgnoreCase(), compareTo(), contains(), startsWith(), endsWith(), isEmpty(), toCharArray().
Question:What is String.format used for, and provide its syntax example?
Answer:String.format("%d %s", num, str) creates formatted strings.
Question:Why should you prefer StringBuilder over + for string concatenation in loops?
Answer:+ creates new String objects each time; StringBuilder mutable avoids this.
Question:Why is "hello".equals(s) safer than s.equals("hello") for null safety?
Answer:Avoids NullPointerException if s is null; always put known value first.
Question:How is encapsulation achieved in Java, and what are its benefits?
Answer:Binding data (fields) and methods via private fields + public getters/setters; benefits data hiding, validation, loose coupling.
Question:What is the JavaBeans convention for fields, getters, and setters?
Answer:Private fields, public getters (getXxx/isXxx for boolean), public setters (setXxx).
Question:How does Java handle class inheritance and multiple inheritance?
Answer:'extends' keyword; single class inheritance only (prevents diamond); multiple via interfaces.
Question:What is the root class of all Java classes, and what relationship does inheritance represent?
Answer:Object class is root; IS-A relationship.
Question:What does the super keyword accomplish in method and constructor calls?
Answer:super.method() calls parent method; super() calls parent constructor (first line).
Question:Are constructors inherited in Java subclasses?
Answer:Constructors not inherited, but parent constructor always called explicitly or implicitly.
Question:Distinguish between method overloading and overriding in terms of timing and resolution.
Answer:Overloading: compile-time/static, same name different params. Overriding: runtime/dynamic, subclass redefines parent.
Question:What is upcasting and downcasting in Java, including risks?
Answer:Upcasting: Parent ref = Child obj (implicit). Downcasting: Child ref = (Child) Parent (explicit, ClassCastException risk).
Question:When is the instanceof operator used in Java polymorphism?
Answer:instanceof checks if object is instance of class/interface before downcasting.
Question:What defines an abstract class versus an interface in Java?
Answer:Abstract class: 0-100% abstract, has constructor/instance vars/any modifier, single inheritance. Interface: 100% abstract pre-J8, no ctor/instance vars, public default, multiple inheritance.
Question:When should you use abstract class versus interface for shared behavior?
Answer:Abstract class for shared base behavior; interface for unrelated classes sharing capability like Serializable.
Question:Can abstract classes have concrete methods or be instantiated indirectly?
Answer:Yes concrete methods; no direct instantiate, but anonymous subclass possible. Interfaces Java8+ default concrete.
Question:What are the key characteristics of Java constructors?
Answer:No return type (not void), same name as class, called with 'new'.
Question:Under what condition does Java provide a default constructor?
Answer:Auto-provided only if no constructors written.
Question:How do you implement copy constructors in Java since they are not built-in?
Answer:Manually write taking same class object as argument, unlike C++.
Question:What is constructor chaining in Java using this() and super()?
Answer:this() calls another same-class ctor; super() calls parent ctor.
Question:What is the initialization order for static blocks, instance blocks, and constructors?
Answer:Static blocks → Instance blocks → Constructor (parent to child).
Question:What happens to the default constructor if you define any parameterized constructor?
Answer:Java does not provide default; must explicitly write if needed.
Question:What defines a static variable and method in Java?
Answer:Static variable: one copy shared by instances, class-owned. Static method: no 'this', no instance access, callable without object.
Question:When does a static block execute, and what is its purpose?
Answer:Runs once on class load before constructors; for static initialization.
Question:How do static nested classes differ from inner (non-static) classes regarding outer class access?
Answer:Static nested: exists without outer instance, no outer instance access. Inner: requires outer instance, has outer access.
Question:What restrictions apply to final variables, methods, and classes in Java?
Answer:Final var: constant post-init. Final method: no override. Final class: no extend (e.g., String).
Question:What is a blank final variable, and where must it be assigned?
Answer:Final var declared without value; assigned in constructor.
Question:Why can you modify contents of a final reference variable like a List?
Answer:Reference cannot point to new object, but object contents changeable (e.g., list.add(5) allowed).
Question:How do method overloading and overriding differ in binding time, parameters, return type, access, exceptions, and static handling?
Answer:Overload: compile bind, params differ, return any, access any, exceptions any. Override: runtime bind, params same, return same/covariant, access not restrictive, checked exceptions not broader, static/private/final not overridable (hide).
Question:What is the purpose of the @Override annotation in Java?
Answer:@Override: compiler verifies valid override.
Question:Classify exceptions as checked or unchecked with examples.
Answer:Checked: must catch/declare (IOException, SQLException, ClassNotFound). Unchecked: RuntimeException subs (NullPointer, ArrayIndexOutOfBounds, ClassCast).
Question:What always executes in try-catch-finally, and what exceptions prevent it?
Answer:Finally always runs (even return in try), except System.exit() or JVM crash.
Question:How does try-with-resources simplify resource management in Java 7+?
Answer:Auto-closes AutoCloseable/Closeable; e.g., try (FileReader fr = new FileReader(f)) {}.
Question:What distinguishes throw from throws in Java exception handling?
Answer:throw: explicitly throws exception. throws: declares method may throw.
Question:How do you create custom checked versus unchecked exceptions in Java?
Answer:Extend Exception for checked; RuntimeException for unchecked.
Question:What is exception chaining and exception propagation priority in return scenarios?
Answer:new RuntimeException("msg", original) preserves cause. Finally return overrides try return.
Question:Describe the Collections Framework hierarchy starting from Iterable.
Answer:Iterable → Collection → {List, Set, Queue}; Map separate.
Question:What are the key properties of ArrayList in terms of operations and thread-safety?
Answer:Dynamic array, O(1) access, O(n) middle insert/delete, not synchronized, allows null.
Question:Compare performance and usage of LinkedList versus ArrayList.
Answer:LinkedList: doubly linked, O(n) access, O(1) ends add/remove, List+Deque.
Question:Why is Vector considered legacy compared to ArrayList?
Answer:Vector like ArrayList but synchronized/thread-safe; prefer ArrayList + manual sync.
Question:What is Stack in Java collections, and what modern alternative is recommended?
Answer:LIFO extends Vector (legacy); prefer ArrayDeque.
Question:Describe HashSet properties regarding duplicates, order, nulls, and operations.
Answer:No duplicates, HashMap-backed, O(1) ops, no order, one null allowed.
Question:How does LinkedHashSet differ from HashSet?
Answer:Like HashSet but maintains insertion order.
Question:What defines TreeSet in terms of ordering, performance, and null handling?
Answer:Sorted natural/Comparator, O(log n), no null, NavigableSet.
Question:Specify HashMap properties for keys/values, ordering, thread-safety, and performance.
Answer:Key-value O(1), one null key/multiple null values, not ordered, not thread-safe.
Question:What enhancements do LinkedHashMap and TreeMap provide over HashMap?
Answer:LinkedHashMap: + insertion order. TreeMap: sorted keys O(log n), no null key, NavigableMap.
Question:Why replace Hashtable with modern alternatives?
Answer:Legacy like HashMap but sync, no nulls; use ConcurrentHashMap.
Question:What is PriorityQueue's default structure, operations, and ordering?
Answer:Min-heap default, O(log n) add/remove, no null, natural/Comparator.
Question:What makes ArrayDeque efficient for queues compared to Stack or LinkedList?
Answer:Double-ended queue, faster than Stack/LinkedList for LIFO/FIFO.
Question:Distinguish Comparable from Comparator for sorting in Java collections.
Answer:Comparable: natural order compareTo() in class. Comparator: external compare() separate class, for unmodifiable or multi-sort.
Question:Name key methods in Collections utility class for list manipulation.
Answer:sort(), shuffle(), reverse(), min(), max(), frequency(), unmodifiableList(), synchronizedList().
Question:List essential methods for Iterator and ListIterator in Java.
Answer:Iterator: hasNext(), next(), remove(). ListIterator: + hasPrevious(), previous(), add(), set().
Question:What happens with fail-fast versus fail-safe iterators during collection modification?
Answer:Fail-fast (ArrayList): ConcurrentModificationException if modified. Fail-safe (CopyOnWriteArrayList): safe.
Question:Explain HashMap internal structure, collision resolution, and Java 8+ optimization.
Answer:Array of buckets, hashCode() bucket, equals() collision. Java8+: chain >8 becomes Red-Black Tree.
Question:What benefits do generics provide for collections and methods in Java?
Answer:Type-safe collections/methods; errors at compile time, not runtime.
Question:Define bounded type parameters and wildcard bounds in Java generics.
Answer:: T Number/subclass. <?> any, <? extends T> upper, <? super T> lower (PECS).
Question:What is type erasure in Java generics, and its runtime implication?
Answer:Generic info removed at runtime; List and List both List.
Question:Why are generic arrays invalid, and what alternatives exist for primitives?
Answer:new T[10] not allowed; primitives like List invalid, use List .
Question:List the four methods for creating threads in Java, noting flexibility.
Answer:1. Extend Thread override run() inflexible. 2. Implement Runnable. 3. Callable with Future. 4. ExecutorService pools.
Question:Outline the complete thread lifecycle states in Java.
Answer:NEW → RUNNABLE → RUNNING → BLOCKED/WAITING/TIMED_WAITING → TERMINATED.
Question:What is the difference between start() and run() for Java threads?
Answer:start() creates new thread + calls run(); run() alone executes in current thread.
Question:How does Thread.sleep(ms) behave regarding locks and exceptions?
Answer:Pauses current thread, does not release lock, InterruptedException handled.
Question:Explain wait(), notify(), notifyAll(), and join() behaviors and requirements.
Answer:wait(): release lock wait synchronized obj. notify(): wake one. notifyAll(): all. join(): current waits for thread finish.
Question:What does yield() do in Java multithreading?
Answer:Hints scheduler to give CPU to same-priority threads, not guaranteed.
Question:Compare synchronized method and synchronized block for thread safety.
Answer:Synchronized method: lock 'this' one thread. Block: granular synchronized(obj) {}.
Question:What does volatile ensure for variables in multithreading?
Answer:Read/write to main memory not thread cache; no atomicity.
Question:Describe deadlock scenario and prevention strategies in Java.
Answer:A holds X waits Y, B holds Y waits X. Prevent: lock order, try-lock timeout, avoid nested.
Question:Differentiate livelock, starvation from deadlock in multithreading.
Answer:Livelock: respond no progress. Starvation: low prio no CPU. Deadlock: blocked forever.
Question:Why is i++ not atomic even with volatile, and what to use instead?
Answer:Volatile visibility only; i++ read-modify-write 3 ops. Use AtomicInteger.
Question:What are lambda expressions in Java 8, and their syntax?
Answer:Anonymous functions: (params) -> expr or {stmts}.
Question:What defines a functional interface for lambdas in Java?
Answer:Interface with exactly one abstract method; @FunctionalInterface verifies.
Question:Name built-in functional interfaces in Java 8 with signatures.
Answer:Predicate (T→bool), Function (T→R), Consumer (T→void), Supplier (void→T), BiFunction .
Question:What is Stream API in Java 8, and its evaluation strategy?
Answer:Pipeline ops on element sequence; lazy eval, intermediates not exec til terminal.
Question:Classify Stream API operations as intermediate or terminal with examples.
Answer:Intermediate lazy: filter map flatMap distinct sorted peek limit skip. Terminal eager: collect forEach reduce count min max findFirst anyMatch allMatch noneMatch.
Question:What error occurs if you reuse a Stream after terminal operation?
Answer:IllegalStateException; cannot reuse post-terminal.
Question:How do parallel streams work, and potential drawbacks?
Answer:stream.parallel() uses ForkJoinPool; may not faster due overhead.
Question:What problem does Optional solve in Java 8, and creation methods?
Answer:Container may/not hold non-null, avoids NPE. of(val) throws if null, ofNullable allows null, empty().
Question:List key methods for Optional handling presence and transformation.
Answer:isPresent(), get(), orElse(), orElseGet(), map(), filter(), ifPresent().