๐Ÿ“˜ Top 500 Java Interview Questions (With Topics)

       ๐Ÿ“˜ Top 500 Java Interview Questions (With Topics)


1. Core Java Basics

  1. What is Java?

  2. What are the features of Java?

  3. What is JVM, JRE, JDK?

  4. Difference between JDK and JRE?

  5. Explain the Java execution flow.

  6. What are data types in Java?

  7. What is type casting?

  8. What are variables in Java?

  9. What are literals in Java?

  10. Difference between primitive and non-primitive data types?

  11. What is a wrapper class?

  12. Explain autoboxing and unboxing.

  13. Difference between == and .equals()?

  14. What are operators in Java?

  15. What is precedence of operators?

  16. What is ternary operator?

  17. Difference between && and &?

  18. What are bitwise operators?

  19. What is instanceof operator?

  20. What are control statements in Java?


2. OOPs Concepts

  1. What is Object-Oriented Programming (OOP)?

  2. What are the four pillars of OOP?

  3. What is class and object?

  4. What is constructor?

  5. Types of constructors in Java?

  6. Difference between constructor and method?

  7. What is this keyword?

  8. What is super keyword?

  9. Difference between overloading and overriding?

  10. What is inheritance?

  11. Types of inheritance in Java?

  12. What is multiple inheritance? Is it supported in Java?

  13. What is polymorphism?

  14. What is method overloading?

  15. What is method overriding?

  16. What is encapsulation?

  17. What is abstraction?

  18. Difference between abstract class and interface?

  19. Can we create object of abstract class?

  20. Can interface have constructors?


3. Strings & Arrays

  1. Difference between String, StringBuffer, and StringBuilder?

  2. Why is String immutable in Java?

  3. How to compare two Strings in Java?

  4. What is intern() in String?

  5. What is String.format()?

  6. What is substring() method?

  7. What is an array in Java?

  8. How to create multidimensional arrays?

  9. Difference between shallow copy and deep copy in arrays?

  10. How to sort an array in Java?


4. Collections Framework

  1. What is Collection Framework in Java?

  2. Difference between List, Set, and Map?

  3. Difference between ArrayList and LinkedList?

  4. Difference between HashSet and TreeSet?

  5. Difference between HashMap and Hashtable?

  6. Difference between HashMap and ConcurrentHashMap?

  7. What is LinkedHashMap?

  8. What is EnumMap?

  9. What is PriorityQueue?

  10. Difference between Iterator and ListIterator?

  11. What is fail-fast and fail-safe iterator?

  12. What is Comparable vs Comparator?

  13. How HashMap works internally?

  14. What is hashing in Java?

  15. What is load factor in HashMap?


5. Exception Handling

  1. What is exception in Java?

  2. Difference between checked and unchecked exceptions?

  3. Difference between throw and throws?

  4. Difference between final, finally, and finalize()?

  5. Can we have try without catch?

  6. What is custom exception in Java?

  7. What is Throwable?

  8. Difference between Error and Exception?

  9. What is try-with-resources?

  10. What happens if finally block has return statement?


6. Multithreading

  1. What is thread in Java?

  2. Difference between process and thread?

  3. How to create thread in Java?

  4. Difference between Runnable and Thread?

  5. What is thread lifecycle?

  6. What is synchronization?

  7. Difference between synchronized method and block?

  8. What is deadlock?

  9. What is race condition?

  10. What is thread pool in Java?

  11. What is Executor framework?

  12. Difference between Callable and Runnable?

  13. What is Future in Java?

  14. What is CountDownLatch?

  15. What is CyclicBarrier?


7. Java 8+ Features

  1. What are new features of Java 8?

  2. What is Lambda expression?

  3. What is Functional Interface?

  4. What is Stream API?

  5. Difference between map() and flatMap()?

  6. What is Optional class in Java 8?

  7. What is default method in interface?

  8. What are method references?

  9. What is LocalDate, LocalTime, LocalDateTime in Java 8?

  10. Difference between forEach() and map() in streams?


8. Memory Management & GC

  1. What is Garbage Collection in Java?

  2. What is heap memory and stack memory?

  3. What are different GC algorithms?

  4. What is finalize() method?

  5. What are memory leaks in Java?

  6. What are weak references?

  7. What is SoftReference, WeakReference, PhantomReference?

  8. Difference between strong and weak reference?

  9. How to make an object eligible for GC?

  10. What is OutOfMemoryError?


9. Advanced Java

  1. What is JDBC?

  2. What are JDBC drivers?

  3. Difference between Statement and PreparedStatement?

  4. What is ResultSet in JDBC?

  5. What is Servlet in Java?

  6. Lifecycle of a Servlet?

  7. What is JSP?

  8. Difference between JSP and Servlet?

  9. What is Spring Framework?

  10. What is Hibernate?

10. Java I/O & File Handling

  1. What is Java I/O?

  2. Difference between Byte stream and Character stream?

  3. What is InputStream and OutputStream?

  4. Difference between FileReader and BufferedReader?

  5. Difference between FileInputStream and FileReader?

  6. What is Serialization in Java?

  7. What is Deserialization?

  8. What is transient keyword?

  9. What is Serializable interface?

  10. Difference between Externalizable and Serializable?

  11. What is RandomAccessFile in Java?

  12. What is NIO (New Input/Output)?

  13. What is Buffer in Java NIO?

  14. Difference between Stream and Channel in NIO?

  15. What are Selectors in NIO?

  16. What is File Locking in Java?

  17. What is Path and Files class in Java NIO?

  18. What is Asynchronous I/O in Java?

  19. What is Scanner class used for?

  20. How to read a file line by line in Java?


11. JVM & Performance

  1. What is JVM architecture?

  2. What are classloaders in Java?

  3. What are the types of classloaders?

  4. What is Just-In-Time (JIT) Compiler?

  5. Difference between interpreter and JIT?

  6. What are JVM memory areas?

  7. What is Method Area in JVM?

  8. What is PermGen vs Metaspace?

  9. What is stack memory in JVM?

  10. What is heap memory?

  11. What is class file structure in Java?

  12. What is bytecode in Java?

  13. How JVM loads a class?

  14. Difference between Bootstrap and Application ClassLoader?

  15. What are custom classloaders?

  16. What is memory leak in Java?

  17. How to analyze heap dumps?

  18. What is JConsole?

  19. What is JVisualVM?

  20. What is profiling in Java?


12. Java Annotations & Reflection

  1. What are annotations in Java?

  2. Difference between @Override and @Overload?

  3. What is @FunctionalInterface?

  4. What is @Deprecated annotation?

  5. What is custom annotation?

  6. How to create your own annotation?

  7. What are meta-annotations?

  8. Difference between @Retention and @Target?

  9. What is @Documented and @Inherited?

  10. What is reflection in Java?

  11. How to get methods of a class using reflection?

  12. How to access private fields using reflection?

  13. What is setAccessible(true) in reflection?

  14. What is dynamic proxy in Java?

  15. What are use cases of reflection?

  16. What is annotation processing tool (APT)?

  17. Difference between runtime and compile-time annotations?

  18. What is dependency injection annotation in Spring?

  19. What is Lombok in Java?

  20. What are marker annotations?


13. Java Networking

  1. What is networking in Java?

  2. What is Socket in Java?

  3. Difference between TCP and UDP in Java?

  4. What is ServerSocket class?

  5. How to create a client-server program in Java?

  6. What is URL and URLConnection class?

  7. What is Datagram in Java?

  8. What is MulticastSocket?

  9. Difference between HTTP and HTTPS?

  10. What is InetAddress in Java?

  11. What is RMI (Remote Method Invocation)?

  12. Difference between RMI and CORBA?

  13. What is REST API in Java?

  14. How to consume REST API using HttpURLConnection?

  15. What is HttpClient API in Java 11?

  16. What is WebSocket in Java?

  17. Difference between GET and POST in HTTP?

  18. What are cookies and sessions in Java web?

  19. What is load balancing?

  20. What is SSL handshake?


14. Java Design Patterns

  1. What are design patterns?

  2. What is Singleton Pattern?

  3. How to implement thread-safe Singleton?

  4. What is Factory Pattern?

  5. Difference between Factory and Abstract Factory?

  6. What is Builder Pattern?

  7. What is Prototype Pattern?

  8. What is Adapter Pattern?

  9. What is Decorator Pattern?

  10. What is Proxy Pattern?

  11. What is Facade Pattern?

  12. What is Composite Pattern?

  13. What is Bridge Pattern?

  14. What is Flyweight Pattern?

  15. What is Observer Pattern?

  16. What is Strategy Pattern?

  17. What is State Pattern?

  18. What is Command Pattern?

  19. What is Template Method Pattern?

  20. What is Chain of Responsibility Pattern?

  21. What is Dependency Injection Pattern?

  22. Difference between MVC and MVVM?

  23. What is DAO Pattern?

  24. What is Repository Pattern?

  25. What is Service Locator Pattern?


15. Spring Framework

  1. What is Spring Framework?

  2. What are the features of Spring?

  3. What is dependency injection in Spring?

  4. What are types of dependency injection?

  5. Difference between constructor and setter injection?

  6. What is Spring Bean?

  7. What is ApplicationContext?

  8. What is BeanFactory vs ApplicationContext?

  9. What is Spring Boot?

  10. What is Spring Boot Starter?

  11. What is Spring Boot AutoConfiguration?

  12. Difference between Spring and Spring Boot?

  13. What is @Component, @Service, and @Repository?

  14. What is @Autowired annotation?

  15. What is @Qualifier annotation?

  16. Difference between @ComponentScan and @EnableAutoConfiguration?

  17. What is @Configuration annotation?

  18. What is Spring AOP?

  19. What is Aspect, JoinPoint, and Advice?

  20. Difference between before, after, and around advice?

  21. What is Spring Transaction Management?

  22. Difference between checked and unchecked exception in Spring Transaction?

  23. What is @Transactional annotation?

  24. What is Spring Data JPA?

  25. What is Hibernate vs JPA?


16. Hibernate

  1. What is Hibernate?

  2. What is ORM (Object Relational Mapping)?

  3. Difference between JDBC and Hibernate?

  4. What are advantages of Hibernate?

  5. What is SessionFactory in Hibernate?

  6. What is Session in Hibernate?

  7. Difference between openSession and getCurrentSession?

  8. What is Hibernate caching?

  9. What is first-level cache in Hibernate?

  10. What is second-level cache in Hibernate?

  11. What are different caching providers in Hibernate?

  12. What is Criteria API?

  13. Difference between HQL and SQL?

  14. What is Named Query?

  15. What is Lazy Loading in Hibernate?

  16. What is Eager Loading in Hibernate?

  17. What is dirty checking in Hibernate?

  18. What are Hibernate annotations?

  19. What is Hibernate Validator?

  20. Difference between get() and load() in Hibernate?


17. Java Concurrency Advanced

  1. What is Callable in Java?

  2. What is FutureTask?

  3. What is CompletionService?

  4. What is ForkJoinPool?

  5. What is parallelStream()?

  6. Difference between parallel() and sequential() in streams?

  7. What is volatile keyword?

  8. Difference between volatile and synchronized?

  9. What is Atomic classes in Java?

  10. What is ReentrantLock?

  11. Difference between ReentrantLock and synchronized?

  12. What is ReadWriteLock?

  13. What is Semaphore?

  14. What is CountDownLatch?

  15. What is CyclicBarrier?

  16. Difference between CyclicBarrier and CountDownLatch?

  17. What is Phaser in Java?

  18. What is Exchanger in Java?

  19. What are ThreadLocal variables?

  20. What is ThreadFactory?


18. Java Security

  1. What is Java Security API?

  2. What is Encryption and Decryption?

  3. Difference between symmetric and asymmetric encryption?

  4. What is RSA in Java?

  5. What is AES in Java?

  6. What is MessageDigest class?

  7. What is SHA-256 hashing?

  8. What is digital signature in Java?

  9. What is KeyStore in Java?

  10. What is SSLContext in Java?


19. Java Microservices

  1. What are microservices?

  2. Difference between monolithic and microservices architecture?

  3. What is Spring Boot’s role in microservices?

  4. What is Spring Cloud?

  5. What is Netflix Eureka?

  6. What is service discovery in microservices?

  7. What is API Gateway in microservices?

  8. What is Zuul vs Spring Cloud Gateway?

  9. What is circuit breaker pattern?

  10. What is Hystrix?

  11. What is Resilience4j?

  12. What is Config Server in Spring Cloud?

  13. Difference between synchronous and asynchronous communication in microservices?

  14. What is REST vs gRPC in microservices?

  15. What is distributed tracing?

  16. What is Zipkin in microservices?

  17. What is Sleuth in Spring Cloud?

  18. What is load balancing in microservices?

  19. What is Ribbon in Spring Cloud?

  20. What are advantages of microservices over monolithic?


20. Java Testing (JUnit & Mockito)

  1. What is JUnit in Java?

  2. Difference between JUnit 4 and JUnit 5?

  3. What are annotations in JUnit?

  4. What is @BeforeEach and @AfterEach?

  5. What is @BeforeAll and @AfterAll?

  6. What is @Test annotation?

  7. How to disable a test in JUnit 5?

  8. What is parameterized test in JUnit?

  9. What is assertEquals() in JUnit?

  10. Difference between assertTrue() and assertFalse()?

  11. What is Mockito?

  12. Difference between mock() and spy()?

  13. What is @Mock annotation?

  14. What is @InjectMocks annotation?

  15. What is @Captor in Mockito?

  16. What is stubbing in Mockito?

  17. How to verify a method call in Mockito?

  18. Difference between JUnit and TestNG?

  19. What is integration testing in Java?

  20. What is system testing in Java?


21. Java 11/17/21 Features

  1. What are new features in Java 11?

  2. What is var in Java?

  3. What is Local-Variable Syntax for Lambda parameters?

  4. What is new HTTP client in Java 11?

  5. What is String.isBlank()?

  6. What is String.lines() method?

  7. What is String.strip() method?

  8. What is Files.readString()?

  9. What is Files.writeString()?

  10. What is the difference between removeIf() and replaceAll()?

  11. What are new features in Java 17?

  12. What is Sealed Class in Java?

  13. What is instanceof pattern matching?

  14. What is record class in Java?

  15. Difference between record and class?

  16. What is switch expression in Java?

  17. What are text blocks in Java?

  18. What are hidden classes?

  19. What is JEP 356 (Enhanced Pseudorandom Number Generators)?

  20. What are features in Java 21?

  21. What is Virtual Thread in Java 21?

  22. What is Structured Concurrency in Java 21?

  23. What is Sequenced Collection in Java 21?

  24. What is String Templates in Java 21?

  25. Difference between Virtual Thread and Platform Thread?

  26. What is Scoped Values in Java 21?

  27. What is Pattern Matching for Switch?

  28. What is Foreign Function & Memory API?

  29. What is Deprecation of RMI in Java 21?

  30. What is key benefit of Virtual Threads?


22. Java & Cloud

  1. What is cloud-native Java?

  2. How to deploy Java apps on AWS?

  3. What is Elastic Beanstalk in AWS?

  4. How to connect Java with S3?

  5. How to connect Java with DynamoDB?

  6. How to use Java Lambda in AWS?

  7. How to connect Java with Google Cloud Storage?

  8. What is GCP App Engine for Java?

  9. What is Azure Functions with Java?

  10. What is Kubernetes in microservices?

  11. What is Docker?

  12. How to containerize Java application?

  13. Difference between Docker and Kubernetes?

  14. What is Helm in Kubernetes?

  15. What is ConfigMap in Kubernetes?

  16. What is Secret in Kubernetes?

  17. How Java apps communicate in Kubernetes?

  18. What is service mesh (Istio)?

  19. What is API throttling in cloud apps?

  20. How to secure cloud-based Java microservices?


23. System Design + Java

  1. How to design a URL shortener in Java?

  2. How to design a parking lot system in Java?

  3. How to design an online book store?

  4. How to design a chat application?

  5. How to design a payment gateway?

  6. How to design a logging framework?

  7. How to design a caching system?

  8. How to design a search engine?

  9. How to design a rate limiter?

  10. How to design a notification system?

  11. How to scale a Java web app?

  12. Difference between vertical and horizontal scaling?

  13. What is CAP theorem?

  14. What is eventual consistency?

  15. What is leader election in distributed systems?

  16. How to design load balancer in Java?

  17. How to design file storage system in Java?

  18. How to design message queue system?

  19. What is Kafka in Java?

  20. Difference between Kafka and RabbitMQ?


24. Java Coding/Logic Questions

  1. Write a program to reverse a string in Java.

  2. Write a program to check palindrome string.

  3. Write a program to find factorial of a number.

  4. Write a program to generate Fibonacci series.

  5. Write a program to check prime number.

  6. Write a program to find largest element in array.

  7. Write a program to find smallest element in array.

  8. Write a program to sort an array.

  9. Write a program to search an element in array.

  10. Write a program to implement binary search.

  11. Write a program to implement linear search.

  12. Write a program to find duplicate elements in array.

  13. Write a program to find missing number in array.

  14. Write a program to count vowels and consonants in string.

  15. Write a program to count words in string.

  16. Write a program to swap two numbers without temp.

  17. Write a program to find second largest element.

  18. Write a program to implement stack in Java.

  19. Write a program to implement queue in Java.

  20. Write a program to implement linked list in Java.

  21. Write a program to reverse linked list.

  22. Write a program to check balanced parentheses.

  23. Write a program to implement binary tree.

  24. Write a program to implement binary search tree.

  25. Write a program to traverse tree (inorder, preorder, postorder).

  26. Write a program to find height of binary tree.

  27. Write a program to check mirror trees.

  28. Write a program to implement graph in Java.

  29. Write a program for BFS in graph.

  30. Write a program for DFS in graph.

  31. Write a program for Dijkstra’s algorithm.

  32. Write a program for Floyd Warshall algorithm.

  33. Write a program for LRU Cache in Java.

  34. Write a program for Producer-Consumer problem.

  35. Write a program for Dining Philosopher problem.

  36. Write a program to implement Singleton.

  37. Write a program to implement Factory Pattern.

  38. Write a program to implement Observer Pattern.

  39. Write a program to implement Strategy Pattern.

  40. Write a program to implement Proxy Pattern.


25. Tricky Java Questions

  1. Can we overload main() method in Java?

  2. Can we run Java program without main()?

  3. Why String is immutable in Java?

  4. Can we make constructor final?

  5. Can we make abstract method static?

  6. Can we override static method?

  7. Can we override private method?

  8. Can constructor be synchronized?

  9. What happens if we call System.exit() in try block?

  10. What happens if exception occurs in finally block?

  11. Can interface have private methods?

  12. Can we create object of interface using anonymous class?

  13. Can enum extend class in Java?

  14. Can enum implement interface?

  15. Can we use multiple public classes in one file?

  16. What happens if constructor throws exception?

  17. Can we serialize static variables?

  18. Can we serialize transient variables?

  19. Can we have two classes with same name in same package?

  20. Can abstract class have constructor?

  21. Can we achieve multiple inheritance in Java?

  22. What is diamond problem in Java?

  23. Why multiple inheritance is not supported in Java?

  24. Difference between shallow copy and deep copy?

  25. Why Java is platform independent?


26. Miscellaneous & Advanced

  1. What is Reactive Programming in Java?

  2. What is Project Reactor?

  3. What is RxJava?

  4. What is CompletableFuture?

  5. What is difference between Future and CompletableFuture?

  6. What is Java Flight Recorder (JFR)?

  7. What is GraalVM?

  8. What is Quarkus in Java?

  9. What is Micronaut framework?

  10. What is Jakarta EE?

  11. Difference between Java EE and Jakarta EE?

  12. What is SOAP vs REST in Java?

  13. What is gRPC in Java?

  14. What is WebFlux in Spring?

  15. What is Server-Sent Events (SSE) in Java?

  16. What is reactive streams in Java?

  17. What is backpressure in reactive programming?

  18. What is Akka in Java?

  19. What is Vert.x in Java?

  20. What is Domain Driven Design (DDD) in Java?

  21. What is Hexagonal Architecture in Java?

  22. What is Event Sourcing in Java?

  23. What is CQRS in Java?

  24. What is clean code principles in Java?

  25. What are best practices for Java programming?





๐ŸŸข Core Java Basics – Questions & Answers


1. What is Java?

๐Ÿ‘‰ Java is a high-level, object-oriented, platform-independent programming language.
It was developed by James Gosling at Sun Microsystems (1995).
The key feature of Java is “Write Once, Run Anywhere (WORA)”, meaning a program written in Java can run on any platform that has JVM.


2. What are the features of Java?

✅ Main features of Java:

  • Simple & easy to learn

  • Object-Oriented

  • Platform Independent (runs on JVM)

  • Secure

  • Robust (memory management, exception handling)

  • Multithreaded

  • High Performance (with JIT compiler)

  • Distributed (supports networking)


3. What is JVM, JRE, JDK?

  • JVM (Java Virtual Machine): Runs Java bytecode. It makes Java platform independent.

  • JRE (Java Runtime Environment): Contains JVM + libraries needed to run Java programs.

  • JDK (Java Development Kit): Contains JRE + tools (compiler javac, debugger, etc.) used for development.


4. Difference between JDK and JRE?

  • JDK: Used for development (includes compiler, debugger, tools).

  • JRE: Used only for running Java applications.

๐Ÿ‘‰ JDK = JRE + Development Tools


5. Explain the Java execution flow.

  1. Write code → Program.java

  2. Compile → javac Program.java → generates Program.class (bytecode)

  3. Run → java Program → JVM executes bytecode line by line.


6. What are data types in Java?

๐Ÿ‘‰ Java has two types of data types:

  • Primitive types (8 total):
    byte, short, int, long, float, double, char, boolean

  • Non-primitive types:
    Strings, Arrays, Classes, Objects, Interfaces.


7. What is type casting?

๐Ÿ‘‰ Type casting means converting one data type into another.

  • Widening (implicit): smaller → larger (int → double)

  • Narrowing (explicit): larger → smaller (double → int)


8. What are variables in Java?

๐Ÿ‘‰ Variable is a name that stores data value in memory.
Types:

  • Local variables (inside method)

  • Instance variables (inside class, non-static)

  • Static variables (declared with static, common to all objects)


9. What are literals in Java?

๐Ÿ‘‰ Literals are fixed values that a variable can hold.
Examples:

  • Integer literal → 10

  • Floating literal → 3.14

  • Boolean literal → true, false

  • Char literal → 'A'

  • String literal → "Hello"


10. Difference between primitive and non-primitive data types?

  • Primitive: predefined by Java (int, char, boolean, etc.), stored directly in memory.

  • Non-primitive: created by programmer (String, Arrays, Objects), store references to memory.


11. What is a wrapper class?

๐Ÿ‘‰ Wrapper classes convert primitive data types into objects.
Examples:

  • int → Integer

  • double → Double

  • boolean → Boolean


12. Explain autoboxing and unboxing.

  • Autoboxing: automatically converting primitive → object.

    int a = 5; Integer obj = a; // autoboxing
  • Unboxing: automatically converting object → primitive.

    Integer obj = 10; int b = obj; // unboxing

13. Difference between == and .equals()?

  • == compares memory references (address).

  • .equals() compares actual values (content).

String s1 = new String("Hello"); String s2 = new String("Hello"); System.out.println(s1 == s2); // false System.out.println(s1.equals(s2)); // true

14. What are operators in Java?

๐Ÿ‘‰ Operators are symbols used to perform operations.
Types:

  • Arithmetic (+, -, *, /, %)

  • Relational (==, !=, >, <, >=, <=)

  • Logical (&&, ||, !)

  • Assignment (=, +=, -=)

  • Bitwise (&, |, ^, ~, <<, >>)

  • Ternary (?:)


15. What is precedence of operators?

๐Ÿ‘‰ Precedence decides which operator executes first.
Example:

int x = 10 + 5 * 2; // result = 20 (multiplication has higher precedence than addition)

16. What is ternary operator?

๐Ÿ‘‰ Ternary operator ?: is a shorthand for if-else.

int age = 18; String result = (age >= 18) ? "Adult" : "Minor";

17. Difference between && and &?

  • &&Logical AND (checks second condition only if needed).

  • &Bitwise AND (always checks both conditions).


18. What are bitwise operators?

๐Ÿ‘‰ Bitwise operators work on bits (0/1).

  • AND → &

  • OR → |

  • XOR → ^

  • Complement → ~

  • Shift Left → <<

  • Shift Right → >>


19. What is instanceof operator?

๐Ÿ‘‰ Used to check whether an object belongs to a particular class or not.

String str = "Hello"; System.out.println(str instanceof String); // true

20. What are control statements in Java?

๐Ÿ‘‰ Control statements control the flow of execution:

  • Conditional → if, if-else, switch

  • Looping → for, while, do-while, for-each

  • Jump → break, continue, return




๐ŸŸข OOPs Concepts in Java – Questions & Answers


21. What is OOPs in Java?

๐Ÿ‘‰ OOPs (Object-Oriented Programming System) is a programming style where everything is represented as objects.
Java is purely object-oriented (except primitive types).


22. What are the main OOPs principles?

The 4 main pillars of OOPs are:

  1. Encapsulation – binding data and methods together.

  2. Inheritance – acquiring properties of another class.

  3. Polymorphism – one name, many forms (method overloading/overriding).

  4. Abstraction – hiding implementation details, showing only functionality.


23. What is a class in Java?

๐Ÿ‘‰ A class is a blueprint/template to create objects. It contains fields (variables) and methods.

class Car { String color; void drive() { System.out.println("Car is driving"); } }

24. What is an object in Java?

๐Ÿ‘‰ An object is an instance of a class. It has state (variables) and behavior (methods).

Car myCar = new Car(); // object created

25. What is the difference between class and object?

  • Class → blueprint, does not occupy memory.

  • Object → instance of class, occupies memory.


26. What is a constructor in Java?

๐Ÿ‘‰ Constructor is a special method used to initialize objects.

  • Same name as class.

  • No return type.

class Student { Student() { System.out.println("Object created"); } }

27. Types of constructors in Java?

  • Default Constructor → created automatically if no constructor is written.

  • Parameterized Constructor → takes parameters.

  • Copy Constructor (not built-in, but can be created by copying another object).


28. What is constructor overloading?

๐Ÿ‘‰ Defining multiple constructors with different parameter lists.

class Student { Student() {} Student(String name) {} Student(int age) {} }

29. What is the difference between constructor and method?

  • Constructor → used to initialize object, no return type.

  • Method → used to define behavior, must have return type (or void).


30. What is this keyword in Java?

๐Ÿ‘‰ this refers to the current object.
Uses:

  • To access instance variables.

  • To call another constructor.

  • To pass current object as parameter.


31. What is super keyword in Java?

๐Ÿ‘‰ super is used to refer to parent class members.
Uses:

  • Access parent variables.

  • Call parent methods.

  • Call parent constructor.


32. What is inheritance in Java?

๐Ÿ‘‰ Inheritance allows one class to acquire properties and methods of another class using the extends keyword.

class Parent {} class Child extends Parent {}

33. Types of inheritance in Java?

  • Single Inheritance → one parent, one child.

  • Multilevel Inheritance → class inherits from another child class.

  • Hierarchical Inheritance → one parent, many children.

๐Ÿ‘‰ Note: Java does not support multiple inheritance (to avoid ambiguity).


34. What is method overloading?

๐Ÿ‘‰ Same method name, different parameter list (compile-time polymorphism).

void add(int a, int b) {} void add(double a, double b) {}

35. What is method overriding?

๐Ÿ‘‰ Redefining a parent class method in child class (runtime polymorphism).

class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { void sound() { System.out.println("Bark"); } }

36. Difference between overloading and overriding?

OverloadingOverriding
Same method name, different parametersSame method name, same parameters
Compile-time polymorphismRuntime polymorphism
Can be done within one classRequires inheritance

37. What is polymorphism?

๐Ÿ‘‰ Polymorphism = many forms.

  • Compile-time → method overloading.

  • Runtime → method overriding.


38. What is encapsulation?

๐Ÿ‘‰ Encapsulation = binding data (variables) and methods together in a class.
✅ Use of private variables + public getters/setters.

class Student { private String name; public void setName(String n) { name = n; } public String getName() { return name; } }

39. What is abstraction?

๐Ÿ‘‰ Abstraction = hiding implementation details, showing only necessary features.

  • Achieved using abstract classes and interfaces.


40. Difference between abstraction and encapsulation?

  • Abstraction → Hides implementation (what to do).

  • Encapsulation → Hides data (how to protect it).


๐ŸŸข Strings & Arrays in Java – Questions & Answers


41. What is a String in Java?

๐Ÿ‘‰ A String is a sequence of characters enclosed in double quotes (" ").
Example:

String s = "Hello Java";

๐Ÿ‘‰ In Java, String is a class in java.lang package.


42. How are Strings stored in Java?

  • Strings in Java are immutable (cannot be changed once created).

  • Stored in String Constant Pool (SCP) for memory efficiency.


43. Difference between String, StringBuilder, and StringBuffer?

  • String → Immutable.

  • StringBuilder → Mutable, fast (not thread-safe).

  • StringBuffer → Mutable, thread-safe (slower than StringBuilder).


44. How to create a String in Java?

Two ways:

String s1 = "Hello"; // String literal String s2 = new String("Hi"); // Using new keyword

45. What are common String methods in Java?

  • length() → returns length

  • charAt(int i) → returns character at position

  • substring(start, end) → extract substring

  • toUpperCase(), toLowerCase()

  • equals(), equalsIgnoreCase()

  • trim() → removes spaces

  • replace() → replaces characters


46. How to compare two Strings in Java?

  • equals() → compares values

  • == → compares memory references

  • compareTo() → compares lexicographically


47. What is String immutability?

๐Ÿ‘‰ Once a String is created, it cannot be changed.
Any modification creates a new String object.


48. Why are Strings immutable in Java?

  • Security (used in passwords, networking).

  • Thread-safety.

  • String Pool optimization.


49. What is String Pool?

๐Ÿ‘‰ A special memory area in heap where String literals are stored.

  • If a String already exists in the pool, Java reuses it instead of creating a new one.


50. Difference between equals() and == in Strings?

  • == → checks reference (memory location).

  • equals() → checks content (value).


51. What is an array in Java?

๐Ÿ‘‰ An array is a collection of similar data types stored in contiguous memory.
Example:

int arr[] = {1, 2, 3, 4, 5};

52. How to declare and initialize an array in Java?

int arr[] = new int[5]; // declaration with size arr[0] = 10; // initialization

53. What are the types of arrays in Java?

  • Single-dimensionalint arr[] = new int[5];

  • Multi-dimensionalint arr[][] = new int[3][3];


54. What is the default value of array elements in Java?

  • Numeric types → 0

  • Boolean → false

  • Object references → null


55. Difference between length and length() in Java?

  • Array: arr.length → property (no brackets).

  • String: str.length() → method (with brackets).


56. How to copy an array in Java?

  • Using loop

  • Using System.arraycopy()

  • Using Arrays.copyOf()

  • Using clone()


57. What is Arrays class in Java?

๐Ÿ‘‰ java.util.Arrays provides utility methods for arrays:

  • sort() → sort array

  • binarySearch() → search element

  • equals() → compare arrays

  • fill() → fill with values


58. What is Jagged Array in Java?

๐Ÿ‘‰ An array of arrays where rows can have different column sizes.

int arr[][] = new int[3][]; arr[0] = new int[2]; arr[1] = new int[3]; arr[2] = new int[4];

59. Difference between Array and ArrayList?

FeatureArrayArrayList
SizeFixedDynamic
Data TypePrimitive & ObjectsObjects only
PerformanceFastSlightly slower
UtilitiesNo built-in methodsMany useful methods

60. What are limitations of arrays in Java?

  • Fixed size (cannot grow/shrink).

  • Cannot store different data types.

  • No built-in methods for searching, sorting.


๐ŸŸข Exception Handling in Java – Questions & Answers


61. What is an exception in Java?

๐Ÿ‘‰ An exception is an unwanted event that disrupts the normal flow of a program.
Example: dividing by zero, accessing an invalid array index.


62. What is exception handling?

๐Ÿ‘‰ Exception handling is a mechanism to handle runtime errors so the program doesn’t crash.
It uses try, catch, finally, throw, and throws.


63. What is the difference between error and exception?

  • Error → serious issues (like OutOfMemoryError) that can’t be handled.

  • Exception → problems that can be handled (like NullPointerException).


64. Types of exceptions in Java?

  1. Checked Exceptions → Checked at compile time (e.g., IOException, SQLException).

  2. Unchecked Exceptions → Occur at runtime (e.g., NullPointerException, ArithmeticException).


65. What are checked exceptions?

๐Ÿ‘‰ Exceptions that must be handled at compile time using try-catch or throws.
Example: IOException, SQLException.


66. What are unchecked exceptions?

๐Ÿ‘‰ Exceptions that occur at runtime and don’t need explicit handling.
Example: NullPointerException, ArrayIndexOutOfBoundsException.


67. What is try-catch block in Java?

๐Ÿ‘‰ try contains risky code, catch handles exceptions.

try { int a = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); }

68. Can we have multiple catch blocks?

๐Ÿ‘‰ Yes, a try block can have multiple catch blocks for different exceptions.


69. What is finally block?

๐Ÿ‘‰ finally always executes, whether exception occurs or not.
Used to release resources like closing files or database connections.


70. Difference between final, finally, and finalize()?

  • final → keyword (for constants, methods, classes).

  • finally → block for cleanup code.

  • finalize() → method called by Garbage Collector before object is destroyed.


71. What is throw keyword?

๐Ÿ‘‰ Used to explicitly throw an exception inside a method.

throw new ArithmeticException("Cannot divide");

72. What is throws keyword?

๐Ÿ‘‰ Used in method declaration to declare checked exceptions.

void readFile() throws IOException { ... }

73. Difference between throw and throws?

  • throw → used to actually throw an exception.

  • throws → used to declare possible exceptions in method signature.


74. What is NullPointerException?

๐Ÿ‘‰ Occurs when we try to access methods or variables of a null object.

String s = null; System.out.println(s.length()); // NullPointerException

75. What is try-with-resources in Java?

๐Ÿ‘‰ Introduced in Java 7, it automatically closes resources (like files, DB connections).

try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) { System.out.println(br.readLine()); }

76. Can we write try without catch?

๐Ÿ‘‰ Yes, but only if followed by finally.

try { int a = 10 / 2; } finally { System.out.println("Always executes"); }

77. Can we catch multiple exceptions in one block?

๐Ÿ‘‰ Yes, using | operator (Java 7+).

catch (IOException | SQLException e) { e.printStackTrace(); }

78. What is custom exception in Java?

๐Ÿ‘‰ User-defined exceptions by extending Exception or RuntimeException.

class MyException extends Exception { MyException(String msg) { super(msg); } }

79. Difference between Exception and RuntimeException?

  • Exception → checked (must be handled).

  • RuntimeException → unchecked (handled at runtime).


80. Best practices for exception handling in Java?

✅ Some good practices are:

  • Don’t swallow exceptions (always handle them).

  • Use specific exceptions (not just Exception).

  • Close resources in finally or use try-with-resources.

  • Don’t use exceptions for normal flow.


๐ŸŸข Collections Framework in Java – Questions & Answers


81. What is the Collections Framework in Java?

๐Ÿ‘‰ The Collections Framework is a set of classes and interfaces in java.util package that provide data structures (like List, Set, Map) and algorithms (sorting, searching).


82. What is the difference between Collection and Collections?

  • Collection (interface) → root interface of all collection classes.

  • Collections (class) → utility class with methods like sort(), reverse(), shuffle().


83. What are the main interfaces of the Collections Framework?

  • List → ordered, allows duplicates (ArrayList, LinkedList).

  • Set → unordered, no duplicates (HashSet, TreeSet).

  • Queue → follows FIFO (PriorityQueue, LinkedList).

  • Map → key-value pairs (HashMap, TreeMap).


84. What is List in Java?

๐Ÿ‘‰ A collection that is ordered and allows duplicate elements.
Implementations: ArrayList, LinkedList, Vector, Stack.


85. Difference between ArrayList and LinkedList?

FeatureArrayListLinkedList
StorageDynamic arrayDoubly linked list
AccessFast (index-based)Slower
Insert/DeleteSlower (shifting)Faster (no shifting)

86. What is a Set in Java?

๐Ÿ‘‰ A collection that does not allow duplicates.
Implementations: HashSet, LinkedHashSet, TreeSet.


87. Difference between HashSet, LinkedHashSet, and TreeSet?

  • HashSet → no order, fast.

  • LinkedHashSet → maintains insertion order.

  • TreeSet → sorted order (ascending by default).


88. What is a Map in Java?

๐Ÿ‘‰ A collection of key-value pairs.
Keys are unique, values can be duplicate.
Implementations: HashMap, LinkedHashMap, TreeMap, Hashtable.


89. Difference between HashMap and Hashtable?

  • HashMap → not synchronized, allows null keys/values.

  • Hashtable → synchronized, does not allow null.


90. Difference between HashMap and TreeMap?

  • HashMap → unordered, faster.

  • TreeMap → maintains sorted order of keys.


91. What is the difference between List and Set?

  • List → ordered, allows duplicates.

  • Set → unordered, no duplicates.


92. What is Iterator in Java?

๐Ÿ‘‰ An object used to iterate elements of a collection.
Methods:

  • hasNext() → checks if element exists

  • next() → returns next element

  • remove() → removes element


93. Difference between Iterator and ListIterator?

  • Iterator → works for all collections, only forward.

  • ListIterator → works only for List, supports forward & backward traversal.


94. What is fail-fast and fail-safe Iterator?

  • Fail-fast → throws ConcurrentModificationException if collection is modified while iterating (e.g., Iterator of ArrayList, HashMap).

  • Fail-safe → does not throw exception (e.g., CopyOnWriteArrayList, ConcurrentHashMap).


95. Difference between Enumeration, Iterator, and ListIterator?

  • Enumeration → legacy, only forward (Vector).

  • Iterator → forward, remove elements.

  • ListIterator → forward + backward, works only with List.


96. How to sort a collection in Java?

๐Ÿ‘‰ Using Collections.sort() method.

List<String> list = new ArrayList<>(); list.add("C"); list.add("A"); list.add("B"); Collections.sort(list); // [A, B, C]

97. What is Comparable interface in Java?

๐Ÿ‘‰ Used to define natural sorting order of objects.

class Student implements Comparable<Student> { int age; public int compareTo(Student s) { return this.age - s.age; } }

98. What is Comparator interface in Java?

๐Ÿ‘‰ Used to define custom sorting order (external).

Comparator<Student> byName = (s1, s2) -> s1.name.compareTo(s2.name);

99. Difference between Comparable and Comparator?

FeatureComparableComparator
Packagejava.langjava.util
SortingNatural orderCustom order
MethodcompareTo()compare()

100. What are concurrent collections in Java?

๐Ÿ‘‰ Thread-safe collection classes introduced in java.util.concurrent package.
Examples:

  • ConcurrentHashMap

  • CopyOnWriteArrayList

  • BlockingQueue


๐ŸŸข Multithreading in Java – Questions & Answers


101. What is multithreading in Java?

๐Ÿ‘‰ Multithreading is a feature that allows multiple threads to run concurrently in a program.
It improves performance by utilizing CPU more efficiently.


102. What is a thread in Java?

๐Ÿ‘‰ A thread is the smallest unit of execution.
A Java program can have multiple threads running at the same time.


103. Difference between process and thread?

  • Process → independent program with its own memory.

  • Thread → lightweight, shares memory of the process.


104. How to create a thread in Java?

Two ways:

  1. Extending Thread class

class MyThread extends Thread { public void run() { System.out.println("Thread running"); } }
  1. Implementing Runnable interface

class MyTask implements Runnable { public void run() { System.out.println("Runnable running"); } }

105. Which is better: extending Thread or implementing Runnable?

๐Ÿ‘‰ Implementing Runnable is better because Java supports only single inheritance.
Using Runnable allows the class to extend another class if needed.


106. What is the lifecycle of a thread?

A thread goes through these states:

  1. New

  2. Runnable

  3. Running

  4. Waiting / Sleeping

  5. Terminated


107. What is the difference between start() and run()?

  • start() → creates a new thread and calls run() internally.

  • run() → just a normal method call, no new thread created.


108. What is thread priority in Java?

๐Ÿ‘‰ Each thread has a priority (1 to 10).

  • MIN_PRIORITY = 1

  • NORM_PRIORITY = 5 (default)

  • MAX_PRIORITY = 10


109. What is daemon thread in Java?

๐Ÿ‘‰ A daemon thread is a background service thread that ends when all user threads finish.
Example: Garbage Collector.


110. How to create a daemon thread?

Thread t = new Thread(); t.setDaemon(true); t.start();

111. What is synchronization in Java?

๐Ÿ‘‰ Synchronization ensures that only one thread accesses a shared resource at a time.
It prevents data inconsistency in multithreading.


112. How to achieve synchronization in Java?

  • Using synchronized keyword (method or block).

  • Using locks (ReentrantLock).


113. Difference between synchronized method and synchronized block?

  • Synchronized method → locks the entire method.

  • Synchronized block → locks only a specific part of the code. (more efficient).


114. What is deadlock in Java?

๐Ÿ‘‰ Deadlock happens when two or more threads wait forever for each other’s resources.


115. How to prevent deadlock?

✅ Best practices:

  • Avoid nested locks.

  • Acquire locks in the same order.

  • Use tryLock() with timeout.


116. What is inter-thread communication?

๐Ÿ‘‰ Mechanism where threads communicate and coordinate with each other.
Achieved using wait(), notify(), and notifyAll().


117. Difference between wait(), notify(), and notifyAll()?

  • wait() → makes thread wait and releases lock.

  • notify() → wakes up one waiting thread.

  • notifyAll() → wakes up all waiting threads.


118. What is volatile keyword in Java?

๐Ÿ‘‰ volatile ensures that a variable’s value is always read from main memory, not from thread cache.


119. Difference between volatile and synchronized?

  • volatile → ensures visibility of variable across threads.

  • synchronized → ensures atomicity + visibility (full thread safety).


120. What is thread pool in Java?

๐Ÿ‘‰ A thread pool is a group of pre-created threads used to execute tasks efficiently.
Java provides it via ExecutorService.

ExecutorService executor = Executors.newFixedThreadPool(5);



๐ŸŸข Java I/O & File Handling – Questions & Answers


121. What is I/O in Java?

๐Ÿ‘‰ I/O (Input/Output) is used to read data from input devices or files and write data to output devices or files.
Java provides java.io and java.nio packages for I/O operations.


122. What are the types of streams in Java?

  • Byte Streams → read/write 1 byte at a time (InputStream, OutputStream).

  • Character Streams → read/write characters (Reader, Writer).


123. Difference between byte stream and character stream?

FeatureByte StreamCharacter Stream
Reads/Writes1 byte1 character
ClassesInputStream, OutputStreamReader, Writer
Used forBinary dataText data

124. What is File class in Java?

๐Ÿ‘‰ java.io.File represents a file or directory path.
It cannot read/write data, only used for metadata and file operations.

File file = new File("test.txt"); System.out.println(file.exists());

125. How to read a file in Java?

  • Using FileReader (character stream)

  • Using BufferedReader (efficient reading line by line)

  • Using Scanner class

Example:

BufferedReader br = new BufferedReader(new FileReader("test.txt")); String line; while((line = br.readLine()) != null){ System.out.println(line); } br.close();

126. How to write to a file in Java?

  • Using FileWriter (character stream)

  • Using BufferedWriter (efficient)
    Example:

BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt")); bw.write("Hello Java"); bw.close();

127. Difference between FileWriter and BufferedWriter?

  • FileWriter → writes directly to file (slower).

  • BufferedWriter → writes to buffer first, then to file (faster).


128. What is the difference between FileInputStream and FileReader?

  • FileInputStream → reads bytes, used for binary data.

  • FileReader → reads characters, used for text files.


129. What is the difference between FileOutputStream and FileWriter?

  • FileOutputStream → writes bytes, used for binary files.

  • FileWriter → writes characters, used for text files.


130. What is BufferedReader and BufferedWriter?

  • BufferedReader → reads text efficiently, line by line.

  • BufferedWriter → writes text efficiently, with buffer.


131. What is the difference between read() and readLine()?

  • read() → reads one character at a time.

  • readLine() → reads one line at a time.


132. What is PrintWriter in Java?

๐Ÿ‘‰ PrintWriter provides convenient methods like println() for writing formatted text to files.

PrintWriter pw = new PrintWriter("out.txt"); pw.println("Hello"); pw.close();

133. What is RandomAccessFile in Java?

๐Ÿ‘‰ Allows reading and writing at any position in a file.
Useful for editing files without loading the entire content.


134. What is ObjectOutputStream and ObjectInputStream?

  • ObjectOutputStream → writes objects to a file (serialization).

  • ObjectInputStream → reads objects from a file (deserialization).


135. What is serialization in Java?

๐Ÿ‘‰ Serialization = converting an object into byte stream to save in file or send over network.


136. What is deserialization in Java?

๐Ÿ‘‰ Deserialization = converting byte stream back into an object.


137. What is the difference between File.exists() and File.createNewFile()?

  • exists() → checks if file exists.

  • createNewFile() → creates a new file if it does not exist.


138. How to delete a file in Java?

File file = new File("test.txt"); file.delete(); // deletes the file

139. How to list all files in a directory?

File dir = new File("myFolder"); String[] files = dir.list(); for(String f : files){ System.out.println(f); }

140. Difference between File and Path in Java NIO?

  • File (java.io) → older API, less flexible.

  • Path (java.nio.file) → newer API, supports advanced operations (like symbolic links, streams).


๐ŸŸข JVM & Performance – Questions & Answers


141. What is JVM in Java?

๐Ÿ‘‰ JVM (Java Virtual Machine) is a virtual machine that runs Java bytecode on any platform.
It makes Java platform-independent.


142. What are the main components of JVM?

  1. Class Loader – loads .class files.

  2. Runtime Data Areas – memory areas like Heap, Stack, Method Area.

  3. Execution Engine – executes bytecode.

  4. Native Method Interface – calls platform-specific methods.

  5. Garbage Collector – automatically frees memory.


143. What is JIT compiler?

๐Ÿ‘‰ JIT (Just-In-Time) compiler converts bytecode to native code at runtime to improve performance.


144. Difference between JVM, JRE, and JDK?

ComponentPurpose
JVMExecutes Java bytecode
JREJVM + libraries for running programs
JDKJRE + tools for development

145. What is bytecode in Java?

๐Ÿ‘‰ Bytecode is platform-independent code generated after compiling a .java file.
It runs on JVM.


146. What are the types of memory in JVM?

  1. Heap Memory – stores objects.

  2. Stack Memory – stores method calls & local variables.

  3. Method Area – stores class structures.

  4. Program Counter (PC) Register – keeps track of next instruction.

  5. Native Method Stack – memory for native (C/C++) methods.


147. What is garbage collection in Java?

๐Ÿ‘‰ Garbage Collection (GC) is the process of automatically removing unused objects to free memory.


148. How to suggest garbage collection in Java?

System.gc(); Runtime.getRuntime().gc();

✅ Note: JVM decides when to actually run GC.


149. Difference between stack memory and heap memory?

FeatureStackHeap
StoresLocal variables, method callsObjects
SizeSmallerLarger
AccessFasterSlower
LifeShort-livedLong-lived

150. What is the difference between final, finally, and finalize()?

  • final → keyword (constants, prevent inheritance).

  • finally → block that always executes.

  • finalize() → method called by GC before destroying object.


151. What are strong, soft, weak, and phantom references in Java?

  • Strong → normal reference, prevents GC.

  • Soft → collected only if memory is low.

  • Weak → collected in next GC cycle.

  • Phantom → used to track object post-GC cleanup.


152. What is the difference between == and .equals() in JVM context?

  • == → compares memory address (reference).

  • .equals() → compares content/value.


153. What are the types of class loaders in JVM?

  1. Bootstrap Class Loader → loads core Java classes.

  2. Extension Class Loader → loads extension libraries.

  3. System/Application Class Loader → loads classes from classpath.


154. Difference between stack overflow and heap overflow?

  • StackOverflowError → too many method calls / recursion.

  • OutOfMemoryError (Heap) → memory exhausted for objects.


155. What is performance tuning in Java?

๐Ÿ‘‰ Process of optimizing Java program for speed, memory usage, and efficiency.


156. How to improve Java performance?

  • Use efficient algorithms and data structures.

  • Minimize object creation.

  • Use StringBuilder for string concatenation.

  • Properly tune Garbage Collector.

  • Use multithreading for concurrent tasks.


157. What is lazy loading in Java?

๐Ÿ‘‰ Objects are created only when required to save memory.
Example: Singleton pattern with lazy initialization.


158. What is eager loading in Java?

๐Ÿ‘‰ Objects are created at the time of class loading, regardless of use.


159. Difference between JVM and JIT compiler?

  • JVM → executes bytecode, manages memory.

  • JIT Compiler → converts bytecode to native code at runtime for performance.


160. What is memory leak in Java?

๐Ÿ‘‰ Memory leak happens when unused objects are not garbage collected due to lingering references.
It can lead to OutOfMemoryError.



๐ŸŸข Java Annotations & Reflection – Questions & Answers


161. What is an annotation in Java?

๐Ÿ‘‰ An annotation is a metadata that provides information about code to the compiler or runtime.
Example: @Override, @Deprecated.


162. What are the types of annotations in Java?

  1. Built-in annotations@Override, @Deprecated, @SuppressWarnings

  2. Custom annotations → user-defined using @interface.


163. What is @Override annotation?

๐Ÿ‘‰ Indicates that a method overrides a parent class method.

@Override void display() { ... }


164. What is @Deprecated annotation?

๐Ÿ‘‰ Marks a method or class as outdated, discouraging its use.

@Deprecated void oldMethod() { ... }


165. What is @SuppressWarnings annotation?

๐Ÿ‘‰ Tells compiler to ignore specific warnings.

@SuppressWarnings("unchecked") List list = new ArrayList();


166. How to create a custom annotation?

@interface MyAnnotation { String value(); int number() default 0; }


167. What is retention policy in Java annotations?

Specifies how long an annotation is retained:

  • SOURCE → discarded after compilation.

  • CLASS → in .class file, but not at runtime.

  • RUNTIME → available at runtime via reflection.


168. What is reflection in Java?

๐Ÿ‘‰ Reflection allows examining or modifying classes, methods, fields at runtime.
Example: get class name, method names, or invoke a method dynamically.


169. Which package is used for reflection in Java?

๐Ÿ‘‰ java.lang.reflect


170. How to get class object in Java?

Three ways:

  1. Class.forName("ClassName")

  2. object.getClass()

  3. ClassName.class


171. How to get method info using reflection?

Method[] methods = MyClass.class.getMethods(); for(Method m : methods) { System.out.println(m.getName()); }


172. How to invoke a method using reflection?

Method m = MyClass.class.getMethod("sayHello"); m.invoke(myObject);


173. How to access private fields using reflection?

Field f = MyClass.class.getDeclaredField("name"); f.setAccessible(true); f.set(myObject, "Rehan");


174. What are advantages of reflection?

  • Dynamically inspect or modify classes.

  • Useful for frameworks like Spring, Hibernate, JUnit.

  • Allows dynamic method invocation.


175. What are disadvantages of reflection?

  • Slower performance.

  • Breaks encapsulation.

  • Security risks if misused.


176. Difference between annotations and reflection?

FeatureAnnotationReflection
PurposeMetadataInspect/modify code
UsageCompile-time or runtimeRuntime
Example@Override, @DeprecatedgetMethods(), getFields()


177. What is @FunctionalInterface?

๐Ÿ‘‰ Indicates an interface with exactly one abstract method.
Useful for lambda expressions.

@FunctionalInterface interface MyFunc { void execute(); }


178. What is meta-annotation?

๐Ÿ‘‰ An annotation that applies to other annotations.
Examples: @Target, @Retention, @Documented, @Inherited.


179. What is @Target annotation?

๐Ÿ‘‰ Specifies where an annotation can be applied: class, method, field, parameter, etc.

@Target(ElementType.METHOD) @interface MyAnnotation { }


180. What is @Retention annotation?

๐Ÿ‘‰ Specifies how long the annotation is retained (SOURCE, CLASS, RUNTIME).

@Retention(RetentionPolicy.RUNTIME) @interface MyAnnotation { }


๐ŸŸข Java Networking – Questions & Answers


181. What is Java Networking?

๐Ÿ‘‰ Java Networking is a set of APIs that allows communication between computers over a network using TCP/IP protocols.
Package: java.net.


182. What is a socket in Java?

๐Ÿ‘‰ A socket is an endpoint for communication between two machines over a network.

  • ServerSocket → server side

  • Socket → client side


183. How to create a server socket in Java?

ServerSocket server = new ServerSocket(5000); Socket client = server.accept();

184. How to create a client socket in Java?

Socket socket = new Socket("localhost", 5000);

185. What is the difference between TCP and UDP?

FeatureTCPUDP
ConnectionConnection-orientedConnectionless
ReliabilityReliableUnreliable
SpeedSlowerFaster
UseFile transfer, EmailVideo streaming, DNS

186. What is InetAddress in Java?

๐Ÿ‘‰ Represents IP address of a host.

InetAddress address = InetAddress.getByName("www.google.com"); System.out.println(address.getHostAddress());

187. What is the difference between IP and URL?

  • IP → identifies a device on the network (e.g., 192.168.1.1)

  • URL → identifies a resource on the web (e.g., https://www.google.com)


188. How to get local IP address in Java?

InetAddress local = InetAddress.getLocalHost(); System.out.println(local.getHostAddress());

189. What is URL class in Java?

๐Ÿ‘‰ Represents a Uniform Resource Locator (web address).
Methods: getProtocol(), getHost(), getPath().


190. How to read data from a URL?

URL url = new URL("https://example.com"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while((line = br.readLine()) != null){ System.out.println(line); } br.close();

191. What is HTTPURLConnection in Java?

๐Ÿ‘‰ Allows sending HTTP requests (GET, POST) and receiving responses.


192. How to send a GET request in Java?

URL url = new URL("https://example.com"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));

193. How to send a POST request in Java?

URL url = new URL("https://example.com"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); OutputStream os = con.getOutputStream(); os.write("data=value".getBytes()); os.flush();

194. What is the difference between URL and URI in Java?

  • URL → specifies location of resource and how to access it.

  • URI → identifies a resource by name only.


195. What is DatagramSocket and DatagramPacket?

  • DatagramSocket → endpoint for sending/receiving UDP packets.

  • DatagramPacket → represents a UDP packet (data + address + port).


196. Difference between TCP and UDP sockets in Java?

FeatureTCP SocketUDP Socket
ConnectionConnection-orientedConnectionless
ReliabilityReliableUnreliable
Data unitStreamDatagram
ClassesSocket, ServerSocketDatagramSocket, DatagramPacket

197. What is multicast in Java?

๐Ÿ‘‰ Multicast allows sending a message to multiple hosts in a group simultaneously.
Uses MulticastSocket.


198. What is loopback address in Java?

๐Ÿ‘‰ 127.0.0.1 is the loopback address used to test network on local machine.


199. How to check if a host is reachable in Java?

InetAddress address = InetAddress.getByName("www.google.com"); System.out.println(address.isReachable(5000)); // timeout in ms

200. What is port in Java Networking?

๐Ÿ‘‰ A port is a logical communication endpoint on a machine (0–65535).
Common ports: HTTP → 80, HTTPS → 443, FTP → 21.


๐ŸŸข Java Generics – Questions & Answers


201. What are Generics in Java?

๐Ÿ‘‰ Generics allow you to write classes, interfaces, and methods with type parameters.
It provides type safety and reduces casting.

List<String> list = new ArrayList<>();


202. What is the purpose of Generics?

  • Type safety at compile time

  • Eliminate type casting

  • Reusable code


203. How to declare a generic class?

class Box<T> { private T value; void set(T value) { this.value = value; } T get() { return value; } }


204. How to declare a generic method?

public <T> void printArray(T[] array){ for(T element : array){ System.out.println(element); } }


205. What is type parameter in Generics?

๐Ÿ‘‰ A type parameter is a placeholder for a specific type, usually T, E, K, V.
Example: class Box<T> { ... }


206. What is type inference in Java Generics?

๐Ÿ‘‰ Java automatically infers the type from context.

Box<Integer> box = new Box<>(); // type inferred as Integer


207. What are bounded type parameters?

๐Ÿ‘‰ Restricts the type parameter to subclass or implement interface.

class Numbers<T extends Number> { ... }


208. What is wildcard in Generics?

๐Ÿ‘‰ A wildcard ? represents an unknown type.

List<?> list = new ArrayList<String>();


209. What are the types of wildcards in Java?

  1. Unbounded<?>

  2. Upper bounded<? extends ClassName>

  3. Lower bounded<? super ClassName>


210. Difference between extends and super in Generics?

  • <? extends T> → accepts T or its subclasses (read-only).

  • <? super T> → accepts T or its superclasses (write allowed).


211. Can we create an array of generic type?

❌ No, due to type erasure.
✅ Workaround: use ArrayList instead of array.


212. What is type erasure in Java Generics?

๐Ÿ‘‰ At runtime, Java removes generic type information to maintain backward compatibility.


213. Can we use primitives with Generics?

❌ No, Generics work with objects only.
✅ Use wrapper classes (Integer, Double) instead.


214. What is the difference between generic class and generic method?

FeatureGeneric ClassGeneric Method
Type parameterClass-levelMethod-level
UsageApplies to entire classApplies only to method
Exampleclass Box<T><T> void print(T data)


215. Can we extend a generic class?

✅ Yes, we can extend generic classes with or without specifying type.

class Box<T> { ... } class SpecialBox extends Box<Integer> { ... }


216. Can we implement a generic interface?

✅ Yes, either specify type or remain generic.

interface Container<T> { void add(T t); } class Box implements Container<Integer> { ... }


217. What is PECS rule in Generics?

Producer Extends, Consumer Super

  • <? extends T> → producer (read)

  • <? super T> → consumer (write)


218. Can we use multiple bounds in Generics?

✅ Yes, with & symbol.

<T extends Number & Comparable<T>>


219. Can we have static members in a generic class?

✅ Yes, but static members cannot use the class type parameter.


220. Can Generics be used with enums?

✅ Yes, Generics can work with enums like any other class.



๐ŸŸข Java Lambda Expressions & Stream API – Questions & Answers


221. What is a Lambda Expression in Java?

๐Ÿ‘‰ Lambda Expression is a short form of writing anonymous methods.
It helps write functional-style code.

(numbers) -> numbers * 2


222. Syntax of Lambda Expression?

(parameters) -> expression or (parameters) -> { statements; }


223. What are the types of Lambda Expressions?

  1. No parameter() -> System.out.println("Hello")

  2. One parameterx -> x * x

  3. Multiple parameters(x, y) -> x + y


224. Difference between Lambda and Anonymous Class?

FeatureLambdaAnonymous Class
SyntaxShort, conciseVerbose
thisRefers to enclosing classRefers to anonymous object
UseFunctional interfacesAny interface or class


225. What is a functional interface?

๐Ÿ‘‰ An interface with exactly one abstract method.
Example: Runnable, Callable, Comparator.
Annotation: @FunctionalInterface


226. How to use Lambda with Collections?

List<String> list = Arrays.asList("A", "B", "C"); list.forEach(s -> System.out.println(s));


227. What is the Stream API in Java?

๐Ÿ‘‰ Stream API allows processing collections in a functional style (filter, map, reduce).


228. Difference between Collection and Stream?

FeatureCollectionStream
StorageStores dataDoes not store data
ProcessingExternal iterationInternal iteration
MutabilityCan modifyCannot modify source


229. How to create a Stream in Java?

  • From Collection: list.stream()

  • From array: Arrays.stream(arr)

  • Using Stream API: Stream.of(1,2,3)


230. What are intermediate and terminal operations in Streams?

  • Intermediate → returns Stream, lazy (e.g., filter, map)

  • Terminal → returns result or side-effect, triggers processing (e.g., collect, forEach)


231. How to filter elements using Stream?

List<Integer> list = Arrays.asList(1,2,3,4); list.stream().filter(n -> n % 2 == 0).forEach(System.out::println);


232. How to map elements using Stream?

list.stream().map(n -> n * n).forEach(System.out::println);


233. How to sort elements using Stream?

list.stream().sorted().forEach(System.out::println);


234. How to collect Stream elements into a list?

List<Integer> result = list.stream().filter(n -> n > 2).collect(Collectors.toList());


235. What is forEach() in Stream?

๐Ÿ‘‰ Iterates over elements and performs action.

list.stream().forEach(System.out::println);


236. What is reduce() in Stream?

๐Ÿ‘‰ Performs aggregation on elements to produce a single value.

int sum = list.stream().reduce(0, (a,b) -> a + b);


237. What is distinct() in Stream?

๐Ÿ‘‰ Removes duplicate elements from the Stream.

list.stream().distinct().forEach(System.out::println);


238. What is limit() and skip() in Stream?

  • limit(n) → takes first n elements

  • skip(n) → skips first n elements

list.stream().skip(1).limit(2).forEach(System.out::println);


239. What is parallel stream?

๐Ÿ‘‰ Parallel stream processes elements concurrently using multiple threads.

list.parallelStream().forEach(System.out::println);


240. Difference between stream() and parallelStream()?

Feature stream() parallelStream()
Processing Sequential Parallel (multi-threaded)
Performance Slower for large data Faster for large data
Order Maintains order May not maintain order


๐ŸŸข Java Design Patterns – Questions & Answers


241. What is a design pattern in Java?

๐Ÿ‘‰ A design pattern is a reusable solution to a common software problem.
It provides a template for solving issues in software design.


242. Types of design patterns in Java?

  1. Creational → Object creation patterns (Singleton, Factory, Builder)

  2. Structural → Object composition patterns (Adapter, Decorator, Proxy)

  3. Behavioral → Object interaction patterns (Observer, Strategy, Command)


243. What is the Singleton pattern?

๐Ÿ‘‰ Ensures only one instance of a class exists.

class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if(instance == null) instance = new Singleton(); return instance; } }

244. What is the Factory pattern?

๐Ÿ‘‰ Factory pattern creates objects without exposing the instantiation logic.

class ShapeFactory { Shape getShape(String type) { if(type.equals("Circle")) return new Circle(); else return new Rectangle(); } }

245. What is the Builder pattern?

๐Ÿ‘‰ Builder pattern is used to construct complex objects step by step.

class CarBuilder { Car car = new Car(); CarBuilder setColor(String color){ car.color=color; return this; } Car build(){ return car; } }

246. What is the Prototype pattern?

๐Ÿ‘‰ Prototype pattern creates objects by cloning an existing object.

class CloneDemo implements Cloneable { public Object clone() throws CloneNotSupportedException { return super.clone(); } }

247. What is the Adapter pattern?

๐Ÿ‘‰ Adapter pattern converts one interface to another.

class Adapter implements Target { Adaptee adaptee = new Adaptee(); public void request() { adaptee.specificRequest(); } }

248. What is the Decorator pattern?

๐Ÿ‘‰ Decorator pattern adds new functionality to objects dynamically.

class CoffeeDecorator extends Coffee { Coffee coffee; CoffeeDecorator(Coffee c){ this.coffee=c; } public double cost(){ return coffee.cost()+2; } }

249. What is the Proxy pattern?

๐Ÿ‘‰ Proxy pattern controls access to an object.

interface Image { void display(); } class ProxyImage implements Image { RealImage real; public void display() { if(real==null) real=new RealImage(); real.display(); } }

250. What is the Observer pattern?

๐Ÿ‘‰ Observer pattern notifies multiple objects when a subject changes.

class Subject { List<Observer> observers = new ArrayList<>(); void notifyAllObservers(){ for(Observer o : observers) o.update(); } }

251. What is the Strategy pattern?

๐Ÿ‘‰ Strategy pattern encapsulates different algorithms and makes them interchangeable.

interface Strategy { int doOperation(int a,int b); } class Add implements Strategy { public int doOperation(int a,int b){ return a+b; } }

252. What is the Command pattern?

๐Ÿ‘‰ Command pattern encapsulates a request as an object to decouple sender and receiver.

interface Command { void execute(); } class LightOnCommand implements Command { public void execute(){ light.on(); } }

253. What is the Template Method pattern?

๐Ÿ‘‰ Template Method pattern defines the skeleton of an algorithm and allows subclasses to implement details.

abstract class Game { abstract void initialize(); abstract void play(); void run(){ initialize(); play(); } }

254. What is the Iterator pattern?

๐Ÿ‘‰ Iterator pattern provides a way to access elements sequentially without exposing the underlying representation.

Iterator<String> it = list.iterator(); while(it.hasNext()){ System.out.println(it.next()); }

255. What is the Composite pattern?

๐Ÿ‘‰ Composite pattern treats individual objects and compositions uniformly.

interface Component { void show(); } class Leaf implements Component { public void show(){ System.out.println("Leaf"); } } class Composite implements Component { List<Component> components = new ArrayList<>(); void add(Component c){ components.add(c); } }

256. What is the Flyweight pattern?

๐Ÿ‘‰ Flyweight pattern reduces memory usage by sharing objects.

class FlyweightFactory { Map<String,Flyweight> map = new HashMap<>(); Flyweight get(String key){ if(!map.containsKey(key)) map.put(key,new Flyweight(key)); return map.get(key); } }

257. What is the Facade pattern?

๐Ÿ‘‰ Facade pattern provides a simplified interface to a complex subsystem.

class ComputerFacade { CPU cpu; Memory memory; Disk disk; void start(){ cpu.start(); memory.load(); disk.read(); } }

258. What is the Bridge pattern?

๐Ÿ‘‰ Bridge pattern decouples abstraction from implementation to allow independent variation.

interface DrawAPI { void drawCircle(int r,int x,int y); } class Circle { DrawAPI drawAPI; void draw(){ drawAPI.drawCircle(r,x,y); } }

259. What is the Mediator pattern?

๐Ÿ‘‰ Mediator pattern reduces communication complexity between multiple objects.

class Mediator { void send(String msg, Colleague c){ ... } }

260. What is the Chain of Responsibility pattern?

๐Ÿ‘‰ Chain of Responsibility passes a request along a chain of handlers until one handles it.

abstract class Handler { Handler next; abstract void handle(String req); }




๐ŸŸข Java 8 Features & New Additions – Questions & Answers


261. What are the main features introduced in Java 8?

  • Lambda Expressions – functional programming style

  • Stream API – process collections efficiently

  • Default and Static Methods in Interface

  • Optional Class – handle nulls safely

  • Date & Time API (java.time)

  • Nashorn JavaScript Engine

  • New Collectors and Utilities


262. What is the purpose of Lambda Expressions in Java 8?

๐Ÿ‘‰ Lambda allows writing concise code for functional interfaces and reduces boilerplate code.


263. What is Stream API in Java 8?

๐Ÿ‘‰ Stream API allows functional-style operations on collections (filter, map, reduce) without modifying the source.


264. What is Optional in Java 8?

๐Ÿ‘‰ Optional is a container object which may or may not contain a value, helps avoid NullPointerException.

Optional<String> opt = Optional.ofNullable(value); opt.ifPresent(System.out::println);

265. What are default methods in Java 8?

๐Ÿ‘‰ Methods in interfaces with a default implementation.

interface A { default void display(){ System.out.println("Hello"); } }

266. What are static methods in interfaces in Java 8?

๐Ÿ‘‰ Methods with implementation inside interface, can be called using interface name.

interface A { static void show(){ System.out.println("Static"); } } A.show();

267. What are the benefits of Stream API?

  • Process large datasets efficiently

  • Parallel processing support

  • Functional programming style

  • Cleaner and readable code


268. What is filter() in Stream API?

๐Ÿ‘‰ Filters elements based on predicate condition.

list.stream().filter(n -> n>5).forEach(System.out::println);

269. What is map() in Stream API?

๐Ÿ‘‰ Transforms elements into another form.

list.stream().map(n -> n*n).forEach(System.out::println);

270. What is reduce() in Stream API?

๐Ÿ‘‰ Aggregates all elements into a single result.

int sum = list.stream().reduce(0, Integer::sum);

271. What is forEach() in Stream API?

๐Ÿ‘‰ Performs an action for each element in the stream.

list.stream().forEach(System.out::println);

272. What is collect() in Stream API?

๐Ÿ‘‰ Terminal operation to convert Stream to List, Set, Map, etc.

List<Integer> result = list.stream().filter(n -> n>5).collect(Collectors.toList());

273. What is distinct() in Stream API?

๐Ÿ‘‰ Removes duplicate elements from a Stream.

list.stream().distinct().forEach(System.out::println);

274. What is sorted() in Stream API?

๐Ÿ‘‰ Sorts elements in natural or custom order.

list.stream().sorted().forEach(System.out::println);

275. What is limit() and skip() in Stream API?

  • limit(n) → takes first n elements

  • skip(n) → skips first n elements

list.stream().skip(2).limit(3).forEach(System.out::println);

276. What is peek() in Stream API?

๐Ÿ‘‰ Allows performing action on elements without modifying the Stream, useful for debugging.

list.stream().peek(System.out::println).collect(Collectors.toList());

277. What is method reference in Java 8?

๐Ÿ‘‰ Shorthand for Lambda Expressions calling a method.

list.forEach(System.out::println);

Types of method references:

  • Static method: ClassName::staticMethod

  • Instance method: object::instanceMethod

  • Constructor: ClassName::new


278. What is java.time package?

๐Ÿ‘‰ New Date and Time API introduced in Java 8, more robust than Date and Calendar.

Classes: LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Duration, Period


279. How to get current date and time in Java 8?

LocalDate date = LocalDate.now(); LocalTime time = LocalTime.now(); LocalDateTime dt = LocalDateTime.now();

280. How to format date in Java 8?

LocalDateTime dt = LocalDateTime.now(); DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); System.out.println(dt.format(fmt));



๐ŸŸข Java Exception Handling – Questions & Answers


281. What is an exception in Java?

๐Ÿ‘‰ An exception is an unexpected event that occurs during program execution, disrupting the normal flow.


282. What are the types of exceptions in Java?

  1. Checked Exception – must be handled (IOException, SQLException)

  2. Unchecked Exception – runtime exceptions (NullPointerException, ArithmeticException)

  3. Errors – serious issues (OutOfMemoryError, StackOverflowError)


283. What is the difference between Checked and Unchecked exceptions?

FeatureCheckedUnchecked
Checked atCompile timeRuntime
Must handleYesNo
ExamplesIOException, SQLExceptionNullPointerException, ArrayIndexOutOfBoundsException

284. What is try-catch in Java?

๐Ÿ‘‰ try block contains code that may throw exception, catch block handles it.

try { int x = 5/0; } catch(ArithmeticException e) { System.out.println("Cannot divide by zero"); }

285. What is finally block in Java?

๐Ÿ‘‰ finally block executes always, whether exception occurs or not.
Used for cleanup (closing resources).


286. Can we have try without catch?

✅ Yes, try can be used with finally only.

try { ... } finally { ... }

287. Can we have multiple catch blocks?

✅ Yes, for handling different exceptions separately.

try { ... } catch(NullPointerException e) { ... } catch(ArithmeticException e) { ... }

288. What is multi-catch in Java 7+?

๐Ÿ‘‰ Allows catching multiple exceptions in a single catch block.

try { ... } catch(IOException | SQLException e) { e.printStackTrace(); }

289. What is throw in Java?

๐Ÿ‘‰ throw is used to explicitly throw an exception.

throw new ArithmeticException("Divide by zero");

290. What is throws in Java?

๐Ÿ‘‰ throws declares exceptions a method may throw.

void readFile() throws IOException { ... }

291. Difference between throw and throws?

Featurethrowthrows
PurposeThrow single exceptionDeclare multiple exceptions
Used inMethod bodyMethod signature
Examplethrow new IOException();void m() throws IOException, SQLException

292. What is the difference between Error and Exception?

FeatureErrorException
CauseSystem-level failureProgram-level problem
RecoverableNoSometimes yes
ExamplesOutOfMemoryErrorIOException, NullPointerException

293. What is custom exception in Java?

๐Ÿ‘‰ User-defined exception by extending Exception class.

class MyException extends Exception { MyException(String msg){ super(msg); } }

294. How to create custom runtime exception?

๐Ÿ‘‰ Extend RuntimeException.

class MyRuntimeException extends RuntimeException { ... }

295. What is try-with-resources in Java 7+?

๐Ÿ‘‰ Automatically closes resources implementing AutoCloseable (e.g., FileReader, BufferedReader).

try(BufferedReader br = new BufferedReader(new FileReader("file.txt"))) { System.out.println(br.readLine()); }

296. Can finally block suppress exception?

✅ Yes, if finally block throws another exception, it may suppress the original one.


297. Difference between checked exception and error?

FeatureChecked ExceptionError
Checked atCompile timeRuntime
Can handleYesUsually cannot
ExampleIOExceptionOutOfMemoryError

298. What is stack trace in Java?

๐Ÿ‘‰ Stack trace shows sequence of method calls leading to exception.

e.printStackTrace();

299. What is Exception class hierarchy in Java?

Throwable ├── Error └── Exception ├── RuntimeException └── Checked Exceptions

300. How to propagate exception in Java?

๐Ÿ‘‰ Use throws keyword in method signature to propagate exception to caller.

void readFile() throws IOException { ... }


๐ŸŸข Java Collections Framework – Questions & Answers


301. What is the Java Collections Framework (JCF)?

๐Ÿ‘‰ JCF is a set of interfaces, classes, and algorithms for storing and manipulating groups of objects.
Package: java.util.


302. What are the main interfaces in JCF?

  • Collection → root interface (List, Set, Queue)

  • Map → stores key-value pairs (HashMap, TreeMap)


303. What is the difference between Collection and Map?

FeatureCollectionMap
StructureStores elementsStores key-value pairs
DuplicateAllows duplicates (except Set)Keys must be unique
HierarchyList, Set, QueueHashMap, TreeMap, LinkedHashMap

304. What is List in Java?

๐Ÿ‘‰ List is an ordered collection that allows duplicates.
Examples: ArrayList, LinkedList, Vector.


305. What is Set in Java?

๐Ÿ‘‰ Set is a collection of unique elements (no duplicates).
Examples: HashSet, LinkedHashSet, TreeSet.


306. What is Queue in Java?

๐Ÿ‘‰ Queue is a collection for holding elements prior to processing, usually FIFO.
Examples: LinkedList, PriorityQueue.


307. What is Deque in Java?

๐Ÿ‘‰ Deque (Double Ended Queue) allows insertion and removal from both ends.
Examples: ArrayDeque, LinkedList.


308. What is Map in Java?

๐Ÿ‘‰ Map stores key-value pairs, keys are unique, values can be duplicated.
Examples: HashMap, TreeMap, LinkedHashMap, Hashtable.


309. Difference between ArrayList and LinkedList?

FeatureArrayListLinkedList
StructureDynamic arrayDoubly linked list
AccessFast (index)Slow (traverse)
Insertion/DeletionSlowFast
MemoryLessMore

310. Difference between HashMap and Hashtable?

FeatureHashMapHashtable
Thread-safeNoYes
Null key/valueYesNo
PerformanceFasterSlower

311. Difference between HashMap and TreeMap?

FeatureHashMapTreeMap
OrderNo orderSorted order (keys)
Null keyAllowedNot allowed
PerformanceFasterSlower

312. Difference between List and Set?

FeatureListSet
DuplicatesAllowedNot allowed
OrderMaintains insertion orderNo order (except LinkedHashSet)
ExamplesArrayListHashSet

313. Difference between ArrayList and Vector?

FeatureArrayListVector
Thread-safeNoYes
PerformanceFasterSlower
LegacyNoYes

314. What is LinkedHashMap in Java?

๐Ÿ‘‰ LinkedHashMap maintains insertion order of keys while storing key-value pairs.


315. What is PriorityQueue in Java?

๐Ÿ‘‰ PriorityQueue orders elements based on natural order or custom comparator, not FIFO.


316. Difference between Queue and Deque?

FeatureQueueDeque
Insert/RemoveOne endBoth ends
ImplementationLinkedList, PriorityQueueArrayDeque, LinkedList

317. What is Iterator in Java?

๐Ÿ‘‰ Iterator allows traversing elements in a collection.

Iterator<String> it = list.iterator(); while(it.hasNext()){ System.out.println(it.next()); }

318. Difference between Iterator and ListIterator?

FeatureIteratorListIterator
TraverseForward onlyForward & backward
ModifyNo add/removeCan add/remove/set
ApplicableAny collectionList only

319. What is the difference between fail-fast and fail-safe iterators?

  • Fail-fast → throws ConcurrentModificationException if collection modified during iteration (ArrayList, HashMap).

  • Fail-safe → works on copy, safe for concurrent modification (ConcurrentHashMap, CopyOnWriteArrayList).


320. Difference between Comparable and Comparator?

FeatureComparableComparator
MethodcompareTo()compare()
SortingNatural orderCustom order
InterfaceImplemented by classSeparate class or lambda










๐ŸŸข Java Multithreading & Concurrency – Questions & Answers


321. What is multithreading in Java?

๐Ÿ‘‰ Multithreading allows a program to execute multiple threads simultaneously, improving performance.


322. What is a thread in Java?

๐Ÿ‘‰ A thread is a lightweight process that executes code independently within a program.


323. How to create a thread in Java?

  1. Extend Thread class

class MyThread extends Thread { public void run() { System.out.println("Thread running"); } } MyThread t = new MyThread(); t.start();
  1. Implement Runnable interface

class MyRunnable implements Runnable { public void run() { System.out.println("Runnable running"); } } Thread t = new Thread(new MyRunnable()); t.start();

324. Difference between Thread and Runnable?

FeatureThreadRunnable
Extend classYesNo
Multiple inheritanceNot allowedAllowed
OverheadHigherLower

325. What is the life cycle of a thread?

States: New → Runnable → Running → Waiting/Blocked → Terminated


326. Difference between start() and run() method?

  • start() → creates new thread and calls run()

  • run() → executes code in current thread, no new thread


327. What is sleep() method in Java?

๐Ÿ‘‰ Pauses current thread for specified time without releasing lock.

Thread.sleep(1000); // 1 second

328. What is join() method in Java?

๐Ÿ‘‰ Waits for another thread to finish before continuing execution.

t.join();

329. What is yield() method in Java?

๐Ÿ‘‰ Suggests current thread to pause and allow other threads to execute.
No guarantee that it will switch threads.


330. Difference between wait() and sleep()?

Featurewait()sleep()
Belongs toObjectThread
Releases lockYesNo
ThrowsInterruptedExceptionInterruptedException

331. What is notify() and notifyAll() in Java?

  • notify() → wakes one waiting thread

  • notifyAll() → wakes all waiting threads


332. What is synchronized block in Java?

๐Ÿ‘‰ Ensures only one thread executes code at a time on the same object.

synchronized(obj) { // critical section }

333. What is synchronized method in Java?

๐Ÿ‘‰ Method is synchronized to lock the object for thread-safe execution.

public synchronized void increment(){ count++; }

334. What is deadlock in Java?

๐Ÿ‘‰ Deadlock occurs when two or more threads wait indefinitely for each other’s resources.


335. What is starvation in Java?

๐Ÿ‘‰ A thread never gets CPU time because higher priority threads always execute first.


336. What is livelock in Java?

๐Ÿ‘‰ Threads keep changing state but no progress is made (like two people trying to pass each other).


337. What is volatile keyword in Java?

๐Ÿ‘‰ Ensures visibility of changes to variables across threads.

volatile boolean flag = true;

338. What is Atomic variable in Java?

๐Ÿ‘‰ Variables like AtomicInteger, AtomicBoolean provide thread-safe operations without synchronized.

AtomicInteger count = new AtomicInteger(0); count.incrementAndGet();

339. What is ExecutorService in Java?

๐Ÿ‘‰ Framework to manage threads in a pool.

ExecutorService executor = Executors.newFixedThreadPool(5); executor.submit(() -> System.out.println("Task")); executor.shutdown();

340. Difference between Callable and Runnable?

FeatureRunnableCallable
Return valuevoidReturns value
ExceptionCannot throw checkedCan throw checked exception
InterfaceRunnableCallable<V>





๐ŸŸข Java I/O Streams – Questions & Answers


341. What is Java I/O?

๐Ÿ‘‰ Java I/O (Input/Output) allows reading from and writing to data sources like files, console, memory, network, etc.


342. What are streams in Java?

๐Ÿ‘‰ A stream is a sequence of data.

  • InputStream / Reader → read data

  • OutputStream / Writer → write data


343. Difference between byte stream and character stream?

FeatureByte StreamCharacter Stream
Data unit8-bit bytes16-bit characters
ClassesFileInputStream, FileOutputStreamFileReader, FileWriter
UseBinary dataText data

344. Difference between InputStream and OutputStream?

FeatureInputStreamOutputStream
PurposeRead dataWrite data
ExamplesFileInputStreamFileOutputStream

345. Difference between Reader and Writer?

FeatureReaderWriter
PurposeRead charactersWrite characters
ExampleFileReaderFileWriter

346. How to read a file using FileReader?

FileReader fr = new FileReader("file.txt"); int i; while((i=fr.read())!=-1) System.out.print((char)i); fr.close();

347. How to write a file using FileWriter?

FileWriter fw = new FileWriter("file.txt"); fw.write("Hello World"); fw.close();

348. What is BufferedReader in Java?

๐Ÿ‘‰ BufferedReader buffers characters for efficient reading and provides readLine() method.

BufferedReader br = new BufferedReader(new FileReader("file.txt")); String line = br.readLine(); br.close();

349. What is BufferedWriter in Java?

๐Ÿ‘‰ BufferedWriter buffers characters for efficient writing and provides newLine() method.

BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")); bw.write("Hello"); bw.newLine(); bw.close();

350. Difference between FileInputStream and FileReader?

FeatureFileInputStreamFileReader
Data typeByteChar
UseBinary filesText files

351. Difference between FileOutputStream and FileWriter?

FeatureFileOutputStreamFileWriter
Data typeByteChar
UseBinary filesText files

352. What is PrintWriter in Java?

๐Ÿ‘‰ PrintWriter allows writing formatted text to files or streams.

PrintWriter pw = new PrintWriter("file.txt"); pw.println("Hello"); pw.close();

353. Difference between Reader/Writer and InputStream/OutputStream?

FeatureReader/WriterInputStream/OutputStream
Data typeCharactersBytes
ClassesFileReader/FileWriterFileInputStream/FileOutputStream
UseText filesBinary files

354. What is File class in Java?

๐Ÿ‘‰ Represents file or directory path, provides metadata like size, name, and permissions.

File f = new File("file.txt"); System.out.println(f.exists());

355. How to check if a file exists?

File f = new File("file.txt"); if(f.exists()) System.out.println("File exists");

356. How to create a new file?

File f = new File("file.txt"); f.createNewFile();

357. How to delete a file?

File f = new File("file.txt"); f.delete();

358. What is DataInputStream and DataOutputStream?

  • DataInputStream → reads primitive data types in machine-independent way

  • DataOutputStream → writes primitive data types

DataOutputStream dos = new DataOutputStream(new FileOutputStream("file.dat")); dos.writeInt(100); dos.close();

359. What is ObjectInputStream and ObjectOutputStream?

  • ObjectOutputStream → writes serializable objects

  • ObjectInputStream → reads serialized objects

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj.dat")); oos.writeObject(obj); oos.close();

360. What is the difference between FileInputStream and BufferedInputStream?

Feature FileInputStream BufferedInputStream
Read efficiency Low High (buffers data)
Use Basic file reading Efficient reading



๐ŸŸข Java Serialization & Deserialization – Questions & Answers


361. What is serialization in Java?

๐Ÿ‘‰ Serialization is the process of converting an object into a byte stream so it can be saved to a file or sent over a network.


362. What is deserialization in Java?

๐Ÿ‘‰ Deserialization is the process of converting a byte stream back into an object.


363. Which interface is used for serialization?

๐Ÿ‘‰ Serializable interface is marker interface used to indicate that a class can be serialized.

class Student implements Serializable { ... }

364. How to serialize an object in Java?

FileOutputStream fos = new FileOutputStream("student.dat"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(student); oos.close();

365. How to deserialize an object in Java?

FileInputStream fis = new FileInputStream("student.dat"); ObjectInputStream ois = new ObjectInputStream(fis); Student s = (Student) ois.readObject(); ois.close();

366. What is transient keyword in Java?

๐Ÿ‘‰ Fields marked as transient are not serialized.

transient int password;

367. What is serialVersionUID in Java?

๐Ÿ‘‰ serialVersionUID is a unique version identifier for a serializable class.
It ensures class consistency during deserialization.

private static final long serialVersionUID = 1L;

368. What happens if serialVersionUID is not declared?

๐Ÿ‘‰ Java generates default serialVersionUID, but changes in class may cause InvalidClassException during deserialization.


369. Difference between Externalizable and Serializable?

FeatureSerializableExternalizable
InterfaceSerializableExternalizable
ControlDefault mechanismFull control over read/write
MethodsNo methodsmust implement readExternal/writeExternal

370. Can we serialize static fields in Java?

❌ No, static fields belong to class, not object, so they are not serialized.


371. Can we serialize final fields in Java?

✅ Yes, final fields are serialized normally.


372. Can we serialize object references?

✅ Yes, all referenced objects must be serializable.


373. What is the purpose of ObjectOutputStream?

๐Ÿ‘‰ Writes objects to an output stream for serialization.


374. What is the purpose of ObjectInputStream?

๐Ÿ‘‰ Reads objects from an input stream for deserialization.


375. Can we customize serialization in Java?

✅ Yes, by defining private writeObject(ObjectOutputStream oos) and readObject(ObjectInputStream ois) methods.


376. What is shallow vs deep serialization?

  • Shallow serialization → only object itself is serialized, references may not be fully serialized

  • Deep serializationentire object graph is serialized


377. What exceptions can occur during serialization?

  • NotSerializableException → if class doesn’t implement Serializable

  • IOException → for I/O errors


378. What exceptions can occur during deserialization?

  • ClassNotFoundException → class of object not found

  • InvalidClassException → serialVersionUID mismatch

  • IOException → for I/O errors


379. Can we serialize transient fields manually?

✅ Yes, by customizing writeObject/readObject methods.

private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); oos.writeInt(password); // serialize transient manually }

380. What is the difference between Serialization and Cloning?

Feature Serialization Cloning
Purpose Save object to byte stream Create copy in memory
Mechanism ObjectOutputStream Object.clone()
Object graph Can persist entire graph Only shallow or deep copy















๐ŸŸข Java Networking – Questions & Answers


381. What is Java Networking?

๐Ÿ‘‰ Java Networking allows programs to communicate over networks using TCP/IP protocols.


382. Which package is used for networking in Java?

๐Ÿ‘‰ java.net package


383. What are the main classes in java.net package?

  • InetAddress – represents IP address

  • URL – represents a URL

  • URLConnection – connects to resources on the web

  • Socket / ServerSocket – TCP communication

  • DatagramSocket / DatagramPacket – UDP communication


384. What is InetAddress in Java?

๐Ÿ‘‰ Represents IP address of a host.

InetAddress address = InetAddress.getByName("www.google.com"); System.out.println(address.getHostAddress());

385. Difference between TCP and UDP in Java?

FeatureTCPUDP
ConnectionConnection-orientedConnectionless
ReliabilityReliableUnreliable
ClassesSocket/ServerSocketDatagramSocket/DatagramPacket
UseFile transfer, HTTPStreaming, DNS

386. What is a URL in Java?

๐Ÿ‘‰ URL (Uniform Resource Locator) represents a web resource.

URL url = new URL("https://www.google.com"); System.out.println(url.getHost());

387. How to read data from a URL in Java?

URL url = new URL("https://www.google.com"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String line; while((line = br.readLine()) != null) System.out.println(line); br.close();

388. What is Socket in Java?

๐Ÿ‘‰ Socket is used to establish a TCP connection between client and server.

Socket socket = new Socket("localhost", 5000);

389. What is ServerSocket in Java?

๐Ÿ‘‰ ServerSocket listens for client connections on a specified port.

ServerSocket server = new ServerSocket(5000); Socket client = server.accept();

390. Difference between Socket and ServerSocket?

FeatureSocketServerSocket
PurposeClient sideServer side
FunctionConnects to serverListens for client

391. What is DatagramSocket in Java?

๐Ÿ‘‰ DatagramSocket is used for UDP communication to send/receive packets.


392. What is DatagramPacket in Java?

๐Ÿ‘‰ DatagramPacket represents data packets sent/received using DatagramSocket.


393. How to send UDP data in Java?

DatagramSocket ds = new DatagramSocket(); byte[] msg = "Hello".getBytes(); InetAddress ip = InetAddress.getByName("localhost"); DatagramPacket dp = new DatagramPacket(msg, msg.length, ip, 5000); ds.send(dp); ds.close();

394. How to receive UDP data in Java?

DatagramSocket ds = new DatagramSocket(5000); byte[] buf = new byte[1024]; DatagramPacket dp = new DatagramPacket(buf, buf.length); ds.receive(dp); System.out.println(new String(dp.getData(), 0, dp.getLength())); ds.close();

395. What is port number in Java networking?

๐Ÿ‘‰ A port is a logical communication endpoint used by TCP/UDP connections.
Range: 0–65535


396. What is loopback address in Java?

๐Ÿ‘‰ Loopback address (127.0.0.1) refers to the local machine.

InetAddress local = InetAddress.getLoopbackAddress();

397. What is the difference between IP and URL?

FeatureIPURL
MeaningInternet Protocol addressWeb resource locator
Example192.168.0.1https://www.google.com
TypeNumericAlphanumeric + protocol

398. What is the difference between TCP and HTTP?

FeatureTCPHTTP
TypeProtocolApplication protocol
TransportReliable connectionUses TCP for transport
UseSocket communicationWeb browsing

399. How to get local IP address in Java?

InetAddress local = InetAddress.getLocalHost(); System.out.println(local.getHostAddress());

400. How to get host name from IP in Java?

InetAddress address = InetAddress.getByName("8.8.8.8"); System.out.println(address.getHostName());







๐ŸŸข Java JDBC – Questions & Answers


401. What is JDBC in Java?

๐Ÿ‘‰ JDBC (Java Database Connectivity) is an API to connect and execute queries with databases from Java programs.


402. Which package is used for JDBC?

๐Ÿ‘‰ java.sql and javax.sql packages.


403. What are the main steps in JDBC?

  1. Load the JDBC driver

  2. Create a connection

  3. Create a statement

  4. Execute query

  5. Process results

  6. Close connection


404. How to load a JDBC driver?

Class.forName("com.mysql.cj.jdbc.Driver");

405. How to establish a database connection?

Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/dbname", "user", "password");

406. What is Statement in JDBC?

๐Ÿ‘‰ Statement is used to execute SQL queries.

Statement stmt = con.createStatement();

407. Difference between Statement, PreparedStatement, and CallableStatement?

FeatureStatementPreparedStatementCallableStatement
PrecompiledNoYesYes
ParametersNoYesYes
UseSimple queriesDynamic queriesStored procedures

408. How to execute SELECT query in JDBC?

ResultSet rs = stmt.executeQuery("SELECT * FROM students"); while(rs.next()){ System.out.println(rs.getString("name")); }

409. How to execute INSERT/UPDATE/DELETE in JDBC?

int rows = stmt.executeUpdate("INSERT INTO students VALUES(1,'John')"); System.out.println(rows + " row(s) affected");

410. What is ResultSet in JDBC?

๐Ÿ‘‰ ResultSet stores the results of SELECT queries.
Methods: next(), getString(), getInt(), etc.


411. What are the types of ResultSet?

  1. TYPE_FORWARD_ONLY → move forward only

  2. TYPE_SCROLL_INSENSITIVE → scrollable, not sensitive to changes

  3. TYPE_SCROLL_SENSITIVE → scrollable, sensitive to changes


412. What are the concurrency types of ResultSet?

  1. CONCUR_READ_ONLY → cannot update

  2. CONCUR_UPDATABLE → can update database


413. Difference between execute(), executeQuery(), executeUpdate()?

MethodUseReturn
executeQuerySELECTResultSet
executeUpdateINSERT/UPDATE/DELETEint (affected rows)
executeAny SQLboolean (true if ResultSet)

414. How to close JDBC resources properly?

rs.close(); stmt.close(); con.close();

415. What is PreparedStatement?

๐Ÿ‘‰ Precompiled SQL query with parameters, prevents SQL injection.

PreparedStatement ps = con.prepareStatement("INSERT INTO students VALUES(?,?)"); ps.setInt(1, 1); ps.setString(2, "John"); ps.executeUpdate();

416. What is CallableStatement?

๐Ÿ‘‰ Used to execute stored procedures in database.

CallableStatement cs = con.prepareCall("{call my_procedure()}"); cs.execute();

417. What is DriverManager in JDBC?

๐Ÿ‘‰ DriverManager manages JDBC drivers and establishes connection.

Connection con = DriverManager.getConnection(url, user, pass);

418. What is DataSource in JDBC?

๐Ÿ‘‰ DataSource provides connection pooling and distributed transactions, better than DriverManager.


419. What is connection pooling in JDBC?

๐Ÿ‘‰ Reusing pre-created database connections to improve performance.


420. Difference between Statement and PreparedStatement?

FeatureStatementPreparedStatement
PrecompiledNoYes
ParametersNoYes
SQL InjectionVulnerableSafe




๐ŸŸข Java Annotations & Reflection – Questions & Answers


421. What is an annotation in Java?

๐Ÿ‘‰ An annotation is metadata that provides information about the code, used by compiler or frameworks.


422. What are the types of annotations in Java?

  1. Built-in annotations@Override, @Deprecated, @SuppressWarnings

  2. Meta-annotations@Retention, @Target, @Documented, @Inherited

  3. Custom annotations → user-defined


423. What is @Override annotation?

๐Ÿ‘‰ Ensures a method overrides a superclass method. Compiler checks it.

@Override public String toString() { return "Hello"; }

424. What is @Deprecated annotation?

๐Ÿ‘‰ Marks a method/class as outdated, compiler shows a warning.

@Deprecated void oldMethod() { ... }

425. What is @SuppressWarnings annotation?

๐Ÿ‘‰ Tells compiler to ignore specific warnings.

@SuppressWarnings("unchecked") List list = new ArrayList();

426. What is meta-annotation in Java?

๐Ÿ‘‰ An annotation applied to another annotation.
Examples: @Retention, @Target, @Inherited, @Documented


427. What is @Retention annotation?

๐Ÿ‘‰ Specifies how long annotation is retained.

  • SOURCE → discarded by compiler

  • CLASS → in class file, not at runtime

  • RUNTIME → available at runtime


428. What is @Target annotation?

๐Ÿ‘‰ Specifies where annotation can be applied (class, method, field, parameter).

@Target(ElementType.METHOD) @interface MyAnno {}

429. How to create custom annotation?

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @interface MyAnnotation { String value(); }

430. How to access custom annotation at runtime?

Method m = MyClass.class.getMethod("myMethod"); MyAnnotation ann = m.getAnnotation(MyAnnotation.class); System.out.println(ann.value());

431. What is Java Reflection?

๐Ÿ‘‰ Reflection allows inspecting and manipulating classes, methods, fields, and constructors at runtime.


432. Which package is used for reflection?

๐Ÿ‘‰ java.lang.reflect


433. How to get class object in Java?

Class<?> cls = MyClass.class; Class<?> cls2 = Class.forName("mypackage.MyClass"); Class<?> cls3 = obj.getClass();

434. How to get methods of a class using reflection?

Method[] methods = cls.getDeclaredMethods(); for(Method m : methods) System.out.println(m.getName());

435. How to get fields of a class using reflection?

Field[] fields = cls.getDeclaredFields(); for(Field f : fields) System.out.println(f.getName());

436. How to invoke a method using reflection?

Method m = cls.getMethod("myMethod", String.class); m.invoke(obj, "Hello");

437. How to access private fields using reflection?

Field f = cls.getDeclaredField("name"); f.setAccessible(true); f.set(obj, "New Name");

438. How to create object using reflection?

Constructor<?> cons = cls.getConstructor(); Object obj = cons.newInstance();

439. Difference between compile-time and runtime annotations?

FeatureCompile-timeRuntime
RetentionSOURCE/CLASSRUNTIME
AccessCompilerReflection
Example@OverrideCustom annotation

440. Why is reflection used in Java?

  • Frameworks (Spring, Hibernate) use reflection

  • Inspect classes/methods at runtime

  • Dynamic object creation

  • Access private members



๐ŸŸข Java Generics – Questions & Answers


441. What are Generics in Java?

๐Ÿ‘‰ Generics allow type-safe operations on objects, enabling classes, interfaces, and methods to operate on any type while maintaining compile-time type safety.


442. Why use Generics in Java?

  • Type safety → prevents ClassCastException

  • Code reusability → works with any type

  • Eliminates casting → no need for manual type casting


443. How to create a generic class in Java?

class Box<T> { private T t; public void set(T t){ this.t = t; } public T get(){ return t; } } Box<Integer> b = new Box<>(); b.set(10);

444. How to create a generic method in Java?

public <T> void printArray(T[] arr){ for(T t : arr) System.out.println(t); }

445. What is type parameter in Generics?

๐Ÿ‘‰ A placeholder for actual type used in class, interface, or method. Common letters: T, E, K, V.


446. What are bounded type parameters?

๐Ÿ‘‰ Restricts generic type to a specific class or interface.

class Box<T extends Number> { ... } // only Number or subclasses

447. What is wildcard in Generics?

๐Ÿ‘‰ ? represents unknown type in Generics.

List<?> list = new ArrayList<Integer>();

448. Difference between ? extends T and ? super T?

Feature? extends T? super T
Upper boundSubclass of TSuperclass of T
UseRead-onlyWrite-only

449. Difference between generic class and generic method?

FeatureGeneric ClassGeneric Method
Type parameterClass-levelMethod-level
ScopeEntire classOnly method
Exampleclass Box<T>public <T> void print(T t)

450. Can we use primitive types with Generics?

❌ No, use wrapper classes (Integer, Double) instead of int, double.


451. What is type erasure in Generics?

๐Ÿ‘‰ During compilation, generic type information is removed, and replaced with Object or bounded type.


452. Difference between compile-time and runtime with Generics?

FeatureCompile-timeRuntime
Type checkingEnforcedNot available (due to type erasure)
ExampleBox<Integer>Box is raw type at runtime

453. What is raw type in Generics?

๐Ÿ‘‰ Using a generic class without specifying a type.

Box b = new Box(); // raw type

454. Can we create arrays of generic types?

❌ No, cannot create generic arrays directly. Use workaround with Object array:

T[] arr = (T[]) new Object[10];

455. Difference between generic and non-generic code?

FeatureGenericNon-Generic
Type safetyYesNo
CastingNot requiredRequired
ReusabilityHighLow

456. What is PECS in Java Generics?

๐Ÿ‘‰ Producer Extends, Consumer Super

  • Producer? extends T (read from collection)

  • Consumer? super T (write to collection)


457. Can we use multiple bounds in Generics?

✅ Yes, using & for interfaces (one class + multiple interfaces).

class MyClass<T extends Number & Serializable> { ... }

458. What is the difference between List<Object> and List<?>?

FeatureList<Object>List<?>
Type safetyCan hold Object onlyCan hold unknown type
UseAdd/remove allowedAdd not allowed (except null)

459. Can generic type be static?

❌ No, static members cannot use class-level generic type, but static methods can define their own generic type.

public static <T> void print(T t){ System.out.println(t); }

460. What are the advantages of using Generics?

  • Compile-time type safety

  • Code reusability

  • Reduces runtime errors

  • Eliminates type casting


๐ŸŸข Java Lambda & Functional Programming – Questions & Answers


461. What is a Lambda expression in Java?

๐Ÿ‘‰ Lambda expressions provide a shorter way to represent anonymous functions using -> operator.

(x, y) -> x + y

462. Why use Lambda expressions in Java?

  • Concise code → less boilerplate

  • Functional programming → pass behavior as parameter

  • Used with Collections & Streams


463. Syntax of Lambda expression in Java?

(parameters) -> expression (parameters) -> { statements }

464. Difference between Lambda and Anonymous class?

FeatureLambdaAnonymous Class
SyntaxShortVerbose
thisRefers to enclosing classRefers to anonymous object
UseFunctional interfacesAny interface/class

465. What is a Functional Interface in Java?

๐Ÿ‘‰ An interface with exactly one abstract method.

@FunctionalInterface interface MyFunc { void execute(); }

466. Examples of built-in functional interfaces?

  • Predicate<T> → boolean test

  • Function<T,R> → map T to R

  • Consumer<T> → accept T, return void

  • Supplier<T> → provide T, no input

  • UnaryOperator<T> → T → T

  • BinaryOperator<T> → (T, T) → T


467. What is Predicate in Java?

๐Ÿ‘‰ Functional interface represents boolean-valued function.

Predicate<Integer> p = x -> x > 10; System.out.println(p.test(15)); // true

468. What is Function in Java?

๐Ÿ‘‰ Functional interface represents a function that takes input and returns output.

Function<String, Integer> f = s -> s.length(); System.out.println(f.apply("Hello")); // 5

469. What is Consumer in Java?

๐Ÿ‘‰ Functional interface accepts input and returns void.

Consumer<String> c = s -> System.out.println(s); c.accept("Hello");

470. What is Supplier in Java?

๐Ÿ‘‰ Functional interface provides results without input.

Supplier<Double> s = () -> Math.random(); System.out.println(s.get());

471. What is UnaryOperator in Java?

๐Ÿ‘‰ Functional interface takes one argument and returns the same type.

UnaryOperator<Integer> u = x -> x * x; System.out.println(u.apply(5)); // 25

472. What is BinaryOperator in Java?

๐Ÿ‘‰ Functional interface takes two arguments of same type and returns same type.

BinaryOperator<Integer> b = (x,y) -> x + y; System.out.println(b.apply(5,10)); // 15

473. Difference between Predicate and Function?

FeaturePredicateFunction
ReturnbooleanAny type
InputTT
Examplex -> x > 0x -> x*2

474. Difference between Consumer and Supplier?

FeatureConsumerSupplier
InputYesNo
ReturnNoYes
Examplex -> System.out.println(x)() -> Math.random()

475. Can Lambda access local variables?

✅ Yes, but must be final or effectively final.

int num = 10; Consumer<Integer> c = x -> System.out.println(x + num);

476. What is Stream API in Java?

๐Ÿ‘‰ Stream API allows functional-style operations on collections like filter, map, reduce.

List<Integer> list = Arrays.asList(1,2,3); list.stream().filter(x->x>1).forEach(System.out::println);

477. What is difference between Collection and Stream?

FeatureCollectionStream
DataStoresProcesses
MutabilityCan modifyCannot modify
Lazy evaluationNoYes
IterationExternalInternal

478. What is map() in Stream?

๐Ÿ‘‰ map() transforms elements from one type to another.

List<String> list = Arrays.asList("a","bb"); list.stream().map(String::length).forEach(System.out::println);

479. What is filter() in Stream?

๐Ÿ‘‰ filter() selects elements based on a predicate.

list.stream().filter(x -> x.length() > 1).forEach(System.out::println);

480. What is reduce() in Stream?

๐Ÿ‘‰ reduce() aggregates elements to produce a single result.

int sum = list.stream().reduce(0, (a,b) -> a+b); System.out.println(sum);



๐ŸŸข Java 8 New Features & Miscellaneous – Questions & Answers


481. What are the major features introduced in Java 8?

  • Lambda expressions

  • Functional interfaces

  • Stream API

  • Default and static methods in interfaces

  • Optional class

  • New Date/Time API (java.time)

  • Nashorn JavaScript engine


482. What is Optional in Java 8?

๐Ÿ‘‰ Optional is a container for optional values, avoids NullPointerException.

Optional<String> name = Optional.ofNullable(null); System.out.println(name.orElse("Default")); // Default

483. What is a default method in Java 8?

๐Ÿ‘‰ Default methods allow methods in interface with body.

interface MyIntf { default void show(){ System.out.println("Hello"); } }

484. What is a static method in interface (Java 8)?

๐Ÿ‘‰ Interface can have static methods called using interface name.

interface MyIntf { static void print(){ System.out.println("Static"); } } MyIntf.print();

485. Difference between default and static methods in interface?

FeatureDefaultStatic
InvocationObjectInterface name
OverrideCan overrideCannot override
PurposeExtend interfaceUtility methods

486. What is new Date/Time API in Java 8?

๐Ÿ‘‰ Classes like LocalDate, LocalTime, LocalDateTime, ZonedDateTime provide modern date/time operations.

LocalDate date = LocalDate.now(); LocalDate tomorrow = date.plusDays(1);

487. Difference between java.util.Date and java.time.LocalDate?

FeatureDateLocalDate
ImmutabilityMutableImmutable
Time zoneNoNo (use ZonedDateTime)
APIOldModern, fluent

488. What is Stream.parallel() in Java 8?

๐Ÿ‘‰ Converts a stream to parallel stream, operations executed concurrently.

list.parallelStream().forEach(System.out::println);

489. What is Predicate.and(), Predicate.or() in Java 8?

  • and() → combines predicates using AND

  • or() → combines predicates using OR

Predicate<Integer> p1 = x -> x>0; Predicate<Integer> p2 = x -> x<10; System.out.println(p1.and(p2).test(5)); // true

490. What is Function.compose() and Function.andThen()?

  • compose() → f(g(x))

  • andThen() → g(f(x))

Function<Integer,Integer> f = x->x+2; Function<Integer,Integer> g = x->x*2; System.out.println(f.andThen(g).apply(2)); // 8

491. What is method reference in Java 8?

๐Ÿ‘‰ Shortcut to refer existing method instead of lambda.

list.forEach(System.out::println);

492. Types of method references?

  1. Static methodClass::staticMethod

  2. Instance method of objectobj::instanceMethod

  3. Instance method of classClass::instanceMethod

  4. Constructor referenceClass::new


493. What is a functional interface in Java 8?

✅ Already covered in Q465, example: Runnable, Callable, Predicate, Function.


494. Can we use lambda with custom functional interface?

✅ Yes

@FunctionalInterface interface MyFunc { void run(); } MyFunc f = () -> System.out.println("Lambda"); f.run();

495. Difference between Stream and ParallelStream?

FeatureStreamParallelStream
ExecutionSequentialConcurrent
PerformanceSlower for large dataFaster for large data
OrderPreservedMay be unordered

496. How to collect stream results to a list?

List<Integer> list2 = list.stream().filter(x->x>2).collect(Collectors.toList());

497. What is IntStream, LongStream, DoubleStream?

๐Ÿ‘‰ Specialized streams for primitive types, avoid boxing overhead.

IntStream.range(1,5).forEach(System.out::println);

498. Difference between map() and flatMap() in Stream?

Featuremap()flatMap()
OutputStream of same typeFlatten nested streams
ExampleList<String> -> List<Integer>List<List<String>> -> List<String>

499. What is Collectors in Java 8?

๐Ÿ‘‰ Provides utility methods to collect stream results:

  • toList(), toSet(), toMap()

  • joining(), counting(), groupingBy(), partitioningBy()

List<String> names = list.stream().collect(Collectors.toList());

500. What are key advantages of Java 8?

  • Functional programming support (lambda, stream)

  • Better date/time API

  • Optional to avoid null

  • Default & static methods in interfaces

  • Method references & compact code

  • Parallel processing with streams



Name: Rehan Khan | Blog by Rehan Khan | Follow me on GitHub, YouTube, Instagram, Facebook - LearnWithRehan GitHub: https://github.com/LearnWithRehan YouTube: https://www.youtube.com/@Learnwithrehan86147/ Instagram: https://www.instagram.com/learnwithrehan86147/ Facebook: https://www.facebook.com/people/Learnwith-Rehan/61572192551355/













Comments

Popular posts from this blog

Git And GitHub Collaborators and teams

Android Interview Question and Answer