Java common questions
Okay, here are concise explanations for each of your requested comparisons:
-
Public vs Private access modifiers
-
Public: Members (classes, methods, variables) declared
public
are accessible from any other class, anywhere. -
Private: Members declared
private
are accessible only within the class in which they are declared. This is key for encapsulation.
-
Public: Members (classes, methods, variables) declared
-
Static methods vs Instance methods
-
Static methods: Belong to the class itself, not to an instance of the class. Called using
ClassName.methodName()
. Cannot directly access instance variables orthis
reference. -
Instance methods: Belong to an instance (object) of the class. Called using
objectName.methodName()
. Can access instance variables and thethis
reference.
-
Static methods: Belong to the class itself, not to an instance of the class. Called using
-
Primitive data types vs Objects
-
Primitive data types: Basic data types (
int
,char
,boolean
,float
,double
,byte
,short
,long
). Store actual values directly. Not objects, have no methods. Stored on the stack (for local variables). - Objects: Instances of classes. Store references (memory addresses) to the actual data, which resides on the heap. Have state (fields) and behavior (methods).
-
Primitive data types: Basic data types (
-
Wrapper classes (Integer, String) vs Primitive types (int, String)
-
Correction:
String
is always an object, not a primitive. The comparison is usuallyInteger
vsint
. -
Wrapper classes (e.g.,
Integer
,Boolean
): Object representations of primitive types. Can benull
. Used in collections (which can only store objects). Provide utility methods. -
Primitive types (e.g.,
int
,boolean
): Direct value types. Cannot benull
. More memory and performance efficient for simple operations. -
String
: Is always an object type in Java, immutable. It's not a primitive.
-
Correction:
-
Array vs List
- Array: Fixed-size data structure. Can store primitives or objects of the same type. Basic, language-level feature.
-
List (Interface): Part of the Java Collections Framework (e.g.,
ArrayList
,LinkedList
). Dynamically resizable. Stores only objects. Offers more methods and flexibility.
-
Set vs List
-
Set (Interface): Collection that does not allow duplicate elements. Order is not guaranteed (e.g.,
HashSet
) or can be based on insertion (LinkedHashSet
) or natural/custom sorting (TreeSet
). - List (Interface): Ordered collection that allows duplicate elements. Elements are accessed by their integer index.
-
Set (Interface): Collection that does not allow duplicate elements. Order is not guaranteed (e.g.,
-
Comparable vs Comparator
-
Comparable (Interface): Implemented by a class to define its natural ordering. Has one method:
compareTo()
. The class itself decides how its instances should be sorted. -
Comparator (Interface): Implemented as a separate class to define custom or multiple orderings for objects of another class. Has one main method:
compare()
. Useful when you can't modify the class or need different sorting criteria.
-
Comparable (Interface): Implemented by a class to define its natural ordering. Has one method:
-
Interface vs Abstract class
-
Interface: A contract specifying methods a class must implement. Cannot have instance variables (only
public static final
constants). Can havedefault
andstatic
methods (Java 8+). A class can implement multiple interfaces. Defines "what" a class can do. - Abstract class: Cannot be instantiated. Can have abstract (unimplemented) and concrete (implemented) methods. Can have instance variables. A class can extend only one abstract class. Provides a base with some common functionality for "is-a" relationships.
-
Interface: A contract specifying methods a class must implement. Cannot have instance variables (only
-
Final vs Static keyword
-
Final:
- Variable: Value cannot be changed after initialization (constant).
- Method: Cannot be overridden by subclasses.
- Class: Cannot be subclassed (inherited from).
-
Static:
- Variable: Class-level variable, shared among all instances of the class.
- Method: Class-level method, can be called without creating an instance of the class.
- Block: Executed once when the class is loaded.
- Nested Class: Can be instantiated without an instance of the outer class.
-
They are orthogonal concepts and can be used together (e.g.,
public static final String MY_CONSTANT = "value";
)
-
Final:
-
== vs equals() method
-
==
operator:- For primitive types: Compares values.
- For objects: Compares memory addresses (references). Checks if two references point to the exact same object.
-
equals()
method:- Defined in the
Object
class (default implementation is==
). - Often overridden in classes (e.g.,
String
,Integer
) to compare the content or logical equality of objects, not just their references.
- Defined in the
-
-
Autoboxing vs Unboxing
-
Autoboxing: Automatic conversion by the Java compiler of a primitive type to its corresponding wrapper class object (e.g.,
int
toInteger
). -
Unboxing: Automatic conversion by the Java compiler of a wrapper class object back to its corresponding primitive type (e.g.,
Integer
toint
).
-
Autoboxing: Automatic conversion by the Java compiler of a primitive type to its corresponding wrapper class object (e.g.,
-
Checked exceptions vs Unchecked exceptions
-
Checked exceptions: Subclasses of
Exception
(excludingRuntimeException
). Must be declared in thethrows
clause of a method or handled in atry-catch
block. Compiler enforces this. Represent anticipated, recoverable problems (e.g.,IOException
,SQLException
). -
Unchecked exceptions: Subclasses of
RuntimeException
orError
. Do not need to be declared or caught (though they can be). Usually indicate programming errors (e.g.,NullPointerException
,ArrayIndexOutOfBoundsException
) or unrecoverable system issues (OutOfMemoryError
).
-
Checked exceptions: Subclasses of
-
Thread vs Runnable
-
Thread (Class): An instance of
Thread
is a thread of execution. You extend theThread
class and override itsrun()
method. Limits a class to single inheritance. -
Runnable (Interface): An instance of a class implementing
Runnable
has a task that can be executed by a thread. You implement theRunnable
interface (itsrun()
method) and pass an instance to aThread
constructor. More flexible as it allows multiple inheritance of interfaces and separates the task from the execution mechanism. Generally preferred.
-
Thread (Class): An instance of
-
StringBuilder vs StringBuffer
- StringBuilder: Mutable sequence of characters. Not synchronized (not thread-safe). Faster. Preferred for single-threaded environments.
- StringBuffer: Mutable sequence of characters. Synchronized (thread-safe). Slower due to synchronization overhead. Use when multiple threads might modify the string.
-
Synchronized methods vs Synchronized blocks
-
Synchronized methods: Lock the entire method using the object's monitor (
this
for instance methods, theClass
object for static methods). Simpler to implement but can lead to lower concurrency if only a small part of the method needs protection. -
Synchronized blocks: Allow finer-grained locking on a specific object's monitor for only a critical section of code within a method. Offers more control and potentially better concurrency.
synchronized(objectToLock) { ... }
-
Synchronized methods: Lock the entire method using the object's monitor (
-
Abstract class vs Concrete class
-
Abstract class: A class declared with the
abstract
keyword. Cannot be instantiated directly. May contain abstract methods (methods without a body, declared withabstract
) that must be implemented by concrete subclasses. Designed to be a base for other classes. - Concrete class: A regular class that can be instantiated. All its methods have implementations (either directly or inherited).
-
Abstract class: A class declared with the
-
Method Overloading vs Method Overriding
- Method Overloading (Compile-time Polymorphism): Defining multiple methods in the same class (or superclass) with the same name but different parameter lists (number, type, or order of parameters). The return type can be different.
-
Method Overriding (Runtime Polymorphism): A subclass provides a specific implementation for a method that is already defined in its superclass. The method signature (name, parameters) must be the same, and the return type must be the same or a covariant type.
@Override
annotation is used.
-
Serialization vs Deserialization
-
Serialization: The process of converting an object's state (its field values) into a byte stream, which can then be stored in a file, sent over a network, or stored in a database. The class must implement the
java.io.Serializable
marker interface. - Deserialization: The reverse process of reconstructing an object from its serialized byte stream representation.
-
Serialization: The process of converting an object's state (its field values) into a byte stream, which can then be stored in a file, sent over a network, or stored in a database. The class must implement the
-
HashMap vs TreeMap
-
HashMap: Implements
Map
. Uses a hash table. Does not guarantee any order of iteration. Allows onenull
key and multiplenull
values. Offers averageO(1)
time complexity forget
andput
. -
TreeMap: Implements
SortedMap
. Uses a red-black tree. Stores entries sorted by their keys (natural order or by a providedComparator
). Does not allownull
keys (if using natural ordering). OffersO(log n)
time complexity forget
andput
.
-
HashMap: Implements
-
ArrayList vs LinkedList
-
ArrayList: Implements
List
using a dynamically resizable array. Fast random access (get(index)
isO(1)
). Slower for additions/removals in the middle (O(n)
) because elements need to be shifted. -
LinkedList: Implements
List
using a doubly-linked list. Slower random access (get(index)
isO(n)
). Faster for additions/removals at the beginning, end, or middle (if an iterator is positioned,O(1)
) as only pointers need to be updated. Higher memory overhead per element.
-
ArrayList: Implements
-
HashMap vs Hashtable
-
HashMap: Not synchronized (not thread-safe). Allows one
null
key and multiplenull
values. Faster. Part of the Java Collections Framework. Preferred for non-concurrent use. -
Hashtable: Synchronized (thread-safe). Does not allow
null
keys ornull
values (throwsNullPointerException
). Slower due to synchronization. A legacy class;ConcurrentHashMap
is generally preferred for thread-safe map operations.
-
HashMap: Not synchronized (not thread-safe). Allows one
-
Enum vs Constant variables
-
Constant variables (e.g.,
public static final int RED = 1;
): Provide fixed values but lack type safety (e.g., you could pass anyint
where a color constant is expected). No intrinsic grouping or behavior. - Enum (Enumeration): A special data type that enables for a variable to be a set of predefined constants. Type-safe (compiler checks values). Can have constructors, methods, and implement interfaces. Provides better readability and maintainability.
-
Constant variables (e.g.,
-
Singleton pattern vs Prototype pattern
- Singleton pattern (Creational): Ensures a class has only one instance and provides a global point of access to it. Useful for managing shared resources like database connections or logging.
- Prototype pattern (Creational): Creates new objects by copying an existing object (the prototype). Useful when object creation is expensive and you need many similar objects.
-
Garbage Collection vs Manual memory management
- Garbage Collection (GC): Automatic process (e.g., in Java, C#) where the runtime environment reclaims memory occupied by objects that are no longer referenced by the program. Reduces risks of memory leaks and dangling pointers.
-
Manual memory management: Programmer is responsible for explicitly allocating (
malloc
,new
) and deallocating (free
,delete
) memory (e.g., in C, C++). Offers more control but is error-prone.
-
Lambda expressions vs Anonymous classes
-
Lambda expressions (Java 8+): Concise syntax for creating instances of functional interfaces (interfaces with a single abstract method). Focus on the "what to do" rather than "how to create an object that does it."
(parameters) -> expression
or(parameters) -> { statements; }
. - Anonymous classes: A way to create an instance of an interface or subclass an existing class on the fly, without explicitly defining a new named class. More verbose. Can have state (fields) and multiple methods, which lambdas cannot directly. Lambdas are often syntactic sugar for simple anonymous classes implementing functional interfaces.
-
Lambda expressions (Java 8+): Concise syntax for creating instances of functional interfaces (interfaces with a single abstract method). Focus on the "what to do" rather than "how to create an object that does it."
-
Functional programming vs Object-oriented programming
- Functional Programming (FP): Paradigm that treats computation as the evaluation of mathematical functions. Emphasizes pure functions (no side effects), immutability, first-class functions, and declarative style.
- Object-Oriented Programming (OOP): Paradigm based on the concept of "objects," which bundle data (fields) and methods that operate on the data. Key principles are encapsulation, inheritance, and polymorphism. Models real-world entities.
-
Try-catch blocks vs finally blocks
- Try block: Encloses a section of code that might throw an exception.
-
Catch block: Follows a
try
block. Catches and handles a specific type of exception if it's thrown within thetry
block. -
Finally block: Follows a
try
block (and anycatch
blocks). Code within thefinally
block always executes, regardless of whether an exception was thrown or caught. Used for cleanup operations (e.g., closing resources).
-
Shallow Copy vs Deep Copy
- Shallow Copy: Creates a new object and copies the values of the fields from the original object. If a field is a reference to another object, only the reference (memory address) is copied, not the object itself. Both original and copy will point to the same referenced object.
- Deep Copy: Creates a new object and recursively copies all objects referenced by the original object. The copy and the original are completely independent; changes in one do not affect the other.
-
Stack vs Heap Memory Allocation
- Stack Memory: LIFO (Last-In, First-Out) data structure. Used for static memory allocation, storing primitive local variables and references to objects. Memory is allocated and deallocated automatically when a method is called and returns (method call stack frames). Fast access. Limited size.
-
Heap Memory: Used for dynamic memory allocation, storing objects (instances of classes) and arrays. Managed by the Garbage Collector in Java. Slower access compared to stack. Larger size. Can lead to
OutOfMemoryError
if not managed properly or if too many objects are created.
Spring / Spring Boot Specifics:
-
@SpringBootApplication vs @Configuration
-
@SpringBootApplication
: A convenience annotation that combines@Configuration
,@EnableAutoConfiguration
, and@ComponentScan
with their default attributes. Typically used on the main application class. -
@Configuration
: A class-level annotation indicating that the class declares one or more@Bean
methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime.
-
-
@ComponentScan vs @EnableAutoConfiguration
-
@ComponentScan
: Tells Spring where to look for Spring-managed components (beans marked with@Component
,@Service
,@Repository
,@Controller
, etc.). By default (when used with@SpringBootApplication
), it scans the package of the main application class and its sub-packages. -
@EnableAutoConfiguration
: Enables Spring Boot's auto-configuration mechanism, which attempts to automatically configure your Spring application based on the JAR dependencies you have added to the classpath.
-
-
@Configuration vs @Bean
-
@Configuration
: Class-level annotation. Declares that a class can contain bean definition methods. Spring processes such classes to create and manage beans. -
@Bean
: Method-level annotation. Used within a@Configuration
class. Indicates that the method produces a bean to be managed by the Spring container. The returned object from the method is registered as a bean.
-
-
@Autowired vs @Qualifier
-
@Autowired
: Marks a constructor, field, setter method, or config method to be autowired by Spring's dependency injection facilities. Spring attempts to resolve the dependency by type. If multiple beans of the same type exist, it can lead to ambiguity. -
@Qualifier("beanName")
: Used in conjunction with@Autowired
to specify which exact bean to inject when there are multiple beans of the same type. It resolves ambiguity by name.
-
-
@RestController vs @Controller
-
@Controller
: A specialization of@Component
. Marks a class as a Spring MVC controller. Handler methods typically return a view name (e.g., for Thymeleaf, JSP rendering) or redirect. -
@RestController
: A convenience annotation that combines@Controller
and@ResponseBody
. Marks a class as a controller where every handler method automatically serializes the return object into the HTTP response body (e.g., as JSON or XML). Primarily used for building RESTful APIs.
-
-
@RequestMapping vs @GetMapping
-
@RequestMapping
: A general-purpose annotation for mapping HTTP requests to handler methods. Can specify HTTP methods (GET, POST, etc.), path, headers, params. Can be used at class or method level. -
@GetMapping
: A shortcut annotation specifically for mapping HTTP GET requests. Equivalent to@RequestMapping(method = RequestMethod.GET)
. More concise for GET mappings.
-
-
@PathVariable vs @RequestParam
-
@PathVariable
: Binds a method parameter to a URI template variable. Used to extract values from the path of the URL (e.g.,/users/{id}
). -
@RequestParam
: Binds a method parameter to a web request parameter. Used to extract values from the query string of a URL (e.g.,/search?query=java
) or from submitted form data.
-
-
@PostMapping vs @PutMapping
-
@PostMapping
: A shortcut annotation specifically for mapping HTTP POST requests. Equivalent to@RequestMapping(method = RequestMethod.POST)
. Typically used for creating new resources. -
@PutMapping
: A shortcut annotation specifically for mapping HTTP PUT requests. Equivalent to@RequestMapping(method = RequestMethod.PUT)
. Typically used for updating an existing resource completely (or creating it if it doesn't exist, making it idempotent).
-
-
PUT vs PATCH (HTTP Methods)
- PUT: An HTTP method used to replace an entire resource at a specific URI with the request payload. If the resource doesn't exist, PUT might create it. Idempotent (multiple identical requests have the same effect as a single one).
- PATCH: An HTTP method used to apply partial updates to a resource. Modifies only the specified fields in the request payload, leaving other fields unchanged. Not necessarily idempotent.
-
@ExceptionHandler vs @ControllerAdvice
-
@ExceptionHandler
: A method-level annotation within a controller (or@ControllerAdvice
class). Defines a method that handles specific types of exceptions thrown by request handler methods within that controller (or globally if in@ControllerAdvice
). -
@ControllerAdvice
: A class-level annotation that allows you to consolidate common controller-related concerns (like exception handling, model attributes, init binders) into a single, global component. Often used with@ExceptionHandler
methods for centralized error handling across multiple controllers.
-
-
@Primary vs @Qualifier
-
@Primary
: When multiple beans of the same type are eligible for autowiring, the bean marked with@Primary
is given preference and will be chosen by default if no other more specific criteria (like@Qualifier
) are used. -
@Qualifier("beanName")
: Used to explicitly specify which named bean to inject when multiple beans of the same type exist. It overrides@Primary
if both are present and a qualifier is used at the injection point.
-
-
@Async vs @Scheduled
-
@Async
: Marks a method to be executed asynchronously in a separate thread, managed by Spring. The caller does not wait for the method to complete. Requires@EnableAsync
on a configuration class. -
@Scheduled
: Marks a method to be executed at scheduled intervals or fixed times (e.g., using cron expressions, fixed rate, or fixed delay). Requires@EnableScheduling
on a configuration class.
-
-
@Cacheable vs @CacheEvict
-
@Cacheable
: Marks a method whose result should be cached. If the method is called again with the same arguments, the cached result is returned directly without executing the method body. Requires@EnableCaching
and a cache manager. -
@CacheEvict
: Marks a method that should trigger cache eviction (removal of one or more entries from the cache). Typically used when data that might be cached is modified (e.g., after an update or delete operation).
-
-
application.properties vs application.yml
- Both are files used in Spring Boot to externalize application configuration.
-
application.properties
: Uses standard Java properties file format (key=value pairs). Simple, flat structure. -
application.yml
(or.yaml
): Uses YAML (YAML Ain't Markup Language) format. More hierarchical and often considered more readable for complex configurations. Supports lists, maps, and more structured data representation. Spring Boot gives YAML precedence if both files exist for the same property.
-
Microservices architecture vs Monolithic architecture
- Monolithic architecture: The entire application is built as a single, large, undecomposable unit. All modules are tightly coupled and deployed together. Simpler to develop and deploy initially, but can become hard to scale, maintain, and update.
- Microservices architecture: The application is structured as a collection of small, independent, loosely coupled services. Each service focuses on a specific business capability and can be developed, deployed, and scaled independently. Offers better scalability, resilience, technology diversity, and team autonomy, but introduces complexity in management, deployment, and inter-service communication.
-
JAR vs WAR files
- JAR (Java Archive): Standard Java packaging format. Can contain compiled Java classes, resources, and a manifest file. Used for libraries, plugins, or executable Java applications (if it includes a main class and is marked as executable). Spring Boot typically produces executable JARs (fat JARs) that embed a servlet container.
-
WAR (Web Application Archive): Specifically for packaging Java web applications to be deployed on a standalone servlet container (e.g., Tomcat, Jetty, WebLogic). Contains web resources (HTML, CSS, JS), servlets, JSPs, Java classes (
WEB-INF/classes
), and libraries (WEB-INF/lib
).
-
Maven vs Gradle
- Both are build automation tools and dependency management tools for Java projects.
-
Maven: Uses XML for configuration (
pom.xml
). Emphasizes "convention over configuration." Well-established, large ecosystem. Can be verbose. Relies on a lifecycle of phases and goals. -
Gradle: Uses a Groovy or Kotlin-based DSL (Domain Specific Language) for build scripts (
build.gradle
). More flexible and expressive. Often offers better performance due to incremental builds and build caching. Can have a steeper learning curve for complex customizations.
-
Continuous Integration vs Continuous Deployment
- Continuous Integration (CI): A development practice where developers frequently merge their code changes into a central repository, after which automated builds and tests are run. Aims to detect integration issues early and often.
- Continuous Deployment (CD): Extends CI. Every code change that passes all stages of the CI pipeline (build, automated tests) is automatically deployed to a production environment. Aims for rapid and reliable releases. (Often, "Continuous Delivery" is a prerequisite, meaning every change is releasable, but the actual deployment to production might be a manual business decision).
-
Agile vs Waterfall methodologies
- Waterfall: A traditional, sequential software development methodology. Progress flows downwards through distinct phases: requirements, design, implementation, testing, deployment, and maintenance. Less flexible to changes once a phase is complete.
- Agile: An iterative and incremental approach to software development. Emphasizes collaboration, customer feedback, rapid delivery of working software in small increments (sprints/iterations), and adaptability to changing requirements. (Examples: Scrum, Kanban).
-
RESTful API vs SOAP API
- RESTful API (Representational State Transfer): An architectural style for designing networked applications. Uses standard HTTP methods (GET, POST, PUT, DELETE, etc.). Typically uses JSON or XML for data format over HTTP/HTTPS. Stateless, scalable, and simpler.
- SOAP API (Simple Object Access Protocol): A protocol for exchanging structured information. Uses XML for its message format and usually relies on other application layer protocols (most notably HTTP or SMTP) for message negotiation and transmission. More rigid, has built-in standards for security (WS-Security), transactions, etc. Can be stateful. Generally more complex and verbose than REST.
-
Reactive programming vs Imperative programming
- Imperative programming: A paradigm where you write code that describes how to achieve results using a sequence of statements that change the program's state. Traditional procedural and most object-oriented programming falls into this category (e.g., "do this, then do that, then update this variable").
- Reactive programming: A declarative programming paradigm concerned with data streams and the propagation of change. You define data flows, and the system reacts to changes in those flows automatically. Asynchronous and event-driven. Focuses on what should happen when data arrives or changes (e.g., spreadsheets, UI event handling, Spring WebFlux).
No Comments