๐ Top 500 Java Interview Questions (With Topics)
๐ Top 500 Java Interview Questions (With Topics)
1. Core Java Basics
-
What is Java?
-
What are the features of Java?
-
What is JVM, JRE, JDK?
-
Difference between JDK and JRE?
-
Explain the Java execution flow.
-
What are data types in Java?
-
What is type casting?
-
What are variables in Java?
-
What are literals in Java?
-
Difference between primitive and non-primitive data types?
-
What is a wrapper class?
-
Explain autoboxing and unboxing.
-
Difference between
==and.equals()? -
What are operators in Java?
-
What is precedence of operators?
-
What is ternary operator?
-
Difference between
&&and&? -
What are bitwise operators?
-
What is
instanceofoperator? -
What are control statements in Java?
2. OOPs Concepts
-
What is Object-Oriented Programming (OOP)?
-
What are the four pillars of OOP?
-
What is class and object?
-
What is constructor?
-
Types of constructors in Java?
-
Difference between constructor and method?
-
What is
thiskeyword? -
What is
superkeyword? -
Difference between overloading and overriding?
-
What is inheritance?
-
Types of inheritance in Java?
-
What is multiple inheritance? Is it supported in Java?
-
What is polymorphism?
-
What is method overloading?
-
What is method overriding?
-
What is encapsulation?
-
What is abstraction?
-
Difference between abstract class and interface?
-
Can we create object of abstract class?
-
Can interface have constructors?
3. Strings & Arrays
-
Difference between String, StringBuffer, and StringBuilder?
-
Why is String immutable in Java?
-
How to compare two Strings in Java?
-
What is
intern()in String? -
What is
String.format()? -
What is
substring()method? -
What is an array in Java?
-
How to create multidimensional arrays?
-
Difference between shallow copy and deep copy in arrays?
-
How to sort an array in Java?
4. Collections Framework
-
What is Collection Framework in Java?
-
Difference between List, Set, and Map?
-
Difference between ArrayList and LinkedList?
-
Difference between HashSet and TreeSet?
-
Difference between HashMap and Hashtable?
-
Difference between HashMap and ConcurrentHashMap?
-
What is LinkedHashMap?
-
What is EnumMap?
-
What is PriorityQueue?
-
Difference between Iterator and ListIterator?
-
What is fail-fast and fail-safe iterator?
-
What is Comparable vs Comparator?
-
How HashMap works internally?
-
What is hashing in Java?
-
What is load factor in HashMap?
5. Exception Handling
-
What is exception in Java?
-
Difference between checked and unchecked exceptions?
-
Difference between
throwandthrows? -
Difference between final, finally, and finalize()?
-
Can we have try without catch?
-
What is custom exception in Java?
-
What is
Throwable? -
Difference between Error and Exception?
-
What is
try-with-resources? -
What happens if finally block has return statement?
6. Multithreading
-
What is thread in Java?
-
Difference between process and thread?
-
How to create thread in Java?
-
Difference between
RunnableandThread? -
What is thread lifecycle?
-
What is synchronization?
-
Difference between synchronized method and block?
-
What is deadlock?
-
What is race condition?
-
What is thread pool in Java?
-
What is Executor framework?
-
Difference between Callable and Runnable?
-
What is Future in Java?
-
What is CountDownLatch?
-
What is CyclicBarrier?
7. Java 8+ Features
-
What are new features of Java 8?
-
What is Lambda expression?
-
What is Functional Interface?
-
What is Stream API?
-
Difference between map() and flatMap()?
-
What is Optional class in Java 8?
-
What is default method in interface?
-
What are method references?
-
What is LocalDate, LocalTime, LocalDateTime in Java 8?
-
Difference between
forEach()andmap()in streams?
8. Memory Management & GC
-
What is Garbage Collection in Java?
-
What is heap memory and stack memory?
-
What are different GC algorithms?
-
What is finalize() method?
-
What are memory leaks in Java?
-
What are weak references?
-
What is SoftReference, WeakReference, PhantomReference?
-
Difference between strong and weak reference?
-
How to make an object eligible for GC?
-
What is OutOfMemoryError?
9. Advanced Java
-
What is JDBC?
-
What are JDBC drivers?
-
Difference between Statement and PreparedStatement?
-
What is ResultSet in JDBC?
-
What is Servlet in Java?
-
Lifecycle of a Servlet?
-
What is JSP?
-
Difference between JSP and Servlet?
-
What is Spring Framework?
-
What is Hibernate?
10. Java I/O & File Handling
-
What is Java I/O?
-
Difference between Byte stream and Character stream?
-
What is InputStream and OutputStream?
-
Difference between FileReader and BufferedReader?
-
Difference between FileInputStream and FileReader?
-
What is Serialization in Java?
-
What is Deserialization?
-
What is
transientkeyword? -
What is
Serializableinterface? -
Difference between Externalizable and Serializable?
-
What is RandomAccessFile in Java?
-
What is NIO (New Input/Output)?
-
What is Buffer in Java NIO?
-
Difference between Stream and Channel in NIO?
-
What are Selectors in NIO?
-
What is File Locking in Java?
-
What is Path and Files class in Java NIO?
-
What is Asynchronous I/O in Java?
-
What is Scanner class used for?
-
How to read a file line by line in Java?
11. JVM & Performance
-
What is JVM architecture?
-
What are classloaders in Java?
-
What are the types of classloaders?
-
What is Just-In-Time (JIT) Compiler?
-
Difference between interpreter and JIT?
-
What are JVM memory areas?
-
What is Method Area in JVM?
-
What is PermGen vs Metaspace?
-
What is stack memory in JVM?
-
What is heap memory?
-
What is class file structure in Java?
-
What is bytecode in Java?
-
How JVM loads a class?
-
Difference between Bootstrap and Application ClassLoader?
-
What are custom classloaders?
-
What is memory leak in Java?
-
How to analyze heap dumps?
-
What is JConsole?
-
What is JVisualVM?
-
What is profiling in Java?
12. Java Annotations & Reflection
-
What are annotations in Java?
-
Difference between @Override and @Overload?
-
What is @FunctionalInterface?
-
What is @Deprecated annotation?
-
What is custom annotation?
-
How to create your own annotation?
-
What are meta-annotations?
-
Difference between @Retention and @Target?
-
What is @Documented and @Inherited?
-
What is reflection in Java?
-
How to get methods of a class using reflection?
-
How to access private fields using reflection?
-
What is setAccessible(true) in reflection?
-
What is dynamic proxy in Java?
-
What are use cases of reflection?
-
What is annotation processing tool (APT)?
-
Difference between runtime and compile-time annotations?
-
What is dependency injection annotation in Spring?
-
What is Lombok in Java?
-
What are marker annotations?
13. Java Networking
-
What is networking in Java?
-
What is Socket in Java?
-
Difference between TCP and UDP in Java?
-
What is ServerSocket class?
-
How to create a client-server program in Java?
-
What is URL and URLConnection class?
-
What is Datagram in Java?
-
What is MulticastSocket?
-
Difference between HTTP and HTTPS?
-
What is InetAddress in Java?
-
What is RMI (Remote Method Invocation)?
-
Difference between RMI and CORBA?
-
What is REST API in Java?
-
How to consume REST API using HttpURLConnection?
-
What is HttpClient API in Java 11?
-
What is WebSocket in Java?
-
Difference between GET and POST in HTTP?
-
What are cookies and sessions in Java web?
-
What is load balancing?
-
What is SSL handshake?
14. Java Design Patterns
-
What are design patterns?
-
What is Singleton Pattern?
-
How to implement thread-safe Singleton?
-
What is Factory Pattern?
-
Difference between Factory and Abstract Factory?
-
What is Builder Pattern?
-
What is Prototype Pattern?
-
What is Adapter Pattern?
-
What is Decorator Pattern?
-
What is Proxy Pattern?
-
What is Facade Pattern?
-
What is Composite Pattern?
-
What is Bridge Pattern?
-
What is Flyweight Pattern?
-
What is Observer Pattern?
-
What is Strategy Pattern?
-
What is State Pattern?
-
What is Command Pattern?
-
What is Template Method Pattern?
-
What is Chain of Responsibility Pattern?
-
What is Dependency Injection Pattern?
-
Difference between MVC and MVVM?
-
What is DAO Pattern?
-
What is Repository Pattern?
-
What is Service Locator Pattern?
15. Spring Framework
-
What is Spring Framework?
-
What are the features of Spring?
-
What is dependency injection in Spring?
-
What are types of dependency injection?
-
Difference between constructor and setter injection?
-
What is Spring Bean?
-
What is ApplicationContext?
-
What is BeanFactory vs ApplicationContext?
-
What is Spring Boot?
-
What is Spring Boot Starter?
-
What is Spring Boot AutoConfiguration?
-
Difference between Spring and Spring Boot?
-
What is @Component, @Service, and @Repository?
-
What is @Autowired annotation?
-
What is @Qualifier annotation?
-
Difference between @ComponentScan and @EnableAutoConfiguration?
-
What is @Configuration annotation?
-
What is Spring AOP?
-
What is Aspect, JoinPoint, and Advice?
-
Difference between before, after, and around advice?
-
What is Spring Transaction Management?
-
Difference between checked and unchecked exception in Spring Transaction?
-
What is @Transactional annotation?
-
What is Spring Data JPA?
-
What is Hibernate vs JPA?
16. Hibernate
-
What is Hibernate?
-
What is ORM (Object Relational Mapping)?
-
Difference between JDBC and Hibernate?
-
What are advantages of Hibernate?
-
What is SessionFactory in Hibernate?
-
What is Session in Hibernate?
-
Difference between openSession and getCurrentSession?
-
What is Hibernate caching?
-
What is first-level cache in Hibernate?
-
What is second-level cache in Hibernate?
-
What are different caching providers in Hibernate?
-
What is Criteria API?
-
Difference between HQL and SQL?
-
What is Named Query?
-
What is Lazy Loading in Hibernate?
-
What is Eager Loading in Hibernate?
-
What is dirty checking in Hibernate?
-
What are Hibernate annotations?
-
What is Hibernate Validator?
-
Difference between get() and load() in Hibernate?
17. Java Concurrency Advanced
-
What is Callable in Java?
-
What is FutureTask?
-
What is CompletionService?
-
What is ForkJoinPool?
-
What is parallelStream()?
-
Difference between parallel() and sequential() in streams?
-
What is volatile keyword?
-
Difference between volatile and synchronized?
-
What is Atomic classes in Java?
-
What is ReentrantLock?
-
Difference between ReentrantLock and synchronized?
-
What is ReadWriteLock?
-
What is Semaphore?
-
What is CountDownLatch?
-
What is CyclicBarrier?
-
Difference between CyclicBarrier and CountDownLatch?
-
What is Phaser in Java?
-
What is Exchanger in Java?
-
What are ThreadLocal variables?
-
What is ThreadFactory?
18. Java Security
-
What is Java Security API?
-
What is Encryption and Decryption?
-
Difference between symmetric and asymmetric encryption?
-
What is RSA in Java?
-
What is AES in Java?
-
What is MessageDigest class?
-
What is SHA-256 hashing?
-
What is digital signature in Java?
-
What is KeyStore in Java?
-
What is SSLContext in Java?
19. Java Microservices
-
What are microservices?
-
Difference between monolithic and microservices architecture?
-
What is Spring Boot’s role in microservices?
-
What is Spring Cloud?
-
What is Netflix Eureka?
-
What is service discovery in microservices?
-
What is API Gateway in microservices?
-
What is Zuul vs Spring Cloud Gateway?
-
What is circuit breaker pattern?
-
What is Hystrix?
-
What is Resilience4j?
-
What is Config Server in Spring Cloud?
-
Difference between synchronous and asynchronous communication in microservices?
-
What is REST vs gRPC in microservices?
-
What is distributed tracing?
-
What is Zipkin in microservices?
-
What is Sleuth in Spring Cloud?
-
What is load balancing in microservices?
-
What is Ribbon in Spring Cloud?
-
What are advantages of microservices over monolithic?
20. Java Testing (JUnit & Mockito)
-
What is JUnit in Java?
-
Difference between JUnit 4 and JUnit 5?
-
What are annotations in JUnit?
-
What is @BeforeEach and @AfterEach?
-
What is @BeforeAll and @AfterAll?
-
What is @Test annotation?
-
How to disable a test in JUnit 5?
-
What is parameterized test in JUnit?
-
What is assertEquals() in JUnit?
-
Difference between assertTrue() and assertFalse()?
-
What is Mockito?
-
Difference between mock() and spy()?
-
What is @Mock annotation?
-
What is @InjectMocks annotation?
-
What is @Captor in Mockito?
-
What is stubbing in Mockito?
-
How to verify a method call in Mockito?
-
Difference between JUnit and TestNG?
-
What is integration testing in Java?
-
What is system testing in Java?
21. Java 11/17/21 Features
-
What are new features in Java 11?
-
What is var in Java?
-
What is Local-Variable Syntax for Lambda parameters?
-
What is new HTTP client in Java 11?
-
What is String.isBlank()?
-
What is String.lines() method?
-
What is String.strip() method?
-
What is Files.readString()?
-
What is Files.writeString()?
-
What is the difference between removeIf() and replaceAll()?
-
What are new features in Java 17?
-
What is Sealed Class in Java?
-
What is instanceof pattern matching?
-
What is record class in Java?
-
Difference between record and class?
-
What is switch expression in Java?
-
What are text blocks in Java?
-
What are hidden classes?
-
What is JEP 356 (Enhanced Pseudorandom Number Generators)?
-
What are features in Java 21?
-
What is Virtual Thread in Java 21?
-
What is Structured Concurrency in Java 21?
-
What is Sequenced Collection in Java 21?
-
What is String Templates in Java 21?
-
Difference between Virtual Thread and Platform Thread?
-
What is Scoped Values in Java 21?
-
What is Pattern Matching for Switch?
-
What is Foreign Function & Memory API?
-
What is Deprecation of RMI in Java 21?
-
What is key benefit of Virtual Threads?
22. Java & Cloud
-
What is cloud-native Java?
-
How to deploy Java apps on AWS?
-
What is Elastic Beanstalk in AWS?
-
How to connect Java with S3?
-
How to connect Java with DynamoDB?
-
How to use Java Lambda in AWS?
-
How to connect Java with Google Cloud Storage?
-
What is GCP App Engine for Java?
-
What is Azure Functions with Java?
-
What is Kubernetes in microservices?
-
What is Docker?
-
How to containerize Java application?
-
Difference between Docker and Kubernetes?
-
What is Helm in Kubernetes?
-
What is ConfigMap in Kubernetes?
-
What is Secret in Kubernetes?
-
How Java apps communicate in Kubernetes?
-
What is service mesh (Istio)?
-
What is API throttling in cloud apps?
-
How to secure cloud-based Java microservices?
23. System Design + Java
-
How to design a URL shortener in Java?
-
How to design a parking lot system in Java?
-
How to design an online book store?
-
How to design a chat application?
-
How to design a payment gateway?
-
How to design a logging framework?
-
How to design a caching system?
-
How to design a search engine?
-
How to design a rate limiter?
-
How to design a notification system?
-
How to scale a Java web app?
-
Difference between vertical and horizontal scaling?
-
What is CAP theorem?
-
What is eventual consistency?
-
What is leader election in distributed systems?
-
How to design load balancer in Java?
-
How to design file storage system in Java?
-
How to design message queue system?
-
What is Kafka in Java?
-
Difference between Kafka and RabbitMQ?
24. Java Coding/Logic Questions
-
Write a program to reverse a string in Java.
-
Write a program to check palindrome string.
-
Write a program to find factorial of a number.
-
Write a program to generate Fibonacci series.
-
Write a program to check prime number.
-
Write a program to find largest element in array.
-
Write a program to find smallest element in array.
-
Write a program to sort an array.
-
Write a program to search an element in array.
-
Write a program to implement binary search.
-
Write a program to implement linear search.
-
Write a program to find duplicate elements in array.
-
Write a program to find missing number in array.
-
Write a program to count vowels and consonants in string.
-
Write a program to count words in string.
-
Write a program to swap two numbers without temp.
-
Write a program to find second largest element.
-
Write a program to implement stack in Java.
-
Write a program to implement queue in Java.
-
Write a program to implement linked list in Java.
-
Write a program to reverse linked list.
-
Write a program to check balanced parentheses.
-
Write a program to implement binary tree.
-
Write a program to implement binary search tree.
-
Write a program to traverse tree (inorder, preorder, postorder).
-
Write a program to find height of binary tree.
-
Write a program to check mirror trees.
-
Write a program to implement graph in Java.
-
Write a program for BFS in graph.
-
Write a program for DFS in graph.
-
Write a program for Dijkstra’s algorithm.
-
Write a program for Floyd Warshall algorithm.
-
Write a program for LRU Cache in Java.
-
Write a program for Producer-Consumer problem.
-
Write a program for Dining Philosopher problem.
-
Write a program to implement Singleton.
-
Write a program to implement Factory Pattern.
-
Write a program to implement Observer Pattern.
-
Write a program to implement Strategy Pattern.
-
Write a program to implement Proxy Pattern.
25. Tricky Java Questions
-
Can we overload main() method in Java?
-
Can we run Java program without main()?
-
Why String is immutable in Java?
-
Can we make constructor final?
-
Can we make abstract method static?
-
Can we override static method?
-
Can we override private method?
-
Can constructor be synchronized?
-
What happens if we call System.exit() in try block?
-
What happens if exception occurs in finally block?
-
Can interface have private methods?
-
Can we create object of interface using anonymous class?
-
Can enum extend class in Java?
-
Can enum implement interface?
-
Can we use multiple public classes in one file?
-
What happens if constructor throws exception?
-
Can we serialize static variables?
-
Can we serialize transient variables?
-
Can we have two classes with same name in same package?
-
Can abstract class have constructor?
-
Can we achieve multiple inheritance in Java?
-
What is diamond problem in Java?
-
Why multiple inheritance is not supported in Java?
-
Difference between shallow copy and deep copy?
-
Why Java is platform independent?
26. Miscellaneous & Advanced
-
What is Reactive Programming in Java?
-
What is Project Reactor?
-
What is RxJava?
-
What is CompletableFuture?
-
What is difference between Future and CompletableFuture?
-
What is Java Flight Recorder (JFR)?
-
What is GraalVM?
-
What is Quarkus in Java?
-
What is Micronaut framework?
-
What is Jakarta EE?
-
Difference between Java EE and Jakarta EE?
-
What is SOAP vs REST in Java?
-
What is gRPC in Java?
-
What is WebFlux in Spring?
-
What is Server-Sent Events (SSE) in Java?
-
What is reactive streams in Java?
-
What is backpressure in reactive programming?
-
What is Akka in Java?
-
What is Vert.x in Java?
-
What is Domain Driven Design (DDD) in Java?
-
What is Hexagonal Architecture in Java?
-
What is Event Sourcing in Java?
-
What is CQRS in Java?
-
What is clean code principles in Java?
-
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.
-
Write code →
Program.java -
Compile →
javac Program.java→ generatesProgram.class(bytecode) -
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.
-
Unboxing: automatically converting object → primitive.
13. Difference between == and .equals()?
-
==→ compares memory references (address). -
.equals()→ compares actual values (content).
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:
16. What is ternary operator?
๐ Ternary operator ?: is a shorthand for if-else.
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.
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:
-
Encapsulation – binding data and methods together.
-
Inheritance – acquiring properties of another class.
-
Polymorphism – one name, many forms (method overloading/overriding).
-
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.
24. What is an object in Java?
๐ An object is an instance of a class. It has state (variables) and behavior (methods).
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.
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.
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.
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).
35. What is method overriding?
๐ Redefining a parent class method in child class (runtime polymorphism).
36. Difference between overloading and overriding?
| Overloading | Overriding |
|---|---|
| Same method name, different parameters | Same method name, same parameters |
| Compile-time polymorphism | Runtime polymorphism |
| Can be done within one class | Requires 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.
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:
๐ 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:
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:
52. How to declare and initialize an array in Java?
53. What are the types of arrays in Java?
-
Single-dimensional →
int arr[] = new int[5]; -
Multi-dimensional →
int 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.
59. Difference between Array and ArrayList?
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Data Type | Primitive & Objects | Objects only |
| Performance | Fast | Slightly slower |
| Utilities | No built-in methods | Many 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?
-
Checked Exceptions → Checked at compile time (e.g., IOException, SQLException).
-
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.
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.
72. What is throws keyword?
๐ Used in method declaration to declare checked exceptions.
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.
75. What is try-with-resources in Java?
๐ Introduced in Java 7, it automatically closes resources (like files, DB connections).
76. Can we write try without catch?
๐ Yes, but only if followed by finally.
77. Can we catch multiple exceptions in one block?
๐ Yes, using | operator (Java 7+).
78. What is custom exception in Java?
๐ User-defined exceptions by extending Exception or RuntimeException.
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
finallyor 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?
| Feature | ArrayList | LinkedList |
|---|---|---|
| Storage | Dynamic array | Doubly linked list |
| Access | Fast (index-based) | Slower |
| Insert/Delete | Slower (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
nullkeys/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
ConcurrentModificationExceptionif 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.
97. What is Comparable interface in Java?
๐ Used to define natural sorting order of objects.
98. What is Comparator interface in Java?
๐ Used to define custom sorting order (external).
99. Difference between Comparable and Comparator?
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Sorting | Natural order | Custom order |
| Method | compareTo() | 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:
-
Extending
Threadclass
-
Implementing
Runnableinterface
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:
-
New
-
Runnable
-
Running
-
Waiting / Sleeping
-
Terminated
107. What is the difference between start() and run()?
-
start()→ creates a new thread and callsrun()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?
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
synchronizedkeyword (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.
๐ข 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?
-
Extend Thread class
-
Implement Runnable interface
324. Difference between Thread and Runnable?
| Feature | Thread | Runnable |
|---|---|---|
| Extend class | Yes | No |
| Multiple inheritance | Not allowed | Allowed |
| Overhead | Higher | Lower |
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 callsrun() -
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.
328. What is join() method in Java?
๐ Waits for another thread to finish before continuing execution.
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()?
| Feature | wait() | sleep() |
|---|---|---|
| Belongs to | Object | Thread |
| Releases lock | Yes | No |
| Throws | InterruptedException | InterruptedException |
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.
333. What is synchronized method in Java?
๐ Method is synchronized to lock the object for thread-safe execution.
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.
338. What is Atomic variable in Java?
๐ Variables like AtomicInteger, AtomicBoolean provide thread-safe operations without synchronized.
339. What is ExecutorService in Java?
๐ Framework to manage threads in a pool.
340. Difference between Callable and Runnable?
| Feature | Runnable | Callable |
|---|---|---|
| Return value | void | Returns value |
| Exception | Cannot throw checked | Can throw checked exception |
| Interface | Runnable | Callable<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?
| Feature | Byte Stream | Character Stream |
|---|---|---|
| Data unit | 8-bit bytes | 16-bit characters |
| Classes | FileInputStream, FileOutputStream | FileReader, FileWriter |
| Use | Binary data | Text data |
344. Difference between InputStream and OutputStream?
| Feature | InputStream | OutputStream |
|---|---|---|
| Purpose | Read data | Write data |
| Examples | FileInputStream | FileOutputStream |
345. Difference between Reader and Writer?
| Feature | Reader | Writer |
|---|---|---|
| Purpose | Read characters | Write characters |
| Example | FileReader | FileWriter |
346. How to read a file using FileReader?
347. How to write a file using FileWriter?
348. What is BufferedReader in Java?
๐ BufferedReader buffers characters for efficient reading and provides readLine() method.
349. What is BufferedWriter in Java?
๐ BufferedWriter buffers characters for efficient writing and provides newLine() method.
350. Difference between FileInputStream and FileReader?
| Feature | FileInputStream | FileReader |
|---|---|---|
| Data type | Byte | Char |
| Use | Binary files | Text files |
351. Difference between FileOutputStream and FileWriter?
| Feature | FileOutputStream | FileWriter |
|---|---|---|
| Data type | Byte | Char |
| Use | Binary files | Text files |
352. What is PrintWriter in Java?
๐ PrintWriter allows writing formatted text to files or streams.
353. Difference between Reader/Writer and InputStream/OutputStream?
| Feature | Reader/Writer | InputStream/OutputStream |
|---|---|---|
| Data type | Characters | Bytes |
| Classes | FileReader/FileWriter | FileInputStream/FileOutputStream |
| Use | Text files | Binary files |
354. What is File class in Java?
๐ Represents file or directory path, provides metadata like size, name, and permissions.
355. How to check if a file exists?
356. How to create a new file?
357. How to delete a file?
358. What is DataInputStream and DataOutputStream?
-
DataInputStream → reads primitive data types in machine-independent way
-
DataOutputStream → writes primitive data types
359. What is ObjectInputStream and ObjectOutputStream?
-
ObjectOutputStream → writes serializable objects
-
ObjectInputStream → reads serialized objects
360. What is the difference between FileInputStream and BufferedInputStream?
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
๐ข Java Serialization & Deserialization – Questions & Answers361. 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?๐
364. How to serialize an object in Java?
365. How to deserialize an object in Java?
366. What is transient keyword in Java?๐ Fields marked as
367. What is serialVersionUID in Java?๐
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?
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?
377. What exceptions can occur during serialization?
378. What exceptions can occur during deserialization?
379. Can we serialize transient fields manually?✅ Yes, by customizing writeObject/readObject methods.
380. What is the difference between Serialization and Cloning?
๐ข Java Networking – Questions & Answers381. 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?๐ 383. What are the main classes in
|
| Feature | TCP | UDP |
|---|---|---|
| Connection | Connection-oriented | Connectionless |
| Reliability | Reliable | Unreliable |
| Classes | Socket/ServerSocket | DatagramSocket/DatagramPacket |
| Use | File transfer, HTTP | Streaming, DNS |
386. What is a URL in Java?
๐ URL (Uniform Resource Locator) represents a web resource.
387. How to read data from a URL in Java?
388. What is Socket in Java?
๐ Socket is used to establish a TCP connection between client and server.
389. What is ServerSocket in Java?
๐ ServerSocket listens for client connections on a specified port.
390. Difference between Socket and ServerSocket?
| Feature | Socket | ServerSocket |
|---|---|---|
| Purpose | Client side | Server side |
| Function | Connects to server | Listens 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?
394. How to receive UDP data in Java?
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.
397. What is the difference between IP and URL?
| Feature | IP | URL |
|---|---|---|
| Meaning | Internet Protocol address | Web resource locator |
| Example | 192.168.0.1 | https://www.google.com |
| Type | Numeric | Alphanumeric + protocol |
398. What is the difference between TCP and HTTP?
| Feature | TCP | HTTP |
|---|---|---|
| Type | Protocol | Application protocol |
| Transport | Reliable connection | Uses TCP for transport |
| Use | Socket communication | Web browsing |
399. How to get local IP address in Java?
400. How to get host name from IP in Java?
๐ข 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?
-
Built-in annotations →
@Override,@Deprecated,@SuppressWarnings -
Meta-annotations →
@Retention,@Target,@Documented,@Inherited -
Custom annotations → user-defined
423. What is @Override annotation?
๐ Ensures a method overrides a superclass method. Compiler checks it.
424. What is @Deprecated annotation?
๐ Marks a method/class as outdated, compiler shows a warning.
425. What is @SuppressWarnings annotation?
๐ Tells compiler to ignore specific warnings.
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).
429. How to create custom annotation?
430. How to access custom annotation at runtime?
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?
434. How to get methods of a class using reflection?
435. How to get fields of a class using reflection?
436. How to invoke a method using reflection?
437. How to access private fields using reflection?
438. How to create object using reflection?
439. Difference between compile-time and runtime annotations?
| Feature | Compile-time | Runtime |
|---|---|---|
| Retention | SOURCE/CLASS | RUNTIME |
| Access | Compiler | Reflection |
| Example | @Override | Custom 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?
444. How to create a generic method in Java?
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.
447. What is wildcard in Generics?
๐ ? represents unknown type in Generics.
448. Difference between ? extends T and ? super T?
| Feature | ? extends T | ? super T |
|---|---|---|
| Upper bound | Subclass of T | Superclass of T |
| Use | Read-only | Write-only |
449. Difference between generic class and generic method?
| Feature | Generic Class | Generic Method |
|---|---|---|
| Type parameter | Class-level | Method-level |
| Scope | Entire class | Only method |
| Example | class 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?
| Feature | Compile-time | Runtime |
|---|---|---|
| Type checking | Enforced | Not available (due to type erasure) |
| Example | Box<Integer> | Box is raw type at runtime |
453. What is raw type in Generics?
๐ Using a generic class without specifying a type.
454. Can we create arrays of generic types?
❌ No, cannot create generic arrays directly. Use workaround with Object array:
455. Difference between generic and non-generic code?
| Feature | Generic | Non-Generic |
|---|---|---|
| Type safety | Yes | No |
| Casting | Not required | Required |
| Reusability | High | Low |
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).
458. What is the difference between List<Object> and List<?>?
| Feature | List<Object> | List<?> |
|---|---|---|
| Type safety | Can hold Object only | Can hold unknown type |
| Use | Add/remove allowed | Add 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.
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.
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?
464. Difference between Lambda and Anonymous class?
| Feature | Lambda | Anonymous Class |
|---|---|---|
| Syntax | Short | Verbose |
this | Refers to enclosing class | Refers to anonymous object |
| Use | Functional interfaces | Any interface/class |
465. What is a Functional Interface in Java?
๐ An interface with exactly one abstract method.
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.
468. What is Function in Java?
๐ Functional interface represents a function that takes input and returns output.
469. What is Consumer in Java?
๐ Functional interface accepts input and returns void.
470. What is Supplier in Java?
๐ Functional interface provides results without input.
471. What is UnaryOperator in Java?
๐ Functional interface takes one argument and returns the same type.
472. What is BinaryOperator in Java?
๐ Functional interface takes two arguments of same type and returns same type.
473. Difference between Predicate and Function?
| Feature | Predicate | Function |
|---|---|---|
| Return | boolean | Any type |
| Input | T | T |
| Example | x -> x > 0 | x -> x*2 |
474. Difference between Consumer and Supplier?
| Feature | Consumer | Supplier |
|---|---|---|
| Input | Yes | No |
| Return | No | Yes |
| Example | x -> System.out.println(x) | () -> Math.random() |
475. Can Lambda access local variables?
✅ Yes, but must be final or effectively final.
476. What is Stream API in Java?
๐ Stream API allows functional-style operations on collections like filter, map, reduce.
477. What is difference between Collection and Stream?
| Feature | Collection | Stream |
|---|---|---|
| Data | Stores | Processes |
| Mutability | Can modify | Cannot modify |
| Lazy evaluation | No | Yes |
| Iteration | External | Internal |
478. What is map() in Stream?
๐ map() transforms elements from one type to another.
479. What is filter() in Stream?
๐ filter() selects elements based on a predicate.
480. What is reduce() in Stream?
๐ reduce() aggregates elements to produce a single result.
Comments
Post a Comment