Home> Java> javaTutorial> body text

Summary of Java interview knowledge points

高洛峰
Release: 2017-02-08 10:28:55
Original
1377 people have browsed it

1. What are the primitive data types in Java, their sizes and corresponding encapsulation classes?

(1) boolean

The boolean data type is either true or false. This data type represents 1 bit of information, but its size is not precisely defined.

The "Java Virtual Machine Specification" says: "Although the boolean data type is defined, it only provides very limited support. There is no boolean value in the Java Virtual Machine Dedicated bytecode instructions and boolean values operated by Java language expressions are replaced by the int data type in the Java virtual machine after compilation, and the boolean array will be encoded into a byte array of the Java virtual machine. Each The element boolean element occupies 8 bits". In this way, we can conclude that the boolean type is 4 bytes when used alone, and 1 byte in an array. So why does the virtual machine use int instead of boolean? Why not use byte or short? Wouldn't this save more memory space? In fact, the reason for using int is that for current 32-bit CPUs, it is more efficient to exchange 32-bit data at a time.

In summary, we can know: The official document does not give a precise definition of the boolean type. The "Java Virtual Machine Specification" gives "4 bytes when used alone, and 1 byte for a boolean array." "The definition of " depends on whether the virtual machine implementation follows the specifications, so 1 byte or 4 bytes are possible. This is actually a time and space trade-off.

The encapsulation class of boolean type is Boolean.

(2)byte——1 byte——Byte

(3)short——2 bytes——Short

(4)int——4 bytes—— Integer

(5)long——8 bytes——Long

(6)float——4 bytes——Float

(7)double——8 bytes—— —Double

(8)char——2 bytes——Character

2. Let’s talk about the difference between “==” and “equals()”.

"Think in Java" says: "Relational operators generate a boolean result, and they calculate the relationship between the values of the operands."

"==" determines whether the memory addresses of the two objects are the same, and is applicable to primitive data types and enumeration types (their variables store the value itself, while reference type variables store references) ;equals is a method of the Object class, and Object's implementation is to compare memory addresses. We can override this method to customize the concept of "equal". For example, String, Date and other classes in the class library have rewritten this method.

In summary, for equality comparisons between enumerated types and primitive data types, "==" should be used; for equality comparisons between reference types, the equals method should be used.

3. What are the four types of references in Java and their application scenarios?

Strong reference: Usually the reference returned when we use the new operator to create an object is a strong reference.

Soft reference: If an object can only be reached through a soft reference, then the object is When the memory is insufficient, it will be recycled and can be used in the image cache. When the memory is insufficient, the system will automatically recycle the Bitmap that is no longer used

Weak reference: If an object can only be reached through a weak reference, then it will be recycled (Even if the memory is sufficient), it can also be used in the image cache. At this time, as long as the Bitmap is no longer used, it will be recycled

Virtual reference: Virtual reference is the "weakest" reference in Java, and it cannot even be obtained through it The only purpose of a referenced object is that when the object it points to is recycled, it will be added to the reference queue so that we can know when the object it points to is destroyed.

4. What methods are defined in object?

clone(), equals(), hashCode(), toString(), notify(), notifyAll(), wait(), finalize(), getClass()

5. What is the function of hashCode?

Please refer to the basic principles and implementation of hash tables

6. What are the differences between ArrayList, LinkedList, and Vector?

ArrayList: Internally uses arrays to store elements, supports efficient random access, and supports dynamic resizing

LinkedList: Internally uses linked lists to store elements, supports fast insertion/deletion of elements, but does not support efficient Random access

Vector: can be regarded as a thread-safe version of ArrayList

7. What is the difference between String, StringBuilder, and StringBuffer?

String: An immutable character sequence. To add new characters to it, you need to create a new String object.

StringBuilder: A variable character sequence, which supports adding new characters to it (no need to create New object)

StringBuffer: can be regarded as a thread-safe version of StringBuilder

8. Characteristics and usage of Map, Set, List, Queue and Stack.

Map : The data types that store key-value pairs in Java all implement this interface, which represents "mapping table". The two core operations supported are get(Object key) and put(K key, V value), which are used to obtain the value corresponding to the key and insert the key-value pair into the mapping table respectively.

Set : Duplicate elements are not allowed in the set type that implements this interface, representing a "set" in the mathematical sense. The core operations it supports are add(E e), remove(Object o), and contains(Object o), which are used to add elements, delete elements and determine whether a given element exists in the set respectively.

List : The list types in the collection framework in Java all implement this interface, which represents an ordered sequence. Supports get(int index), add(E e) and other operations.

Queue : The queue interface in the Java collection framework represents a "first in, first out" queue. Supports add(E element), remove() and other operations.

Stack : The data type representing the stack in the Java collection framework. The stack is a "last in, first out" data structure. Supports push(E item), pop() and other operations.

For more detailed instructions, please refer to the official documentation. Students who are not familiar with relevant data structures can refer to "Introduction to Algorithms" or other related books.

9. The difference between HashMap and HashTable

HashTable is thread-safe, but HashMap is not

HashMap allows null keys and null values. However,

is not allowed in HashTable. For more detailed analysis, please refer to the in-depth analysis of HashMap and HashTable

10. The implementation principle of HashMap

Simply put, The underlying implementation of HashMap is a "zipper-based hash table". For detailed analysis, please refer to the in-depth analysis of HashMap and HashTable

11. The implementation principle of ConcurrentHashMap

ConcurrentHashMap is a HashMap that supports concurrent reading and writing. Its characteristic is that when reading data No locking is required, and the locking granularity can be kept as small as possible when writing data. Since it uses "segmented storage" internally, you only need to lock the "segment" where the data to be written is located. For a detailed analysis of the underlying implementation of ConcurrentHashMap, please refer to Java Concurrent Programming: Concurrent Container ConcurrentHashMap

12. What is the difference between TreeMap, LinkedHashMap, and HashMap?

The underlying implementation of HashMap is a hash table, so the elements stored inside it are unordered;

The underlying implementation of TreeMap is a red-black tree, so the elements inside it are ordered. The sorting is based on natural order or the Comparator object provided when creating the TreeMap.

LinkedHashMap can remember the order in which elements are inserted.

For more detailed explanation, please refer to the differences between HashMap, LinkedMap and TreeMap

13. What is the difference between Collection and Collections?

Collection is the basic interface in the Java collection framework; Collections is a tool class provided by the Java collection framework, which contains a large number of static methods for operating or returning collections.

For those who are not familiar with the Java collection framework, please refer to Java Core Technology Points Collection Framework

14. For "try-catch-finally", if The try statement block contains a "return" statement. Will the finally statement block be executed?

The answer is that it will be executed. There are only two situations where the statements in the finally block will not be executed:

The System.exit() method is called;

The JVM "crashes".

15. Exception hierarchy in Java

The exception hierarchy in Java is as shown below:

Summary of Java interview knowledge points

We can see that the Throwable class is the base class in the exception hierarchy. The Error class represents internal errors, which are beyond our control; Exception represents exceptions, and RuntimeException and its subclasses are unchecked exceptions. Such exceptions include ArrayIndexOutOfBoundsException, NullPointerException, etc. We should avoid unchecked exceptions through conditional judgments and other statements. happened. IOException and its subclasses are checked exceptions. The compiler will check whether we have provided exception handlers for all checked exceptions that may be thrown. If not, an error will be reported. For unchecked exceptions, we do not need to catch them (of course Java also allows us to catch them, but what we should do is to avoid the occurrence of unchecked exceptions).

16. Three characteristics and meanings of Java object-oriented

Three major characteristics: encapsulation, inheritance, and polymorphism. For a detailed introduction, please click on the three major characteristics of Java object-oriented

17. The meaning and difference of Override and Overload

Override means "overwriting", which is the subclass's rewrite of the parent class Redefinition of the same method in

Overload means "overloading", that is, defining a new method with the same name as the defined method but a different signature

18. The difference between interface and abstract class

Interface is a convention, and the class that implements the interface must follow this convention; abstract class is essentially a class, and the cost of using abstract class is greater than that of interface. The comparison between interfaces and abstract classes is as follows:

Abstract classes can contain attributes, methods (including abstract methods and methods with specific implementations), and constants; interfaces can only contain constants and method declarations.

Methods and member variables in abstract classes can define visibility (such as public, private, etc.); while methods in interfaces can only be public (the default is public).

A subclass can only have one parent class (concrete class or abstract class); an interface can inherit multiple interfaces, and a class can also implement multiple interfaces.

When a subclass implements an abstract method in the parent class, the visibility can be greater than or equal to that in the parent class; while the visibility of the interface method in the interface implementation class can only be the same as that in the interface (public).

19. The difference between static inner classes and non-static inner classes

Static inner classes will not hold references to outer classes, while non-static inner classes will implicitly Holds a reference to the enclosing class.

To learn more about internal classes, please click on the internal classes of Java core technology

20. The implementation principle of polymorphism in Java

The so-called polymorphism State refers to the parent class reference pointing to the child class object. When calling a method, the implementation of the child class will be called instead of the implementation of the parent class. The key to the implementation of polymorphism lies in "dynamic binding". For a detailed introduction, please click on the internal implementation mechanism of Java dynamic binding

21. Briefly describe the two methods of creating new threads in Java

Inherit the Thread class (assuming subclasses for MyThread), and rewrite the run() method, then create a new MyThread object and call start() on it to start a new thread.

Implement the Runnable interface (assuming the implementation class is MyRunnable), then pass the MyRunnable object as a parameter to the Thread constructor, and call the start() method on the obtained Thread object.

22. Briefly describe the method of thread synchronization in Java

volatile: Java Memory Model ensures that writing to the same volatile variable happens before reading it;

synchronized: You can lock a code block or a method. The "locked" place is called the critical section. The thread entering the critical section will obtain the monitor of the object, so that other attempts to enter the critical section The thread in the area will be blocked because it cannot obtain the monitor. A thread that is blocked waiting for another thread to release a monitor cannot be interrupted.

ReentrantLock: The thread trying to acquire the lock can be interrupted and the timeout parameter can be set.

For a more detailed introduction, please click on Multithreading, the core technical point of Java

23. Briefly describe the types of granular locks in Java

In Java, classes, objects, methods or code blocks can be locked. For a more detailed introduction, please click on Java Core Technology Points Multithreading

24. Give a solution to the "producer-consumer" problem

Use blocking queue:

public class BlockingQueueTest { private int size = 20; private ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(size); public static void main(String[] args) { BlockingQueueTest test = new BlockingQueueTest(); Producer producer = test.new Producer(); Consumer consumer = test.new Consumer(); producer.start(); consumer.start(); } class Consumer extends Thread{ @Override public void run() { while(true){ try { //从阻塞队列中取出一个元素 queue.take(); System.out.println("队列剩余" + queue.size() + "个元素"); } catch (InterruptedException e) { } } } } class Producer extends Thread{ @Override public void run() { while (true) { try { //向阻塞队列中插入一个元素 queue.put(1); System.out.println("队列剩余空间:" + (size - queue.size())); } catch (InterruptedException e) { } } } } }
Copy after login

25. The design concept and function of ThreadLocal

The function of ThreadLocal is to provide local variables within the thread, which can ensure that the ThreadLocal variables in each thread are independent when accessed in a multi-thread environment. In other words, each thread's ThreadLocal variable is dedicated to itself and cannot be accessed by other threads. ThreadLocal is most commonly used in the following scenario: there are concurrent accesses to non-thread-safe objects in a multi-threaded environment, and the object does not need to be shared between threads, but we do not want to lock. In this case, ThreadLocal can be used to make each thread maintain There is a copy of this object.

For an analysis of the implementation principles of ThreadLocal, please click for an in-depth analysis of ThreadLocal

26. The overall architecture of the concurrent package

Summary of Java interview knowledge points

27. ArrayBlockingQueue, CountDownLatch The role of the class

CountDownLatch: Allows a set of threads to wait until the counter reaches 0. Applicable scenario: When one or more threads need to wait for a specified number of events to occur before continuing execution.

ArrayBlockingQueue: A blocking queue based on array implementation, which needs to specify the capacity when it is constructed. The current thread is blocked when trying to add elements to a full queue or remove elements from an empty queue. Through the blocking queue, we can work in the following mode: the worker thread can periodically put the intermediate results into the blocking queue, and other threads can take out the intermediate results and perform further operations. If the worker thread executes slowly (before it has time to insert elements into the queue), other threads that take elements from the queue will wait for it (trying to take elements from the empty queue and block); if the worker thread executes quickly ( If you try to insert an element into a full queue), it will wait for other threads to remove the element before continuing.

28. The difference between wait() and sleep()

wait(): Instance method defined in the Object class. Calling the wait method on the specified object will put the current thread into a waiting state (provided that the current thread holds the monitor of the object). At this time, the current thread will release the monitor of the corresponding object, so that other threads will have the opportunity to obtain the object. monitor. When other threads obtain the monitor of this object and perform the required operations, they can call the notify method to wake up the thread that previously entered the waiting state.

sleep(): Static method in the Thread class, which is used to put the current thread into sleep state so that other threads have the opportunity to execute. A thread that goes to sleep does not release the lock it holds.

29. Usage and advantages of thread pool

Advantages: Realize the reuse of threads and avoid the overhead of repeatedly creating and destroying threads; using threads The pool's unified management of threads can reduce the number of concurrent threads. Too many threads tend to waste too much time on thread context switching and thread synchronization.

Usage: We can call a constructor method of ThreadPoolExecutor to create a thread pool ourselves. But usually we can use the static factory method provided to us by the Executors class to create a thread pool object more conveniently. After creating the thread pool object, we can call the submit method to submit the task to the thread pool for execution; after the thread pool is used, we must remember to call the shutdown method to close it.

For a detailed introduction to the thread pool and analysis of the implementation principles, please click on In-depth Understanding of Java's Thread Pool

30. Comparison of the efficiency of for-each and conventional for loops

Regarding this question, let’s look directly at the answer given to us by "Effective Java":

for-each能够让代码更加清晰,并且减少了出错的机会。下面的惯用代码适用于集合与数组类型: for (Element e : elements) { doSomething(e); }使用for-each循环与常规的for循环相比,并不存在性能损失,即使对数组进行迭代也是如此。实际上,在有些场合下它还能带来微小的性能提升,因为它只计算一次数组索引的上限。
Copy after login

31. Briefly describe the difference between Java IO and NIO

Java IO is stream-oriented. This means that we need to read one or more bytes from the stream at a time until all bytes have been read; NIO is buffer-oriented, which means that the data will be read into a buffer and then the buffer The data in the area is processed accordingly.

Java IO is blocking IO, while NIO is non-blocking IO.

There is something called a selector in Java NIO, which allows you to register multiple channels to a selector, and then use a thread to monitor these channels: If there is something in these channels When the channel is ready to start reading or writing operations, start reading and writing the corresponding channel. While waiting for a channel to become readable/writable, the thread requesting read and write operations on the channel can do other things.

For further explanation, please click Java NIO and IO

32. The role and principle of reflection

The role of reflection is generally speaking, it is runtime Obtain various definition information of the class, such as which properties and methods are defined. The principle is to obtain various information about a class through its class object.

For a detailed introduction, please refer to Reflection, the core technical point of Java

33. Generic mechanism in Java

For a detailed introduction to the generic mechanism, please Directly poke at the core technical points of Java: Generics

34. New features of Java 7 and Java 8

Here are two very good summaries: Java 7 New features New features of Java 8

35. Common design patterns

The so-called "design patterns" are just some commonly used software design techniques in object-oriented programming, and After practical testing, these design techniques can solve some needs in their respective scenarios, so they have become widely circulated "design patterns" today. In other words, it was officially because some thorny problems occurred in certain scenarios that the corresponding design patterns were born. Having made this clear, when we learn a certain design pattern, we must fully understand the background of its creation and the main contradictions it solves.

Commonly used design patterns can be divided into the following three categories:

Creative patterns: including factory patterns (which can be further divided into simple factory patterns, factory method patterns, and abstract factory patterns), Builder pattern, singleton pattern.

Structural mode: including adapter mode, bridge mode, decoration mode, appearance mode, flyweight mode, and proxy mode.

Behavioral mode: including command mode, mediator mode, observer mode, state mode, and strategy mode.

For a detailed introduction to each mode, please refer to the illustrated design pattern

36. Basic usage of JNI

About JNI, here is a good article: JNI in Android

37. Definition, application scenarios and principles of dynamic proxy

Regarding dynamic proxy, please directly refer to Dynamic Proxy of Java Core Technology Points

38. The basic concept and use of annotations

Annotations can be regarded as "enhanced versions of comments", which can explain some things to the compiler and virtual machine.

Annotations are codes that describe Java code. They can be parsed by the compiler, and annotation processing tools can also parse annotations at runtime. The annotation itself is "passive" information, and it is meaningful only if it is actively parsed.

In addition to passing information to the compiler/virtual machine, we can also use annotations to generate some "templated" code.

Are these enough? Of course not enough. The above lists common questions about Java in interviews, and most of them are also the core technical points of the Java technology system. The series of questions raised by these questions point out a way for us to improve our own knowledge system. We must do The best thing is to keep going along this path:)

For more Java interview knowledge points summary and related articles, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!