Spaces:
Runtime error
Runtime error
File size: 29,822 Bytes
1207440 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 | ### Java Platform
Why is Java so popular?
Java’s popularity stems from platform independence, robust libraries, scalability, and strong community support, making it ideal for enterprise, web, and mobile applications.
What is platform independence?
Platform independence means Java code runs on any device with a JVM, achieved through bytecode compilation, not tied to specific hardware or OS.
What is bytecode?
Bytecode is an intermediate, platform-independent representation of a Java program, generated by the compiler and executed by the JVM.
Compare JDK vs JVM vs JRE.
- JDK: Java Development Kit, includes JRE, compiler, and tools for development.
- JVM: Java Virtual Machine, executes bytecode, platform-specific.
- JRE: Java Runtime Environment, includes JVM and libraries for running Java apps.
What are the important differences between C++ and Java?
- Java is platform-independent; C++ is platform-specific.
- Java uses automatic garbage collection; C++ requires manual memory management.
- Java doesn’t support pointers or multiple inheritance; C++ does.
What is the role for a classloader in Java?
The classloader loads class files into memory, verifies bytecode, and initializes classes for JVM execution.
### Wrapper Classes
What are Wrapper classes?
Wrapper classes (e.g., Integer, Double) encapsulate primitive types, providing methods and object functionality.
Why do we need Wrapper classes in Java?
Wrapper classes enable primitives to be used in collections, provide utility methods, and support object-oriented operations.
What are the different ways of creating Wrapper class instances?
- Using constructors, e.g., `Integer i = new Integer(10);`
- Using `valueOf()`, e.g., `Integer i = Integer.valueOf(10);`
What are differences in the two ways of creating Wrapper classes?
- Constructors create new objects; `valueOf()` reuses cached objects for efficiency.
- `valueOf()` is preferred for performance and memory optimization.
What is auto boxing?
Auto boxing automatically converts primitives to their wrapper class, e.g., `int` to `Integer`.
What are the advantages of auto boxing?
Simplifies code, improves readability, and enables seamless use of primitives in collections.
What is casting?
Casting converts a variable from one type to another, e.g., `int` to `double`.
What is implicit casting?
Implicit casting automatically converts a smaller type to a larger type, e.g., `int i = 10; double d = i;`.
What is explicit casting?
Explicit casting manually converts a larger type to a smaller type, e.g., `double d = 10.5; int i = (int) d;`.
### Strings
Are all String’s immutable?
Yes, String objects are immutable; their values cannot be changed after creation.
Where are String values stored in memory?
String literals are stored in the String Pool (Heap); new String objects are in the Heap.
Why should you be careful about String concatenation (+) operator in loops?
The `+` operator creates new String objects per iteration, causing memory overhead and performance issues.
How do you solve above problem?
Use `StringBuilder` or `StringBuffer` for concatenation in loops to avoid creating multiple objects.
What are differences between String and StringBuffer?
- String is immutable; StringBuffer is mutable.
- StringBuffer is thread-safe; String is not inherently thread-safe.
What are differences between StringBuilder and StringBuffer?
- StringBuilder is not thread-safe, faster; StringBuffer is thread-safe, slower.
- StringBuilder is preferred for single-threaded applications.
Can you give examples of different utility methods in String class?
- `length()`: Returns string length.
- `substring(int, int)`: Extracts a substring.
- `toUpperCase()`: Converts to uppercase.
- `indexOf(String)`: Finds substring position.
### Object-Oriented Programming Basics
What is a class?
A class is a blueprint defining properties and behaviors for creating objects.
What is an object?
An object is an instance of a class, representing a specific entity with state and behavior.
What is state of an object?
State is the data (fields) of an object, e.g., a `Car`’s color and speed.
What is behavior of an object?
Behavior is the methods defining what an object can do, e.g., `Car`’s `drive()` method.
What is the super class of every class in Java?
`Object` is the superclass of all classes in Java.
Explain about toString method?
`toString()` returns a string representation of an object, often overridden for meaningful output.
What is the use of equals method in Java?
`equals()` compares two objects for equality based on their content, not reference.
What are the important things to consider when implementing equals method?
- Reflexive, symmetric, transitive, consistent.
- Handle null checks and type compatibility.
What is the Hashcode method used for in Java?
`hashCode()` generates an integer for objects, used in hash-based collections like HashMap.
Explain inheritance with examples.
Inheritance allows a class to inherit properties/methods from another, e.g., `class Dog extends Animal {}` inherits `eat()`.
What is method overloading?
Method overloading defines multiple methods with the same name but different parameters.
What is method overriding?
Method overriding redefines a superclass method in a subclass with the same signature.
Can super class reference variable can hold an object of sub class?
Yes, e.g., `Animal a = new Dog();` (polymorphism).
Is multiple inheritance allowed in Java?
No, Java supports single inheritance for classes but allows multiple interfaces.
What is an interface?
An interface defines a contract of methods that implementing classes must provide.
How do you define an interface?
`interface MyInterface { void myMethod(); }`
How do you implement an interface?
`class MyClass implements MyInterface { public void myMethod() {} }`
Can you explain a few tricky things about interfaces?
- Methods are implicitly public/abstract (pre-Java 8).
- Default/static methods (Java 8+) can have implementations.
- Cannot instantiate interfaces.
Can you extend an interface?
Yes, e.g., `interface Child extends Parent {}`.
Can a class extend multiple interfaces?
Yes, e.g., `class MyClass implements Interface1, Interface2 {}`.
What is an abstract class?
An abstract class cannot be instantiated and may contain abstract methods.
When do you use an abstract class?
Use for shared code among related classes, e.g., `abstract class Vehicle` for `Car` and `Bike`.
How do you define an abstract method?
`abstract void myMethod();` in an abstract class.
Compare abstract class vs interface?
- Abstract classes can have state and implementations; interfaces (pre-Java 8) cannot.
- Classes can implement multiple interfaces, but inherit one abstract class.
What is a constructor?
A constructor initializes an object when created, with the same name as the class.
What is a default constructor?
A default constructor is a no-argument constructor automatically provided if none is defined.
Will this code compile?
Please provide the code to evaluate.
How do you call a super class constructor from a constructor?
Use `super(args)` as the first statement in a subclass constructor.
Will this code compile?
Please provide the code to evaluate.
What is the use of this()?
`this()` calls another constructor in the same class, used for constructor chaining.
Can a constructor be called directly from a method?
No, constructors are called only during object creation with `new`.
Is a super class constructor called even when there is no explicit call from a sub class constructor?
Yes, the superclass’s no-arg constructor is called implicitly if no `super()` is specified.
### Advanced Object-Oriented Concepts
What is polymorphism?
Polymorphism allows objects to be treated as their superclass type or behave differently based on subtype, e.g., method overriding.
What is the use of instanceof operator in Java?
`instanceof` checks if an object is an instance of a class or interface, e.g., `obj instanceof String`.
What is coupling?
Coupling is the dependency between classes; low coupling improves modularity.
What is cohesion?
Cohesion is how well a class’s methods and data work together for a single purpose; high cohesion is desirable.
What is encapsulation?
Encapsulation hides data and exposes methods to control access, using private fields and public getters/setters.
What is an inner class?
An inner class is defined inside another class, accessing its enclosing class’s members.
What is a static inner class?
A static inner class is a nested class declared `static`, not tied to an instance of the outer class.
Can you create an inner class inside a method?
Yes, a local inner class can be defined inside a method.
What is an anonymous class?
An anonymous class is an unnamed class defined inline, often for one-time use, e.g., `new Runnable() {}`.
### Modifiers
What is default class modifier?
Default (package-private) restricts class access to the same package if no modifier is specified.
What is private access modifier?
Private restricts access to the class itself, e.g., private fields or methods.
What is default or package access modifier?
Default allows access within the same package if no modifier is specified.
What is protected access modifier?
Protected allows access within the same package and subclasses in different packages.
What is public access modifier?
Public allows access from everywhere.
What access types of variables can be accessed from a class in same package?
Public, protected, and default variables can be accessed.
What access types of variables can be accessed from a class in different package?
Only public variables can be accessed.
What access types of variables can be accessed from a sub class in same package?
Public, protected, and default variables are accessible.
What access types of variables can be accessed from a sub class in different package?
Public and protected variables are accessible.
What is the use of a final modifier on a class?
`final` prevents a class from being subclassed, e.g., `final class MyClass`.
What is the use of a final modifier on a method?
`final` prevents a method from being overridden in subclasses.
What is a final variable?
A `final` variable cannot be reassigned after initialization.
What is a final argument?
A `final` argument cannot be modified within a method.
What happens when a variable is marked as volatile?
`volatile` ensures visibility of variable changes across threads, preventing caching.
What is a static variable?
A `static` variable belongs to the class, shared across all instances.
### Conditions & Loops
Why should you always use blocks around if statement?
Blocks `{}` ensure clarity and prevent errors when adding statements to single-line `if`.
Guess the output.
Please provide the code to evaluate.
Guess the output.
Please provide the code to evaluate.
Guess the output of this switch block.
Please provide the switch block code to evaluate.
Guess the output of this switch block?
Please provide the switch block code to evaluate.
Should default be the last case in a switch statement?
Yes, `default` is typically last, but it can be anywhere; it executes if no cases match.
Can a switch statement be used around a String?
Yes, since Java 7, `switch` supports String objects.
Guess the output of this for loop.
Please provide the for loop code to evaluate.
What is an enhanced for loop?
An enhanced for loop (`for-each`) iterates over arrays/collections, e.g., `for (int i : array)`.
What is the output of the for loop below?
Please provide the for loop code to evaluate.
What is the output of the program below?
Please provide the program code to evaluate.
What is the output of the program below?
Please provide the program code to evaluate.
### Exception Handling
Why is exception handling important?
Exception handling ensures robust programs by managing errors gracefully, preventing crashes.
What design pattern is used to implement exception handling features in most languages?
The Chain of Responsibility pattern is used, passing exceptions up the call stack.
What is the need for finally block?
The `finally` block executes cleanup code (e.g., closing resources) regardless of exception.
In what scenarios is code in finally not executed?
`finally` is skipped if the JVM exits, `System.exit()` is called, or the thread is interrupted.
Will finally be executed in the program below?
Please provide the code to evaluate.
Is try without a catch is allowed?
Yes, `try` can be used with `finally` without `catch`.
Is try without catch and finally allowed?
No, `try` requires either `catch` or `finally`.
Can you explain the hierarchy of exception handling classes?
`Throwable` is the root, with `Error` (system issues) and `Exception` (program issues, checked/unchecked).
What is the difference between error and exception?
Errors are severe (e.g., OutOfMemoryError); exceptions are recoverable (e.g., IOException).
What is the difference between checked exceptions and unchecked exceptions?
Checked exceptions (e.g., IOException) require handling; unchecked (e.g., NullPointerException) do not.
How do you throw an exception from a method?
Use `throw new ExceptionType("message");`.
What happens when you throw a checked exception from a method?
It must be declared with `throws` in the method signature or handled in a `try-catch`.
What are the options you have to eliminate compilation errors when handling checked exceptions?
- Use `try-catch` to handle the exception.
- Declare with `throws` to pass it up.
How do you create a custom exception?
Extend `Exception` or `RuntimeException`, e.g., `class MyException extends Exception {}`.
How do you handle multiple exception types with same exception handling block?
Use multi-catch, e.g., `catch (IOException | SQLException e)`.
Can you explain about try with resources?
`try-with-resources` automatically closes resources implementing `AutoCloseable`, e.g., `try (FileReader fr = new FileReader("file")) {}`.
How does try with resources work?
Resources declared in `try()` are closed automatically after execution, even if exceptions occur.
Can you explain a few exception handling best practices?
- Catch specific exceptions.
- Use `try-with-resources` for resource management.
- Log exceptions for debugging.
- Avoid empty catch blocks.
### Miscellaneous Topics
What are the default values in an array?
Primitives: 0 (numbers), `false` (boolean); objects: `null`.
How do you loop around an array using enhanced for loop?
`for (Type element : array) { System.out.println(element); }`
How do you print the content of an array?
Use `Arrays.toString(array)` or loop through elements.
How do you compare two arrays?
Use `Arrays.equals(array1, array2)` for content comparison.
What is an enum?
An `enum` defines a fixed set of constants, e.g., `enum Day { MONDAY, TUESDAY }`.
Can you use a switch statement around an enum?
Yes, `switch` works with enums, e.g., `switch (day) { case MONDAY: ... }`.
What are variable arguments or varargs?
Varargs (`Type... args`) allow a method to accept variable numbers of arguments.
What are asserts used for?
Asserts validate assumptions during development, throwing `AssertionError` if false.
When should asserts be used?
Use in testing/development to catch logical errors, not in production.
What is garbage collection?
Garbage collection reclaims memory from unused objects automatically.
Can you explain garbage collection with an example?
`Object obj = new Object(); obj = null;` makes the object eligible for garbage collection.
When is garbage collection run?
It runs automatically when memory is low or during idle periods.
What are best practices on garbage collection?
- Avoid unnecessary object creation.
- Null out references when done.
- Use weak references for caches.
What are initialization blocks?
Initialization blocks are code blocks for initializing instance/static variables.
What is a static initializer?
A `static {}` block initializes static variables when a class is loaded.
What is an instance initializer block?
An `{}` block initializes instance variables before constructors.
What is tokenizing?
Tokenizing splits a string into smaller parts (tokens) based on delimiters.
Can you give an example of tokenizing?
`StringTokenizer st = new StringTokenizer("a,b,c", ",");` splits into "a", "b", "c".
What is serialization?
Serialization converts an object to a byte stream for storage or transmission.
How do you serialize an object using serializable interface?
Implement `Serializable` and use `ObjectOutputStream` to write the object.
How do you de-serialize in Java?
Use `ObjectInputStream` to read a serialized object back into memory.
What do you do if only parts of the object have to be serialized?
Use `transient` to exclude fields from serialization.
How do you serialize a hierarchy of objects?
Ensure all classes in the hierarchy implement `Serializable`.
Are the constructors in an object invoked when it is de-serialized?
No, constructors are not called during deserialization.
Are the values of static variables stored when an object is serialized?
No, static variables are not serialized as they belong to the class.
### Collections
Why do we need collections in Java?
Collections provide dynamic, flexible data structures for storing and manipulating data.
What are the important interfaces in the collection hierarchy?
`Collection`, `List`, `Set`, `Map`, `Queue`, `Deque`.
What are the important methods that are declared in the collection interface?
`add()`, `remove()`, `size()`, `contains()`, `iterator()`.
Can you explain briefly about the List interface?
`List` is an ordered, index-based collection allowing duplicates, e.g., `ArrayList`.
Explain about ArrayList with an example?
`ArrayList list = new ArrayList(); list.add("item");` – dynamic, resizable list.
Can an ArrayList have duplicate elements?
Yes, `ArrayList` allows duplicates.
How do you iterate around an ArrayList using iterator?
`Iterator<String> it = list.iterator(); while (it.hasNext()) { System.out.println(it.next()); }`
How do you sort an ArrayList?
Use `Collections.sort(list)` or `list.sort(Comparator)`.
How do you sort elements in an ArrayList using comparable interface?
Implement `Comparable` in the class and use `Collections.sort(list)`.
How do you sort elements in an ArrayList using comparator interface?
Use `Collections.sort(list, new Comparator<Type>() { ... })` or `list.sort(comparator)`.
What is vector class? How is it different from an ArrayList?
`Vector` is synchronized; `ArrayList` is not, making `ArrayList` faster for single-threaded use.
What is linkedList? What interfaces does it implement? How is it different from an ArrayList?
`LinkedList` implements `List` and `Deque`; it’s a doubly-linked list, better for insertions/deletions than `ArrayList`.
Can you briefly explain about the Set interface?
`Set` is a collection with no duplicates, e.g., `HashSet`, `TreeSet`.
What are the important interfaces related to the Set interface?
`SortedSet`, `NavigableSet`.
What is the difference between Set and sortedSet interfaces?
`SortedSet` maintains sorted order; `Set` does not.
Can you give examples of classes that implement the Set interface?
`HashSet`, `LinkedHashSet`, `TreeSet`.
What is a HashSet?
`HashSet` is an unordered set with fast lookup, no duplicates.
What is a linkedHashSet? How is different from a HashSet?
`LinkedHashSet` maintains insertion order; `HashSet` does not.
What is a TreeSet? How is different from a HashSet?
`TreeSet` is sorted; `HashSet` is unordered, faster for lookups.
Can you give examples of implementations of navigableSet?
`TreeSet`, `ConcurrentSkipListSet`.
Explain briefly about Queue interface?
`Queue` supports FIFO operations, e.g., `add()`, `poll()`.
What are the important interfaces related to the Queue interface?
`Deque`, `BlockingQueue`.
Explain about the Deque interface?
`Deque` (double-ended queue) supports adding/removing from both ends.
Explain the BlockingQueue interface?
`BlockingQueue` supports thread-safe queuing with blocking operations for full/empty queues.
What is a priorityQueue?
`PriorityQueue` orders elements based on priority (natural or custom).
Can you give example implementations of the BlockingQueue interface?
`ArrayBlockingQueue`, `LinkedBlockingQueue`, `PriorityBlockingQueue`.
Can you briefly explain about the Map interface?
`Map` stores key-value pairs, e.g., `HashMap`, no duplicate keys.
What is difference between Map and sortedMap?
`SortedMap` maintains sorted keys; `Map` does not.
What is a HashMap?
`HashMap` is an unordered key-value store with fast lookups.
What are the different methods in a Hash Map?
`put()`, `get()`, `remove()`, `containsKey()`, `keySet()`.
What is a TreeMap? How is different from a HashMap?
`TreeMap` is sorted by keys; `HashMap` is unordered, faster.
Can you give an example of implementation of navigableMap interface?
`TreeMap`, `ConcurrentSkipListMap`.
What are the static methods present in the collections class?
`sort()`, `reverse()`, `shuffle()`, `max()`, `min()`.
### Advanced Collections
What is the difference between synchronized and concurrent collections in Java?
Synchronized collections (e.g., `Vector`) lock fully; concurrent collections (e.g., `ConcurrentHashMap`) allow partial concurrency, improving performance.
Explain about the new concurrent collections in Java?
`ConcurrentHashMap`, `CopyOnWriteArrayList`, `BlockingQueue` support thread-safe operations with better concurrency.
Explain about copyonwrite concurrent collections approach?
`CopyOnWriteArrayList` creates a new copy on write operations, ideal for read-heavy scenarios.
What is compareandswap approach?
Compare-and-swap atomically updates a value if it matches an expected value, used in concurrent collections.
What is a lock? How is it different from using synchronized approach?
A `Lock` (e.g., `ReentrantLock`) offers flexible locking; `synchronized` is simpler but less configurable.
What is initial capacity of a Java collection?
Initial capacity is the starting size of a collection, e.g., `new ArrayList(10)`.
What is load factor?
Load factor determines when a collection (e.g., `HashMap`) resizes, typically 0.75.
When does a Java collection throw UnsupportedOperationException?
When an unmodifiable collection (e.g., `Collections.unmodifiableList()`) is modified.
What is difference between fail-safe and fail-fast iterators?
Fail-fast throws `ConcurrentModificationException` on modification; fail-safe (e.g., `CopyOnWriteArrayList`) works on a snapshot.
What are atomic operations in Java?
Atomic operations (e.g., `AtomicInteger.incrementAndGet()`) are thread-safe without locks.
What is BlockingQueue in Java?
`BlockingQueue` is a thread-safe queue with blocking operations for full/empty states.
### Generics
What are Generics?
Generics enable type-safe collections and methods, e.g., `List<String>`.
Why do we need Generics? Can you give an example of how Generics make a program more flexible?
Generics ensure type safety and eliminate casting. Example: `List<String> list = new ArrayList<>();` avoids runtime type errors.
How do you declare a generic class?
`class MyClass<T> { T field; }`
What are the restrictions in using generic type that is declared in a class declaration?
Cannot use primitive types or create instances of the generic type (`new T()`).
How can we restrict Generics to a subclass of particular class?
Use `extends`, e.g., `class MyClass<T extends Number>`.
How can we restrict Generics to a super class of particular class?
Use `super`, e.g., `class MyClass<T super Integer>` (rare, used in wildcards).
Can you give an example of a generic method?
`<T> void print(T item) { System.out.println(item); }`
### Multi Threading
What is the need for threads in Java?
Threads enable concurrent execution, improving performance for tasks like I/O or computations.
How do you create a thread?
Extend `Thread` or implement `Runnable` and pass to a `Thread` object.
How do you create a thread by extending thread class?
`class MyThread extends Thread { public void run() { ... } }`
How do you create a thread by implementing runnable interface?
`class MyRunnable implements Runnable { public void run() { ... } } Thread t = new Thread(new MyRunnable());`
How do you run a thread in Java?
Call `thread.start()` to execute the `run()` method in a new thread.
What are the different states of a thread?
New, Runnable, Blocked, Waiting, Timed Waiting, Terminated.
What is priority of a thread? How do you change the priority of a thread?
Priority (1-10) affects thread scheduling; set with `thread.setPriority(Thread.MAX_PRIORITY)`.
What is executorservice?
`ExecutorService` manages a pool of threads for task execution.
Can you give an example for executorservice?
`ExecutorService es = Executors.newFixedThreadPool(2); es.submit(() -> System.out.println("Task"));`
Explain different ways of creating executor services.
- `Executors.newFixedThreadPool(n)`: Fixed-size thread pool.
- `Executors.newCachedThreadPool()`: Dynamic thread pool.
- `Executors.newSingleThreadExecutor()`: Single-thread executor.
How do you check whether an executionservice task executed successfully?
Use `Future.get()` to retrieve results or catch exceptions.
What is callable? How do you execute a callable from executionservice?
`Callable` returns a value; submit with `Future result = es.submit(new Callable<Type>() { ... });`.
What is synchronization of threads?
Synchronization ensures thread-safe access to shared resources using locks.
Can you give an example of a synchronized block?
`synchronized(obj) { // critical section }`
Can a static method be synchronized?
Yes, using `synchronized static void method()` or `synchronized(ClassName.class)`.
What is the use of join method in threads?
`join()` makes a thread wait for another thread to complete.
Describe a few other important methods in threads?
`sleep()`, `yield()`, `interrupt()`, `isAlive()`.
What is a deadlock?
A deadlock occurs when threads hold resources each other needs, causing a standstill.
What are the important methods in Java for inter-thread communication?
`wait()`, `notify()`, `notifyAll()`.
What is the use of wait method?
`wait()` makes a thread wait until notified, releasing the lock.
What is the use of notify method?
`notify()` wakes one waiting thread holding the same lock.
What is the use of notifyall method?
`notifyAll()` wakes all waiting threads holding the same lock.
Can you write a synchronized program with wait and notify methods?
```java
class Shared {
synchronized void produce() throws InterruptedException {
wait();
System.out.println("Produced");
}
synchronized void consume() throws InterruptedException {
notify();
System.out.println("Consumed");
}
}
```
### Functional Programming - Lambda Expressions and Streams
What is functional programming?
Functional programming emphasizes immutable data, pure functions, and declarative style.
Can you give an example of functional programming?
`list.stream().filter(x -> x > 5).map(x -> x * 2).forEach(System.out::println);`
What is a stream?
A stream is a sequence of elements for processing in a functional style.
Explain about streams with an example?
`List<Integer> list = Arrays.asList(1, 2, 3); list.stream().map(x -> x * 2).collect(Collectors.toList());` doubles each element.
What are intermediate operations in streams?
Intermediate operations (e.g., `filter`, `map`) transform streams and are lazy.
What are terminal operations in streams?
Terminal operations (e.g., `collect`, `forEach`) produce results and close streams.
What are method references?
Method references (`Class::method`) are shorthand for lambda expressions calling methods.
What are lambda expressions?
Lambda expressions (`x -> x * 2`) are anonymous functions for functional interfaces.
Can you give an example of lambda expression?
`Function<Integer, Integer> doubleIt = x -> x * 2;`
Can you explain the relationship between lambda expression and functional interfaces?
Lambda expressions implement functional interfaces (one abstract method), e.g., `Runnable`, `Function`.
What is a predicate?
A `Predicate` is a functional interface testing a condition, e.g., `Predicate<Integer> isEven = x -> x % 2 == 0`.
What is the functional interface - function?
`Function<T, R>` takes an input and returns an output, e.g., `Function<Integer, String> toString = String::valueOf`.
What is a consumer?
A `Consumer` takes an input and performs an action, e.g., `Consumer<String> print = System.out::println`.
Can you give examples of functional interfaces with multiple arguments?
`BiFunction<Integer, Integer, Integer> sum = (a, b) -> a + b;`
### New Features
What are the new features in Java 5?
Generics, enhanced for loop, autoboxing, enums, varargs, annotations.
What are the new features in Java 6?
Scripting engine, JDBC 4.0, improved garbage collection.
What are the new features in Java 7?
Try-with-resources, switch with String, diamond operator, multi-catch.
What are the new features in Java 8?
Lambda expressions, streams, functional interfaces, default methods, Optional class. |