Ans. Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle). It is platform-independent due to the "Write Once, Run Anywhere" (WORA) principle, enabled by the Java Virtual Machine (JVM).
Ans. Key features of Java include:
Ans.
Ans. Java supports two categories of data types:
Ans. A class in Java is a blueprint for creating objects and defines properties (fields) and behaviors (methods). An object is an instance of a class that contains actual values and can perform actions using methods defined in the class.
Ans. Method overloading occurs when multiple methods in the same class have the same name but different parameters. Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass.
Ans. Inheritance is a mechanism in Java by which one class can inherit the properties (fields) and behaviors (methods) of another class. It promotes code reusability.
Ans. Encapsulation is the process of wrapping code and data together into a single unit, typically a class. It helps protect data by restricting direct access using access modifiers (private, protected, public).
Ans. Polymorphism means the ability of a variable, function, or object to take multiple forms. It can be achieved through method overloading (compile-time) and method overriding (runtime).
Ans. Abstraction is the concept of hiding implementation details and showing only the functionality to the user. It is achieved using abstract classes and interfaces.
Ans. An abstract class can have both abstract and non-abstract methods, whereas an interface can only have abstract methods (prior to Java 8). Interfaces support multiple inheritance; abstract classes do not.
Ans. The final
keyword is used to declare constants, prevent method overriding, and inheritance of classes.
Ans. A constructor is a special method used to initialize objects. It has the same name as the class and has no return type.
Ans. The ==
operator compares references (memory locations), while the equals()
method compares the actual content or values of objects.
Ans. The static
keyword is used to define variables and methods that belong to the class rather than any object instance.
Ans. Exception handling is a mechanism to handle runtime errors, ensuring normal program flow. It uses keywords like try, catch, finally, throw, and throws.
Ans. Checked exceptions are checked at compile-time (e.g., IOException), while unchecked exceptions are checked at runtime (e.g., NullPointerException).
Ans. Multithreading is a Java feature that allows concurrent execution of two or more threads for maximum CPU utilization.
Ans. String
is immutable, StringBuilder
is mutable and not thread-safe, StringBuffer
is mutable and thread-safe.
Ans. Garbage collection is an automatic process in Java that reclaims memory used by objects that are no longer reachable in the program.
Ans. A package is a namespace that organizes classes and interfaces. It helps avoid name conflicts and controls access using protected and default access levels.
Ans. The super
keyword refers to the immediate parent class object. It is used to access parent class methods, variables, and constructors.
Ans. this
refers to the current class instance. It is commonly used to resolve naming conflicts and pass the current object as a parameter.
Ans. Method overriding occurs when a subclass provides its own implementation of a method defined in the parent class using the same method name and parameters.
Ans. Java does not support multiple inheritance with classes to avoid ambiguity. However, it supports multiple inheritance using interfaces.
Ans. Wrapper classes convert primitive data types into objects. Examples include Integer, Double, Character, etc.
Ans. Annotations provide metadata about the program but are not part of the program logic. Examples: @Override, @Deprecated, @SuppressWarnings.
Ans. ArrayList is backed by an array and offers fast random access, while LinkedList uses a doubly-linked list structure and is better for frequent insertions/deletions.
Ans. Synchronization is used to control access to shared resources by multiple threads to prevent data inconsistency. It can be done using the synchronized keyword or blocks.
Ans. A class is a blueprint for objects with method implementations, while an interface is a contract that contains abstract methods. Classes can implement multiple interfaces but extend only one class.
Ans. A static block is used for static initialization of a class. It runs once when the class is loaded into memory.
Ans. Static methods belong to the class and can be called without an instance. Instance methods require an object of the class to be invoked.
Ans. The final
keyword is used to define constants, prevent method overriding, and inheritance of classes.
Ans. The ==
operator compares object references, while equals()
compares the actual contents of the objects.
Ans. A constructor is a special method used to initialize objects. It has the same name as the class and no return type.
Ans. Yes, private constructors are used in singleton design patterns to restrict object creation from outside the class.
Ans. Garbage collection is the process of automatic memory management that deletes unused objects to free memory.
Ans. An abstract class can have both abstract and concrete methods, while an interface only has abstract methods (until Java 8+ which allows default and static methods).
Ans. Access modifiers define the visibility of classes, methods, and variables. Types: public, private, protected, and default.
Ans. throw
is used to explicitly throw an exception, while throws
is used in method signatures to declare possible exceptions.
Ans. Exception handling is a mechanism to handle runtime errors using try, catch, finally, throw, and throws keywords.
Ans. It's a try block that declares resources, which are closed automatically after execution, used primarily for managing I/O streams.
Ans. Multithreading allows concurrent execution of two or more threads to perform tasks simultaneously for better performance.
Ans. The thread states are: New, Runnable, Blocked, Waiting, Timed Waiting, and Terminated.
Ans. A process is an independent executing program, while a thread is a lightweight subprocess that shares the same memory space.
Ans. It is a set of classes and interfaces that implement commonly reusable data structures such as List, Set, Map, and Queue.
Ans. HashMap is not synchronized and allows one null key, while Hashtable is synchronized and does not allow any null keys or values.
Ans. The transient
keyword prevents variables from being serialized during object serialization.
Ans. A singleton class allows only one instance to be created and provides a global point of access to it.
Ans. String is immutable, StringBuffer is mutable and thread-safe, and StringBuilder is mutable but not thread-safe.
Ans. A marker interface is an empty interface used to signal the JVM or compiler, such as Serializable or Cloneable.
Ans. Method overloading is when multiple methods have the same name but different parameter lists in the same class.
Ans. Compile-time polymorphism is achieved through method overloading, while runtime polymorphism is achieved through method overriding.
Ans. The instanceof
operator checks if an object is an instance of a specific class or implements an interface.
Ans. A classloader is a subsystem of the JVM responsible for loading class files when required.
Ans. Public is accessible everywhere, private only within the class, protected in the same package or subclass, and default only in the same package.
Ans. Autoboxing is the automatic conversion of primitive types to wrapper classes, and unboxing is the reverse process.
Ans. A daemon thread runs in the background and does not prevent the JVM from exiting once all user threads are done.
Ans. final
is a keyword, finally
is a block that executes after try-catch, and finalize()
is a method called by the garbage collector before object destruction.
Ans. JVM is a part of the Java Runtime Environment that executes Java bytecode and provides platform independence.
Ans. Method hiding occurs when a static method in a subclass has the same signature as a static method in the parent class. The method that gets called depends on the reference type.
Ans. The volatile
keyword ensures visibility and ordering of changes to variables across threads. It prevents caching of variables and guarantees the latest value is read.
Ans. Object cloning is the process of creating an exact copy of an object using the clone()
method from the Cloneable
interface.
Ans. A static nested class is a nested class that is declared static. It can access the static members of the outer class and doesn't require an outer class instance to be instantiated.
Ans. A functional interface contains exactly one abstract method and can be used as the assignment target for lambda expressions. Example: Runnable
, Comparator
.
Ans. A lambda expression is a concise way to represent an anonymous function. It provides a clear and concise way to implement functional interfaces.
Ans. Stream API allows functional-style operations on streams of data such as map, filter, reduce, etc., and enables bulk data processing.
Ans. Default methods are methods in interfaces with default implementations. They allow interfaces to evolve without breaking existing implementations.
Ans. Optional
is a container object used to contain not-null objects. It helps avoid null pointer exceptions.
Ans. Fail-fast iterators throw ConcurrentModificationException
if the collection is modified, while fail-safe iterators work on a clone of the collection.
Ans. Reflection is an API that allows inspection and modification of classes, interfaces, methods, and fields at runtime.
Ans. Enums define a set of constant values. They are type-safe and can have fields, methods, and constructors.
Ans. The transient
keyword prevents fields from being serialized during object serialization.
Ans. A shallow copy copies object references, whereas a deep copy creates copies of all objects recursively.
Ans. The strictfp
keyword ensures consistent floating-point calculations across platforms.
Ans. Stack memory is used for method execution and local variables, while heap memory stores objects and class instances.
Ans. A method reference is a shorthand for calling a method. It uses the ::
operator and is used with functional interfaces.
Ans. Serialization is converting an object into a byte stream. Deserialization is the process of converting a byte stream back into an object.
Ans. Comparable
provides a natural ordering using the compareTo()
method, while Comparator
allows custom ordering using compare()
.
Ans. JMM defines how threads interact through memory and ensures visibility and ordering of variables across threads.
Ans. Path
is an interface in Java NIO for representing file paths, while File
is a legacy class used for file and directory operations.
Ans. A memory leak occurs when objects are no longer used but still referenced, preventing garbage collection.
Ans. Stack overflow occurs when the stack memory is full due to deep recursion. OutOfMemoryError occurs when heap memory is exhausted.
Ans. Weak references allow objects to be garbage collected even if they are still referenced. Useful for memory-sensitive caches.
Ans. It is used for parallel task execution by breaking tasks into smaller sub-tasks using recursive decomposition.
Ans. A phantom reference is the weakest level of reference and is used to determine exactly when an object is removed from memory.
Ans. Arrays are fixed in size and can hold primitives, while ArrayLists are dynamic and only hold objects.
Ans. It is called by the garbage collector before destroying the object to perform cleanup, though its use is discouraged.
Ans. Just-In-Time compiler converts bytecode to native code during runtime for performance optimization.
Ans. Checked exceptions must be handled at compile-time, while runtime exceptions occur during execution and can be optionally handled.
Ans. Static import allows static members to be used without class qualification, improving code readability.
Ans. Hybrid inheritance is a mix of two or more types of inheritance. Java doesn't support it directly with classes but allows it through interfaces.
Ans. Varargs allow a method to accept a variable number of arguments, declared using ...
.
Ans. System.out
is used for standard output, and System.err
is used to display error messages.
Ans. The assert
keyword is used for debugging to test assumptions in code. It throws an error if the condition is false.
Ans. java
launches the Java application, while javac
is the compiler that converts Java source code into bytecode.
Ans. The Java Memory Model (JMM) defines rules for how threads interact through memory, ensuring consistency and visibility.
Ans. notify()
wakes up one waiting thread, while notifyAll()
wakes up all waiting threads on the object.
Ans. It provides classes for concurrency and multithreading such as ExecutorService, BlockingQueue, and CountDownLatch.
Ans. Immutable classes are those whose objects cannot be modified once created. Example: String
, Integer
.