Common java interview questions

  • 2020-05-17 05:24:00
  • OfStack

This article is mainly for you to sort out Java common interview questions, for your reference, the specific content is as follows

1. Differences between sleep and wait in Java

The two methods come from different classes: sleep from Thread, and wait from Object.
sleep is the static class method of Thread, and whoever calls it goes to sleep. Even if b's sleep method is called in a thread, a actually goes to sleep. To put b thread to sleep, sleep is called in b code.

(2) lock: the most important is that the sleep method does not release the lock, while the wait method releases the lock, so that other threads can use the synchronous control block or method.

sleep does not transfer system resources; wait is to enter the thread waiting pool to wait, transfer system resources, other threads can occupy CPU. 1 general wait does not have a time limit, because if the wait thread runs out of resources, it is useless to come out again. You have to wait for other threads to call notify/notifyAll to wake up all the threads in the waiting pool before entering the ready queue waiting for OS to allocate system resources. sleep(milliseconds) can be timed to automatically wake it up, and can only call interrupt() to force an interruption if the time is not up.

Thread.sleep (0) is used to "trigger an immediate re-run of the CPU race by the operating system".

Scope of use: wait, notify and notifyAll can only be used in sync control methods or sync control blocks, while sleep can be used anywhere.


 synchronized(x){ 
  x.notify() 
  // or wait() 
 }

2. Differences between HashMap and HashTable in Java

Historical reasons: Hashtable is given to the obsolete Dictonary class, and HashMap is an implementation of the Map interface introduced by Java1.2

HashMap allows empty key-value pairs, while HashTable does not

HashTable is synchronous, while HashMap is asynchronous, which is more efficient than HashTable

3. What is the difference between throw and throws

throw represents an action that throws an exception. throws represents one state, which means that the method may have an exception thrown
throw is used in method implementations, while throws is used in method declarations
throw can only be used to throw one exception, while throws can throw multiple exceptions

4. Difference between memory overflow and memory leak

Out of memory out of memory refers to the application for memory, there is not enough memory space for its use, out of memory; For example, if you apply for one integer, but give it the number that long can save, that is memory overflow.

Memory leak memory leak, refers to the program after the application for memory, has been unable to release the memory space, a memory leak can be ignored, but the memory leak accumulation consequences are very serious, no matter how much memory, sooner or later will be occupied.

memory leak will eventually lead to out of memory!

A memory leak is when you ask for more memory than the system can give you, the system can't meet the requirements, and an overflow occurs.

A memory leak is when you ask the system to allocate memory for use (new), but then don't return it (delete). As a result, you can no longer access the memory you requested (perhaps you lost its address), and the system can no longer allocate it to the program you want. A plate can only hold 4 fruits in all kinds of ways. You put 5 into it, and then you fall down on the ground and can't eat any more. This is an overflow! For example, when the stack is full and then do the stack must produce space overflow, called overflows, stack empty and then do the stack also produce space overflow, called underflows. Is the memory allocated is not enough to put down the data item sequence, called memory overflow.

Memory leaks can be classified by the way they occur into four categories:

Frequent memory leaks. The code that has a memory leak is executed multiple times, each time leading to a memory leak.
(2) accidental memory leakage. Memory leaks occur in code only under certain circumstances or during certain operations. Recurrent and incidental are relative. For certain circumstances, sporadic may become recurrent. So the test environment and test methods are critical to detecting memory leaks.
1 primary memory leak. The code that has a memory leak will only be executed once, or because of an algorithmic flaw, there will always be one and only one memory leak. For example, memory is allocated in the constructor of a class, but not freed in the destructor, so a memory leak occurs only once.
Implicit memory leak. The program allocates memory as it runs, but it does not release memory until it is finished. Strictly speaking, there is no memory leak because the final program releases all the requested memory. However, for a single server program, it may take days, weeks, or even months to run, and failure to release memory in time may eventually cause the system to run out of memory. Therefore, we call this type of memory leak an implicit memory leak.

From the point of view of the user using the program, the memory leak itself does not cause any harm. As a user like 1, the memory leak is not felt at all. The real danger is the accumulation of memory leaks, which eventually deplete the system's memory. From this perspective, a primary memory leak is not harmful because it does not accumulate, whereas an implicit memory leak is very harmful because it is harder to detect than a frequent or occasional memory leak.

5. Differences between String, StringBuffer and StringBuilder

Variable and immutable
The String class USES a character array to hold the string, as shown below, and because of the "final" modifier, you know that the string object is immutable.

private final char value [];

StringBuilder and StringBuffer both inherit from the AbstractStringBuilder class, and AbstractStringBuilder also USES character arrays to hold strings, as shown below. Both objects are mutable.

char [] value;

Whether multithreading security

The objects in String are immutable, which means they can be considered constants, which is thread safe.

AbstractStringBuilder is the common parent of StringBuilder and StringBuffer. It defines the basic operations of some strings, such as expandCapacity, append, insert, indexOf and other public methods.

StringBuffer is thread-safe because it has a synchronous lock on the method or on the method being called. Look at the following source code:


public synchronized StringBuffer reverse() { 
  super.reverse(); 
  return this; 
 } 
 
 public int indexOf(String str) { 
  return indexOf(str, 0);  // There are  public synchronized int indexOf(String str, int fromIndex)  methods  
 } 

StringBuilder does not synchronize methods, so it is not thread-safe.

StringBuilder and StringBuffer have something in common

StringBuilder and StringBuffer have a common parent, AbstractStringBuilder(abstract class).

One of the differences between an abstract class and an interface is that you can define the public methods of some subclasses in an abstract class. Subclasses only need to add new functions and do not need to repeat the existing methods. Interfaces are just declarations of methods and definitions of constants.

StringBuilder, StringBuffer methods all call public methods in AbstractStringBuilder, such as super.append (...) . It's just that StringBuffer adds the synchronized keyword to the method to synchronize.

Finally, if the program is not multithreaded, StringBuilder is more efficient than StringBuffer.

6. The difference between an array and a linked list

Both of them belong to one data structure

From the logical structure:
The array must be defined in advance a fixed length (the number of elements), can not adapt to the dynamic increase and decrease of data. When the data increases, the number of elements may exceed the original definition. When the data is reduced, resulting in memory waste; Arrays can be accessed directly by subscripts.
(2) the linked list of dynamic storage allocation, can adapt to the dynamic increase and decrease of data, and can easily insert, delete data items. (it is very tedious to move other data items when inserting or deleting data items from an array.) the linked list must find the next element according to the next pointer.

From the perspective of memory storage:
(static) array from the stack allocation space, convenient for programmers quickly, but small degrees of freedom.
(2) the linked list from the heap allocation space, freedom, but the application management is more troublesome.
As you can see from the above comparison, if you need to access data quickly with little or no insertion or deletion of elements, you should use arrays. In contrast, if you need to insert and delete elements frequently, you need to use a linked list data structure.

7. Difference between ArrayList and LinkedList

ArrayList is a data structure based on dynamic array and LinkedList is a data structure based on linked lists.
For random access to get and set, ArrayList feels better than LinkedList, because LinkedList moves the pointer.
For new and delete operations add and remove, LinedList has the advantage because ArrayList moves data.


Related articles: