Quick Dictionary - Java
What is composition and inheritance in java?
Composition and inheritance are two mechanisms of achieving code reuse in Java. Composition allows classes to be composed of other classes as components, while inheritance allows classes to inherit properties and behaviors from a parent class. Composition emphasizes "has-a" relationships, whereas inheritance represents an "is-a" relationship.
What is volatile keyword in java?
The "volatile" keyword in Java is used to declare a variable as being shared among multiple threads. It ensures that the variable's value is always read directly from and written to the main memory, bypassing any thread-specific caching. This guarantees visibility of the latest value and prevents certain kinds of subtle concurrency issues.
What is JMM?
The Java Memory Model (JMM) defines how threads interact with the main memory and ensures proper synchronization in a multithreaded environment. It provides rules and guarantees for reading and writing shared variables, ordering of operations, and visibility of changes made by one thread to other threads. The JMM ensures thread safety by establishing a consistent and predictable memory model for concurrent programs.
What is inner classes in java?
Inner classes in Java are classes that are defined within another class. They allow for encapsulation and provide a way to logically group related classes together. Inner classes can access the members of the enclosing class, including private members, and can also have different access modifiers such as public, private, or protected.
What is lambda expression?
A lambda expression in Java is a concise way to represent an anonymous function. It allows the creation of small, single-method interfaces without the need for a separate implementation class. Lambda expressions facilitate functional programming by providing a more streamlined syntax for writing code that operates on collections, enables parallel processing, and enhances readability.
What is Java reflection API?
The Java Reflection API allows programmers to inspect, manipulate, and instantiate classes, interfaces, methods, and fields at runtime. It provides a way to introspect and analyze the structure and behavior of Java programs dynamically. Reflection enables features like runtime type inspection, dynamic loading of classes, and accessing private members of classes, but its usage should be carefully considered due to its potential impact on performance and security.
What is the purpose of java.util.concurrent package?
The java.util.concurrent package in Java provides a set of utilities and classes for concurrent programming. It offers higher-level abstractions for thread synchronization, task scheduling, and concurrent data structures. It includes classes like Executors for managing thread pools, Locks and Conditions for fine-grained synchronization, and Concurrent collections for safe concurrent access to data structures.
What is the difference between thread and runnable in java?
In Java, a Thread is a class that represents an independent unit of execution. It encapsulates a sequence of instructions that can be scheduled and run concurrently with other threads. On the other hand, a Runnable is an interface that defines a unit of work that can be executed by a thread. It provides a way to decouple the task from the thread, allowing the same task to be executed by different threads.
What is a deadlock in java?
In Java, a deadlock occurs when two or more threads are blocked forever, waiting for each other to release resources that they hold. It is a state where no progress can be made, and the threads are effectively stuck. Deadlocks commonly occur due to the improper ordering of locks or the incorrect synchronization of resources.
What is the purpose of synchronized keyword in java?
The "synchronized" keyword in Java is used to provide mutual exclusion and ensure thread safety. It can be applied to methods or blocks of code to ensure that only one thread can access the synchronized code at a time. It prevents multiple threads from concurrently modifying shared data, thus avoiding race conditions and maintaining consistency in multi-threaded programs.
What is JNI?
The Java Native Interface (JNI) is a programming framework that allows Java code to call and be called by native applications or libraries written in other languages, such as C or C++. It enables the integration of Java programs with platform-specific functionalities and leverages the power and flexibility of native code within Java applications.
What is JVM profiler?
A JVM profiler is a tool used to analyze the runtime behavior and performance of Java applications. It provides insights into the memory usage, CPU utilization, method execution times, and other metrics, allowing developers to identify performance bottlenecks and optimize their code. Profilers can help in detecting memory leaks, optimizing algorithms, and improving the overall efficiency of Java applications.
What is the difference between stack and heap memory areas in java?
In Java, the Stack and Heap are two distinct memory areas used for different purposes. The Stack is used for storing method frames, local variables, and method call information. It is organized as a stack data structure and follows a Last-In-First-Out (LIFO) order. The Heap, on the other hand, is used for dynamically allocating objects. It is a region of memory where objects are stored and managed by the garbage collector. The Stack is generally faster to access, while the Heap provides flexibility for managing and allocating objects.
What is the purpose of assert keyword in java?
The "assert" keyword in Java is used for defining assertions in the code. Assertions are conditional statements that check for specific conditions and throw an AssertionError if the condition is false. They are typically used during development and testing to verify assumptions and detect logical errors. The purpose of the "assert" keyword is to provide a convenient way to add these checks in the code and enable runtime debugging and testing.
What is generics?
Generics in Java allow the creation of classes, interfaces, and methods that can work with different types. They provide compile-time type safety and allow for the creation of reusable and type-parameterized code. Generics enable the creation of classes like ArrayList<T> or interfaces like Comparable<T>, where T represents a type parameter that can be specified at compile time.
What is shallow copy and deep copy in java?
Shallow copy and deep copy are two ways of creating copies of objects in Java. A shallow copy creates a new object that shares the same references to the fields as the original object. In contrast, a deep copy creates a new object and recursively copies all referenced objects, creating separate copies. As a result, modifying the original object's referenced objects does not affect the deep copy, while it may affect the shallow copy.
What is the difference between "==" and "equals" operator in java?
The "==" operator in Java is used for reference comparison. It checks if two object references point to the same memory location. On the other hand, the "equals()" method is used for value comparison. It compares the content or state of two objects and returns true if they are equal based on the defined equality criteria. The "equals()" method can be overridden by classes to provide custom comparison logic, while the "==" operator cannot be overridden and only performs reference comparison.
What is the purpose of "strictfp" keyword in java?
The "strictfp" keyword in Java is used to enforce strict floating-point precision. When applied to a class, interface, or method, it ensures that all floating-point calculations within that context follow the IEEE 754 standard. It guarantees consistent and portable results for floating-point computations across different platforms and ensures that the same calculation produces the same result regardless of the underlying hardware or compiler optimizations.
What is lambda expression?
Lambda expressions in Java are anonymous functions that allow the concise representation of functional interfaces. They provide a way to pass behavior as a parameter to methods, making the code more expressive and readable. Lambda expressions eliminate the need for writing verbose anonymous inner classes when working with functional interfaces, enabling functional-style programming in Java
What is the difference between comparable and comparator interfaces in java?
The Comparable and Comparator interfaces are used for object comparison in Java. The Comparable interface is implemented by a class to define a natural ordering for its instances. It provides a single method, compareTo(), which determines how objects should be ordered. On the other hand, the Comparator interface allows for custom comparison logic to be defined separately from the target class. It provides methods like compare() to compare objects based on specific criteria.
What is the difference between equals and hashcode method in java?
The "equals()" method in Java is used to compare two objects for equality based on their content or state. It is a method that can be overridden by classes to provide custom comparison logic. The "hashCode()" method, on the other hand, returns an integer value that represents the object's hash code, which is used in hash-based data structures like HashMap and HashSet. The "hashCode()" method should be implemented consistently with the "equals()" method to ensure correct behavior in collections.
What is Recursion in java?
Recursion in Java is a programming technique where a method calls itself to solve a problem by breaking it down into smaller, similar subproblems. It involves defining a base case that terminates the recursion and recursive cases that reduce the problem to a simpler form. Recursion is commonly used for solving problems that can be naturally divided into smaller instances, such as tree traversal, factorial calculation, and searching algorithms.
What is the difference between checked and unchecked exceptions in java?
Checked and unchecked exceptions are two types of exceptions in Java. Checked exceptions are exceptions that must be declared in the method signature or caught using a try-catch block. They represent exceptional conditions that a well-behaved caller should anticipate and handle. Unchecked exceptions, also known as runtime exceptions, do not need to be declared or caught explicitly. They usually indicate programming errors or unexpected conditions and can be caught or left unhandled.
What is the purpose of finalize() method in java?
The "finalize()" method in Java is a special method defined in the Object class. It is called by the garbage collector before an object is reclaimed to perform any necessary cleanup or finalization actions. It can be overridden by classes to release resources, close connections, or perform other cleanup operations. However, the usage of "finalize()" is discouraged in modern Java programming, and explicit resource management is recommended using try-with-resources or other mechanisms.
What is Anonymous classes?
Anonymous classes in Java are local classes without a name that can be defined and instantiated in a single expression. They provide a way to quickly define and use a class for a specific purpose without explicitly creating a separate class file. Anonymous classes are often used when implementing interfaces, extending abstract classes, or providing custom behavior to methods directly at the point of invocation.
What is Java Stream API?
The Java Stream API is a powerful and functional-style API introduced in Java 8. It provides a set of classes and methods for processing collections of objects in a declarative and concise manner. The Stream API enables operations like filtering, mapping, reducing, and collecting elements from a collection or other data sources. It promotes a functional programming approach, making code more readable, modular, and parallelizable
What is String builder and String buffer?
The StringBuilder and StringBuffer classes in Java are used for mutable string manipulation. StringBuilder is not thread-safe and provides better performance in single-threaded scenarios. StringBuffer, on the other hand, is thread-safe but has slightly lower performance due to the overhead of synchronization. The choice between StringBuilder and StringBuffer depends on whether thread-safety is required in the specific use case.
What is the purpose of break and continue statements in java?
The "break" and "continue" statements in Java are used to control the flow of control in loops. "break" terminates the loop and moves to the next statement outside the loop, while "continue" skips the remaining code in the loop and moves to the next iteration.
What is autoboxing and unboxing in java?
Autoboxing and unboxing are automatic conversions between primitive types and their corresponding wrapper classes in Java. Autoboxing converts primitive types to their wrapper classes, and unboxing converts wrapper classes back to primitive types, allowing seamless interconversion between the two.
What is the difference between shallow copy and deep copy?
Shallow copy creates a new object that shares the same references to the fields as the original object, while deep copy creates a new object and recursively copies all referenced objects, creating separate copies of the entire object structure.
What is enumset in java?
The "EnumSet" class in Java is a specialized implementation of the Set interface that is optimized for use with enumeration types. It provides a compact and efficient way to represent and manipulate sets of enum constants, offering better performance and type safety compared to other Set implementations.
What is Annotations?
Annotations in Java are a form of metadata that can be added to code elements like classes, methods, or variables. They provide additional information or instructions to the compiler, runtime, or other tools. Annotations are extensively used for configuration, documentation, and code analysis purposes in Java.
What is the difference between "super" and "this" keyword ?
The "super" keyword in Java is used to refer to the superclass of a class or to invoke the superclass's constructor or method. The "this" keyword, on the other hand, refers to the current instance of a class. "super" is used for accessing superclass members or resolving name conflicts, while "this" is used for accessing current instance members or invoking current constructors.
What is "try-with-resources"?
The "try-with-resources" statement in Java is used for automatic resource management. It ensures that specified resources, such as file streams or database connections, are closed properly, even if an exception occurs, by automatically invoking the close() method on the resources within the try block.
What is java executor framework?
The Java Executor Framework provides a high-level API for managing and executing concurrent tasks in Java. It abstracts the complexities of thread management, task scheduling, and resource control, offering thread pools, task queues, and thread execution services to efficiently handle asynchronous and parallel programming scenarios.
What is the difference between hashmap and hashtable?
The "HashMap" and "Hashtable" classes in Java both provide key-value pair storage, but there are a few differences. "HashMap" is not thread-safe, allows null keys and values, and offers better performance. "Hashtable" is thread-safe, does not allow null keys or values, and has slightly lower performance due to synchronization overhead.
What is java.util.function package?
The "java.util.function" package in Java provides functional interfaces that are essential for functional programming in Java. It includes interfaces such as Predicate, Function, Consumer, and Supplier, which represent common functional concepts and allow the use of lambda expressions and method references in Java.
What is Serialization and Deserialization?
Serialization is the process of converting an object into a byte stream, allowing it to be stored in memory, sent over a network, or persisted to a file. Deserialization is the reverse process of reconstructing an object from the serialized byte stream. Serialization and deserialization in Java are primarily used for object persistence, data sharing, and remote communication.
What is the difference between references and lambda expressions?
Method references and lambda expressions are both features of functional programming in Java. Lambda expressions provide a concise way to represent anonymous functions, while method references refer to existing methods by name. Method references are often used when a lambda expression simply calls an existing method without additional logic, making the code more readable and compact.
What is ThreadLocal class in java?
The "ThreadLocal" class in Java provides a way to create thread-local variables. Each thread accessing a "ThreadLocal" variable has its own independently initialized copy of the variable. It allows the storage of data that is specific to each thread and can be accessed efficiently without the need for synchronization. It is commonly used in multi-threaded environments to maintain thread-isolated state and avoid concurrency issues.
What is Classloaders in java
Classloaders in Java are responsible for loading classes into the Java Virtual Machine (JVM) at runtime. They follow a hierarchical structure and are responsible for locating, loading, and initializing classes based on the class name. Classloaders enable dynamic class loading, which allows Java applications to load classes that are not known at compile-time, making it possible to create extensible and customizable applications.
What is the difference between Hashset and TreeSet in java?
HashSet and TreeSet are implementations of the Set interface in Java, but with some differences. HashSet uses a hash-based mechanism for storing elements, providing constant-time performance for basic operations. It does not maintain any specific order of elements. On the other hand, TreeSet uses a tree data structure (usually a red-black tree) to store elements in sorted order. TreeSet offers logarithmic-time performance for basic operations but requires elements to implement the Comparable interface or have a custom Comparator to define the sorting order.
What is the purpose of "finally" block in java exception handling?
The "finally" block in Java exception handling is used to define a code section that will be executed regardless of whether an exception is thrown or not. It ensures that certain cleanup or resource release tasks are performed, such as closing open files, releasing database connections, or cleaning up temporary resources. The "finally" block is commonly used along with the "try" and "catch" blocks to handle exceptions and guarantee the execution of essential cleanup code.
What is the difference between array list and linked list in java?
ArrayList and LinkedList are implementations of the List interface in Java, but with different underlying data structures and performance characteristics. ArrayList uses a dynamic array to store elements, providing fast random access and efficient element retrieval by index. LinkedList, on the other hand, uses a doubly-linked list structure, offering fast insertion and deletion of elements, especially at the beginning or end of the list. LinkedList performs better when frequent insertion or deletion operations are required, while ArrayList is better suited for scenarios with frequent random access.