Java interview questions

Here are the top 50 questions viewed by experienced Java developers, along with brief answers:

  1. What is the difference between ArrayList, Vector LinkedList in Java?
Feature ArrayList Vector LinkedList
Underlying Data Structure Dynamic array Dynamic array Doubly linked list
Synchronization Not synchronized (not thread-safe) Synchronized (thread-safe) Not synchronized (not thread-safe)
Performance Faster for most operations (especially retrieval) Slower due to synchronization overhead Generally slower for access due to node traversal
Access Time O(1) for getting elements O(1) for getting elements O(n) for getting elements
Insertion Time O(n) for inserting elements (especially in the middle) O(n) for inserting (same as ArrayList) O(1) for adding/removing at both ends, O(n) for middle
Deletion Time O(n) for removing elements (especially in the middle) O(n) for removing (same as ArrayList) O(1) for removing at both ends, O(n) for middle
Memory Overhead Less memory overhead (only array) More memory overhead (node pointers) More memory overhead (node pointers)
Growth Grows by resizing the array (usually doubles) Grows by resizing the array (usually doubles) Grows by adding new nodes
Use Case Better for random access and frequent retrieval Suitable for legacy code or when thread safety is needed Better for frequent insertions and deletions
Enumeration Fail-fast iterator Fail-fast iterator Fail-fast iterator
  1. What is the purpose of the final keyword in Java?

    • The final keyword is used to create constants, prevent method overriding, and prevent class inheritance.
  2. What is the difference between fail-fast and fail-safe iterators in Java?

    • fail-fast iterators throw a ConcurrentModificationException if the underlying collection is modified while the iterator is in use.
    • fail-safe iterators create a copy of the underlying collection, so modifications to the collection do not affect the iterator.
  3. What is the purpose of the synchronized keyword in Java?

    • The synchronized keyword is used to ensure thread safety by allowing only one thread to access a specific resource (method or block of code) at a time.
  4. Explain the difference between throw and throws in Java.

    • throw is used to manually throw an exception object.
    • throws is used in a method declaration to indicate that the method may throw one or more exceptions.
  5. What is the purpose of the static keyword in Java?

    • The static keyword is used to create class-level variables and methods that can be accessed without creating an instance of the class.
  6. What is the difference between abstract and interface

Feature Abstract Class Interface
Definition A class that cannot be instantiated and can contain both abstract and concrete methods. A reference type that can contain only abstract methods (Java 7 and earlier) and static/default methods (Java 8 and later).
Inheritance Supports single inheritance only. Supports multiple inheritance through interfaces.
Method Implementation Can have both abstract methods (without body) and concrete methods (with body). Can have only abstract methods (prior to Java 8) but can have default and static methods (from Java 8).
Access Modifiers Can have any access modifier (public, protected, private). All methods are implicitly public; cannot have private or protected methods (except default/static methods).
Field Declaration Can have instance variables with any access modifier. Can only have static final variables (constants).
Constructor Can have a constructor. Cannot have a constructor.
Use Case Use when classes share a common base and can have shared code or state. Use when classes need to implement a contract or behavior without sharing code.
Instantiation Cannot be instantiated directly. Cannot be instantiated directly.
Default Method Cannot have default methods. Can have default methods (from Java 8).
  1. Explain the difference between == and .equals() in Java.

    • == compares the reference (memory address) of two objects, while .equals() compares the content (values) of two objects.
  2. What is the purpose of the try-catch block in Java?

    • The try-catch block is used to handle exceptions in Java. The try block contains the code that may throw an exception, and the catch block contains the code to handle the exception.
  3. Explain the difference between throws and try-catch in Java.

    • throws is used in a method declaration to indicate that the method may throw one or more exceptions.
    • try-catch is used to handle exceptions within the method itself.
  4. Explain the difference between public, private, protected, and default access modifiers in Java.

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
  1. String, StringBuilder, StringBuffer
Feature String StringBuilder StringBuffer
Mutability Immutable Mutable Mutable
Synchronization Not synchronized Not synchronized (not thread-safe) Synchronized (thread-safe)
Performance Slower for concatenation and modifications Faster for concatenation and modifications Slower due to synchronization overhead
Use Case Suitable for fixed or constant strings Suitable for dynamic string manipulation in single-threaded contexts Suitable for dynamic string manipulation in multi-threaded contexts
Memory Overhead Lower (since immutable) Lower than StringBuffer Higher due to synchronization
Methods Provides methods for string operations (concatenation creates new strings) Provides mutable methods for appending, inserting, etc. Similar to StringBuilder but with synchronized methods
When to Use When you need constant strings or no modifications When you need to manipulate strings without thread safety When you need thread-safe string manipulation
  1. HashMap, LinkedHashMap, ConcurrentHashMap
Feature HashMap LinkedHashMap ConcurrentHashMap
Order No guaranteed order of elements Maintains insertion order No guaranteed order
Performance Fast for insertions and lookups (average O(1)) Slightly slower due to maintaining order (O(1) average) Good performance in concurrent scenarios (O(1) average)
Synchronization Not synchronized (not thread-safe) Not synchronized (not thread-safe) Synchronized (thread-safe)
Use Case Suitable for non-threaded applications where order is not important Suitable when order of insertion matters Suitable for concurrent access in multi-threaded environments
Null Keys/Values Allows one null key and multiple null values Allows one null key and multiple null values Does not allow null keys or values
Memory Overhead Lower memory overhead Higher memory overhead due to linked list Higher memory overhead due to segmenting for concurrency
Iteration Fail-fast iterator Fail-fast iterator Fail-safe iterator
  1. What is the purpose of the Exception class in Java?

    • The Exception class is the base class for all exception types in Java. It represents an exceptional condition that has occurred during the execution of a program.
  2. checked, unchecked exceptions

Feature Checked Exception Unchecked Exception
Definition Exceptions that are checked at compile-time Exceptions that are checked at runtime
Inheritance Subclass of Exception (not RuntimeException) Subclass of RuntimeException
Handling Requirement Must be either caught or declared in the method signature Not required to be caught or declared
Examples IOException, SQLException NullPointerException, ArrayIndexOutOfBoundsException
Use Case Typically used for recoverable conditions, such as I/O issues Typically used for programming errors or logic errors
Compile-Time Error Causes a compile-time error if not handled Does not cause a compile-time error
Common Libraries Often used in APIs that involve I/O or database operations Commonly encountered in code due to logic issues
  1. What is the purpose of the Override annotation in Java?

    • The @Override annotation is used to indicate that a method in a subclass is intended to override a method in the superclass. It helps the compiler detect errors in method overriding.
  2. Comparable, Comparator

Feature Comparable Comparator
Definition An interface used to define the natural ordering of objects An interface used to define a custom ordering of objects
Method Contains the method compareTo(T o) Contains the method compare(T o1, T o2)
Implementation Implemented in the class whose objects are to be compared Implemented in a separate class or as a lambda expression
Sorting Order Defines a single sorting order (natural order) Can define multiple sorting orders (custom order)
Usage Used when you want to define the natural ordering of objects Used when you need various ways to sort objects, e.g., by different attributes
Example Classes String, Integer, Date Custom comparator classes or lambda expressions
Modification Cannot change the natural ordering once defined Can be easily modified or created for different sorting needs
  1. What is the purpose of the Serializable interface in Java?

    • The Serializable interface is used to allow an object to be converted to a stream of bytes, which can then be stored or transmitted and later reconstructed.
  2. Explain the purpose of the final keyword for variables, methods, and classes in Java.

    • For variables, final makes the variable a constant.
    • For methods, final prevents the method from being overridden in subclasses.
    • For classes, final prevents the class from being subclassed.
  3. What is the purpose of the transient keyword in Java?

    • The transient keyword is used to mark a field in a class as not to be serialized when the object is serialized.
  4. Explain the purpose of the volatile keyword in Java.

    • The volatile keyword is used to mark a variable as accessible to multiple threads. It ensures that all threads see the latest value of the variable.
  5. Explain the purpose of the functinal interface in Java.
    A functional interface in Java is an interface that contains exactly one abstract method. It can have multiple default or static methods, but it must have only one abstract method. Functional interfaces are primarily used to enable the use of lambda expressions, which provide a clear and concise way to represent a single method interface.

Key Characteristics

  1. Single Abstract Method: A functional interface must have exactly one abstract method. This is the defining characteristic.

  2. @FunctionalInterface Annotation: Although using this annotation is not mandatory, it is a good practice. The annotation helps the compiler enforce the rule that the interface must have only one abstract method. If more than one abstract method is added, it will result in a compile-time error.

  3. Lambda Expressions: Functional interfaces can be implemented using lambda expressions, simplifying code and improving readability.

@FunctionalInterface
interface MyFunctionalInterface {
    void execute(); // Single abstract method

    // Default method
    default void defaultMethod() {
        System.out.println("This is a default method.");
    }
}

// Using the functional interface with a lambda expression
public class FunctionalInterfaceExample {
    public static void main(String[] args) {
        MyFunctionalInterface myFunc = () -> System.out.println("Executing the functional interface method.");
        myFunc.execute(); // Calls the abstract method
        myFunc.defaultMethod(); // Calls the default method
    }
}
  1. access level in Java?
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
  1. Explain the purpose of the try-with-resources statement in Java.

    • The try-with-resources statement is used to automatically close resources (such as files, connections, or streams) when the try block completes, even in the presence of exceptions.
  2. What is the purpose of the Enum class in Java?

    • The Enum class is the base class for all enum types in Java. It provides methods for working with enums, such as getting the name, ordinal, and list of values.
  3. What is the purpose of the Reflection API in Java?

    • The Reflection API in Java allows you to inspect and interact with classes, methods, fields, and constructors at runtime. This can be useful for dynamic code generation and analysis.
  4. Explain the purpose of the Future and CompletableFuture classes in Java.

    • The Future interface represents the result of an asynchronous computation. It provides methods to check the status and retrieve the result of the computation.
    • The CompletableFuture class is an implementation of the Future interface that adds support for composing, transforming, and combining asynchronous computations.
  5. What is the purpose of the Supplier, Consumer, Function, and Predicate functional interfaces in Java?

    • Supplier is a functional interface that represents a supplier of results.
    • Consumer is a functional interface that represents an operation that accepts a single input argument and returns no result.
    • Function is a functional interface that represents a function that accepts one argument and produces a result.
    • Predicate is a functional interface that represents a predicate (boolean-valued function) of one argument.
  6. Explain the purpose of the Stream API in Java.

    • The Stream API in Java provides a functional-style way of processing collections of elements. It allows you to perform various operations, such as filtering, mapping, sorting, and reducing, on data streams.
  7. What is the purpose of the Annotation feature in Java?

    • Annotations in Java are a form of metadata that can be added to Java code elements (classes, methods, variables, etc.). They can be used for a variety of purposes, such as providing additional information for the compiler, runtime environments, or other tools.
  8. Explain the purpose of the Java Concurrency API in Java.

    • The Java Concurrency API provides a set of classes and interfaces for working with concurrent and parallel programming in Java. This includes features like threads, locks, semaphores, and other synchronization primitives.
  9. What is the purpose of the Java Memory Model in Java?

    • The Java Memory Model (JMM) is a specification that defines how memory is accessed and shared between threads in a Java program. It ensures that the behavior of a program is consistent and predictable, even in the presence of concurrency.
  10. Explain the purpose of the Java Virtual Machine (JVM) in Java.

    • The Java Virtual Machine (JVM) is the core of the Java runtime environment. It is responsible for executing Java bytecode, managing memory, and providing a secure and portable execution environment for Java programs.
  11. What is the purpose of the Java Garbage Collector in Java?

    • Garbage Collection (GC) in Java is a process that automatically manages memory, reclaiming space occupied by objects that are no longer in use. It helps prevent memory leaks and optimizes memory usage. Here's a detailed explanation of how GC works, focusing on the Young Generation and Old Generation.
Memory Management in Java

Java uses a heap to manage memory, which is divided into several areas:

  1. Young Generation: This is where new objects are allocated. It is further divided into:

    • Eden Space: Where new objects are initially created.
    • Survivor Spaces: Two areas (S0 and S1) where objects that survive garbage collection in the Eden space are moved.
  2. Old Generation (Tenured Generation): This area holds long-lived objects that have survived multiple garbage collection cycles in the Young Generation.

Object Creation and Memory Allocation

  1. Creation: When an object is created using the new keyword, memory is allocated in the Eden space of the Young Generation.
  2. Reference Counting: Each object has a reference count, which tracks how many references point to it. When the reference count drops to zero, the object becomes eligible for garbage collection.
Garbage Collection Process

Young Generation GC (Minor GC)

  1. Triggering: A minor garbage collection is triggered when the Eden space is full.

  2. Marking: The GC marks all reachable objects (those still referenced) starting from the root (like local variables, static fields).

  3. Copying:

    • Survivor Spaces: Reachable objects are copied from the Eden space to one of the Survivor spaces (S0 or S1).
    • Promotion: If an object survives multiple collections (usually 15-20), it is promoted to the Old Generation.
  4. Cleaning: After copying, the Eden space and the empty Survivor space are cleared.

Old Generation GC (Major GC)

  1. Triggering: A major garbage collection occurs when the Old Generation is nearly full or when the system runs low on memory.
  2. Marking: Similar to the Young Generation, the GC marks all reachable objects in the Old Generation.
  3. Compacting: The GC compacts the memory by moving live objects together, which helps reduce fragmentation.
  4. Cleaning: Unreachable objects are reclaimed and their memory is freed up.

Generational Garbage Collection

Java's garbage collection is based on the generational hypothesis, which states that most objects die young. By segregating objects based on their age, the GC can optimize performance:

  • Young Generation: Frequent collections are efficient because most objects become unreachable quickly.
  • Old Generation: Infrequent collections are necessary since objects tend to live longer.

Tuning Garbage Collection

Java provides several options to tune the garbage collector, such as:

  • Heap Size: Adjusting the heap size using -Xms and -Xmx.
  • GC Algorithms: Selecting different garbage collection algorithms (e.g., G1, CMS, Parallel GC) depending on application needs.

Conclusion

Garbage Collection in Java is a complex but well-structured process that helps manage memory efficiently. By understanding how objects are created and memory is reclaimed in both the Young and Old Generations, developers can write more efficient code, optimize performance, and reduce the risk of memory leaks.

  1. Explain the purpose of the Java Serialization API in Java.

    • The Java Serialization API allows you to convert Java objects into a stream of bytes, which can then be transmitted or stored, and later reconstructed. This is useful for tasks like data persistence, remote method invocation, and caching.
  2. What is the purpose of the Java Native Interface (JNI) in Java?

    • The Java Native Interface (JNI) is a programming framework that allows Java code to interact with native code (such as C or C++) and vice versa. This can be useful for integrating Java with existing native libraries or for improving performance in certain scenarios.
  3. Design patterns

    • Here are the top 5 most commonly used design patterns, along with three important features for each:

Singleton

  • Purpose: Ensures a class has only one instance and provides a global point of access to it.
  • Features:
    • Lazy Initialization: The instance is created only when needed.
    • Global Access: Provides a static method to access the instance.
    • Thread Safety: Can be implemented to handle multiple threads safely.
public class Singleton {
    // Static variable to hold the single instance
    private static Singleton instance;

    // Private constructor to prevent instantiation
    private Singleton() {
        // Initialization code here
    }

    // Public method to provide access to the instance
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }

    // Example method
    public void showMessage() {
        System.out.println("Hello from Singleton!");
    }
}

// Usage
public class Main {
    public static void main(String[] args) {
        Singleton singleton1 = Singleton.getInstance();
        singleton1.showMessage(); // Output: Hello from Singleton!

        Singleton singleton2 = Singleton.getInstance();
        System.out.println(singleton1 == singleton2); // Output: true (both are the same instance)
    }
}

Factory Method

  • Purpose: Defines an interface for creating an object but allows subclasses to alter the type of objects that will be created.
  • Features:
    • Decoupling: Reduces the dependency on concrete classes.
    • Flexibility: New types of products can be added without altering existing code.
    • Encapsulation: Creation logic is encapsulated in the factory method.

Observer

  • Purpose: Establishes a one-to-many dependency between objects so that when one object changes state, all its dependents are notified.
  • Features:
    • Loose Coupling: Subjects and observers are loosely coupled.
    • Dynamic Relationships: Observers can be added or removed at runtime.
    • Event-driven: Supports an event-driven architecture, promoting responsiveness.

Decorator

  • Purpose: Adds behavior or responsibilities to objects dynamically without altering their structure.
  • Features:
    • Flexible Composition: Can combine multiple decorators to extend functionality.
    • Single Responsibility: Each decorator has its own responsibilities.
    • Open/Closed Principle: Classes can be extended without modifying existing code.

Strategy

  • Purpose: Defines a family of algorithms, encapsulates each one, and makes them interchangeable.
  • Features:
    • Encapsulation: Algorithms are encapsulated in separate classes.
    • Flexibility: Easily switch between different strategies at runtime.
    • Single Responsibility: Each strategy focuses on a specific algorithm, adhering to the single responsibility principle.

These design patterns provide foundational solutions to common software design problems, enhancing code reusability, maintainability, and flexibility.

  1. What is the purpose of the Java Internationalization API in Java?

    • The Java Internationalization API (known as java.text and java.util.locale) provides a set of classes and interfaces for handling localization-related tasks, such as formatting dates, numbers, and currencies based on the user's locale.
  2. Explain the purpose of the Java Logging API in Java.

    • The Java Logging API (also known as java.util.logging) provides a standardized way to add logging capabilities to Java applications. It allows you to log messages at different levels of severity, and to customize the output and behavior of the logging system.
  3. What is the purpose of the Java Database Connectivity (JDBC) API in Java?

    • The Java Database Connectivity (JDBC) API is a Java API that defines how clients can access a database. It provides a standard set of interfaces for connecting to a database, executing SQL statements, and processing the results.
  4. Explain the purpose of the Java Swing and JavaFX APIs in Java.

    • The Java Swing API and the JavaFX API are both Java libraries used for building graphical user interfaces (GUIs) for desktop applications. They provide a wide range of UI components, layout managers, and event handling mechanisms to help developers create rich and interactive user experiences.1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355

推荐阅读更多精彩内容