Logo/

Java Fundamentals

Log in

Made with ScholarlyMake flashcards like these from your own notes

Java Fundamentals

Questions and answers

104 cards
  1. 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.

  2. 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.

  3. Question:What components are included in the Java Development Kit (JDK)?

    Answer:JDK includes compiler (javac), debugger, javadoc, and JRE for developers.

  4. Question:What does the Java Runtime Environment (JRE) provide for running Java programs?

    Answer:JRE provides JVM plus standard libraries for running programs.

  5. 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.

  6. 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.

  7. Question:What are the hierarchical classloaders in Java and their order?

    Answer:Bootstrap → Extension → Application classloaders load .class files into JVM.

  8. Question:What is bytecode in the context of Java compilation?

    Answer:Bytecode is intermediate, platform-independent code, neither machine code nor source code.

  9. 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.

  10. Question:What is the size and range of the byte primitive data type in Java?

    Answer:Byte is 1 byte, range -128 to 127.

  11. 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.

  12. Question:Specify the size and range of the int primitive data type in Java.

    Answer:Int is 4 bytes, range -2³¹ to 2³¹-1.

  13. 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.

  14. 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.

  15. Question:What is the default floating-point type in Java and its size?

    Answer:Double is 8 bytes, double precision; default for decimals.

  16. 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.

  17. 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.

  18. Question:Name all the wrapper classes for Java primitive types.

    Answer:Integer, Long, Double, Float, Character, Boolean, Byte, Short.

  19. Question:What is autoboxing in Java, and provide an example of its behavior?

    Answer:Autoboxing converts int to Integer automatically; unboxing reverses it.

  20. 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.

  21. 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).

  22. 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.

  23. 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.

  24. 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.

  25. Question:What does the intern() method do for String objects in Java?

    Answer:intern() forces a String object to use the SCP version.

  26. 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.

  27. 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().

  28. Question:What is String.format used for, and provide its syntax example?

    Answer:String.format("%d %s", num, str) creates formatted strings.

  29. Question:Why should you prefer StringBuilder over + for string concatenation in loops?

    Answer:+ creates new String objects each time; StringBuilder mutable avoids this.

  30. 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.

  31. 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.

  32. Question:What is the JavaBeans convention for fields, getters, and setters?

    Answer:Private fields, public getters (getXxx/isXxx for boolean), public setters (setXxx).

  33. Question:How does Java handle class inheritance and multiple inheritance?

    Answer:'extends' keyword; single class inheritance only (prevents diamond); multiple via interfaces.

  34. Question:What is the root class of all Java classes, and what relationship does inheritance represent?

    Answer:Object class is root; IS-A relationship.

  35. Question:What does the super keyword accomplish in method and constructor calls?

    Answer:super.method() calls parent method; super() calls parent constructor (first line).

  36. Question:Are constructors inherited in Java subclasses?

    Answer:Constructors not inherited, but parent constructor always called explicitly or implicitly.

  37. 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.

  38. 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).

  39. Question:When is the instanceof operator used in Java polymorphism?

    Answer:instanceof checks if object is instance of class/interface before downcasting.

  40. 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.

  41. 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.

  42. 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.

  43. Question:What are the key characteristics of Java constructors?

    Answer:No return type (not void), same name as class, called with 'new'.

  44. Question:Under what condition does Java provide a default constructor?

    Answer:Auto-provided only if no constructors written.

  45. 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++.

  46. Question:What is constructor chaining in Java using this() and super()?

    Answer:this() calls another same-class ctor; super() calls parent ctor.

  47. Question:What is the initialization order for static blocks, instance blocks, and constructors?

    Answer:Static blocks → Instance blocks → Constructor (parent to child).

  48. Question:What happens to the default constructor if you define any parameterized constructor?

    Answer:Java does not provide default; must explicitly write if needed.

  49. 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.

  50. Question:When does a static block execute, and what is its purpose?

    Answer:Runs once on class load before constructors; for static initialization.

  51. 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.

  52. 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).

  53. Question:What is a blank final variable, and where must it be assigned?

    Answer:Final var declared without value; assigned in constructor.

  54. 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).

  55. 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).

  56. Question:What is the purpose of the @Override annotation in Java?

    Answer:@Override: compiler verifies valid override.

  57. Question:Classify exceptions as checked or unchecked with examples.

    Answer:Checked: must catch/declare (IOException, SQLException, ClassNotFound). Unchecked: RuntimeException subs (NullPointer, ArrayIndexOutOfBounds, ClassCast).

  58. 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.

  59. 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)) {}.

  60. Question:What distinguishes throw from throws in Java exception handling?

    Answer:throw: explicitly throws exception. throws: declares method may throw.

  61. Question:How do you create custom checked versus unchecked exceptions in Java?

    Answer:Extend Exception for checked; RuntimeException for unchecked.

  62. Question:What is exception chaining and exception propagation priority in return scenarios?

    Answer:new RuntimeException("msg", original) preserves cause. Finally return overrides try return.

  63. Question:Describe the Collections Framework hierarchy starting from Iterable.

    Answer:Iterable → Collection → {List, Set, Queue}; Map separate.

  64. 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.

  65. Question:Compare performance and usage of LinkedList versus ArrayList.

    Answer:LinkedList: doubly linked, O(n) access, O(1) ends add/remove, List+Deque.

  66. Question:Why is Vector considered legacy compared to ArrayList?

    Answer:Vector like ArrayList but synchronized/thread-safe; prefer ArrayList + manual sync.

  67. Question:What is Stack in Java collections, and what modern alternative is recommended?

    Answer:LIFO extends Vector (legacy); prefer ArrayDeque.

  68. Question:Describe HashSet properties regarding duplicates, order, nulls, and operations.

    Answer:No duplicates, HashMap-backed, O(1) ops, no order, one null allowed.

  69. Question:How does LinkedHashSet differ from HashSet?

    Answer:Like HashSet but maintains insertion order.

  70. Question:What defines TreeSet in terms of ordering, performance, and null handling?

    Answer:Sorted natural/Comparator, O(log n), no null, NavigableSet.

  71. 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.

  72. Question:What enhancements do LinkedHashMap and TreeMap provide over HashMap?

    Answer:LinkedHashMap: + insertion order. TreeMap: sorted keys O(log n), no null key, NavigableMap.

  73. Question:Why replace Hashtable with modern alternatives?

    Answer:Legacy like HashMap but sync, no nulls; use ConcurrentHashMap.

  74. Question:What is PriorityQueue's default structure, operations, and ordering?

    Answer:Min-heap default, O(log n) add/remove, no null, natural/Comparator.

  75. Question:What makes ArrayDeque efficient for queues compared to Stack or LinkedList?

    Answer:Double-ended queue, faster than Stack/LinkedList for LIFO/FIFO.

  76. 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.

  77. Question:Name key methods in Collections utility class for list manipulation.

    Answer:sort(), shuffle(), reverse(), min(), max(), frequency(), unmodifiableList(), synchronizedList().

  78. Question:List essential methods for Iterator and ListIterator in Java.

    Answer:Iterator: hasNext(), next(), remove(). ListIterator: + hasPrevious(), previous(), add(), set().

  79. Question:What happens with fail-fast versus fail-safe iterators during collection modification?

    Answer:Fail-fast (ArrayList): ConcurrentModificationException if modified. Fail-safe (CopyOnWriteArrayList): safe.

  80. 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.

  81. Question:What benefits do generics provide for collections and methods in Java?

    Answer:Type-safe collections/methods; errors at compile time, not runtime.

  82. Question:Define bounded type parameters and wildcard bounds in Java generics.

    Answer:: T Number/subclass. <?> any, <? extends T> upper, <? super T> lower (PECS).

  83. Question:What is type erasure in Java generics, and its runtime implication?

    Answer:Generic info removed at runtime; List and List both List.

  84. Question:Why are generic arrays invalid, and what alternatives exist for primitives?

    Answer:new T[10] not allowed; primitives like List invalid, use List .

  85. 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.

  86. Question:Outline the complete thread lifecycle states in Java.

    Answer:NEW → RUNNABLE → RUNNING → BLOCKED/WAITING/TIMED_WAITING → TERMINATED.

  87. 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.

  88. Question:How does Thread.sleep(ms) behave regarding locks and exceptions?

    Answer:Pauses current thread, does not release lock, InterruptedException handled.

  89. 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.

  90. Question:What does yield() do in Java multithreading?

    Answer:Hints scheduler to give CPU to same-priority threads, not guaranteed.

  91. Question:Compare synchronized method and synchronized block for thread safety.

    Answer:Synchronized method: lock 'this' one thread. Block: granular synchronized(obj) {}.

  92. Question:What does volatile ensure for variables in multithreading?

    Answer:Read/write to main memory not thread cache; no atomicity.

  93. 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.

  94. Question:Differentiate livelock, starvation from deadlock in multithreading.

    Answer:Livelock: respond no progress. Starvation: low prio no CPU. Deadlock: blocked forever.

  95. 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.

  96. Question:What are lambda expressions in Java 8, and their syntax?

    Answer:Anonymous functions: (params) -> expr or {stmts}.

  97. Question:What defines a functional interface for lambdas in Java?

    Answer:Interface with exactly one abstract method; @FunctionalInterface verifies.

  98. 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 .

  99. 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.

  100. 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.

  101. Question:What error occurs if you reuse a Stream after terminal operation?

    Answer:IllegalStateException; cannot reuse post-terminal.

  102. Question:How do parallel streams work, and potential drawbacks?

    Answer:stream.parallel() uses ForkJoinPool; may not faster due overhead.

  103. 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().

  104. Question:List key methods for Optional handling presence and transformation.

    Answer:isPresent(), get(), orElse(), orElseGet(), map(), filter(), ifPresent().