Common Java interview questions (with answers)

(*-*)浩
Release: 2019-11-26 15:02:51
Original
2501 people have browsed it

Common Java interview questions (with answers)

How to implement a queue using an array?

When using an array to implement a queue, we must pay attention to the overflow phenomenon. In this case, we can use the method of looping the array to solve it, that is, connecting the ends of the array. Use the front pointer to point to the first position of the queue and the tail pointer to point to the last position of the queue. (Recommended study: java common interview questions)

When an internal class accesses a local variable, why must the variable be modified with final?

Because the life cycle is different. Local variables will be destroyed after the method ends, but the inner class object will not necessarily be destroyed. This will cause the inner class to reference a variable that does not exist.

So the compiler will generate a copy of the local variable in the inner class. The life cycle of this copy is the same as the inner class object, so the above problems will not occur.

But this leads to the problem that one of the variables is modified and the values ​​of the two variables may be different. In order to solve this problem, the compiler requires that local variables need to be final modified to ensure that the two variables have the same value.

After JDK8, the compiler does not require that local variables accessed by inner classes must be final modified, but the value of local variables cannot be modified (either in a method or in an inner class), otherwise a compilation error will be reported. Using javap to view the compiled bytecode, you can find that the compiler has added final.

long s = 499999999 * 499999999 In the above code, what is the value of s?

According to the calculation result of the code, the value of s should be -1371654655. This is because the calculation of the right-hand value in Java defaults to the int type.

Can non-static inner classes define static methods?

public class OuterClass{
    private static float f = 1.0f;

    class InnerClass{
        public static float func(){return f;}
    }
}
Copy after login

The above code will cause a compilation error, because only static inner classes can define static methods.

What is the difference between Lock and Synchronized?

1. 使用方法的区别
- **Synchronized**:在需要同步的对象中加入此控制,`synchronized`可以加在方法上,也可以加在特定代码块中,括号中表示需要锁的对象。
- **Lock**:需要显示指定起始位置和终止位置。一般使用`ReentrantLock`类做为锁,多个线程中必须要使用一个`ReentrantLock`类做为对象才能保证锁的生效。且在加锁和解锁处需要通过`lock()`和`unlock()`显示指出。所以一般会在`finally`块中写`unlock()`以防死锁。
2. 性能的区别
`synchronized`是托管给JVM执行的,而`lock`是java写的控制锁的代码。在Java1.5中,`synchronize`是性能低效的。因为这是一个重量级操作,需要调用操作接口,导致有可能加锁消耗的系统时间比加锁以外的操作还多。相比之下使用Java提供的Lock对象,性能更高一些。但是到了Java1.6,发生了变化。`synchronize`在语义上很清晰,可以进行很多优化,有适应自旋,锁消除,锁粗化,轻量级锁,偏向锁等等。导致在Java1.6上`synchronize`的性能并不比Lock差。
  - **Synchronized**:采用的是CPU悲观锁机制,即线程获得的是独占锁。独占锁意味着 **其他线程只能依靠阻塞来等待线程释放锁**。而在CPU转换线程阻塞时会引起线程上下文切换,当有很多线程竞争锁的时候,会引起CPU频繁的上下文切换导致效率很低。
  - **Lock**:用的是乐观锁方式。所谓乐观锁就是,**每次不加锁而是假设没有冲突而去完成某项操作,如果因为冲突失败就重试,直到成功为止**。乐观锁实现的机制就是`CAS`操作。我们可以进一步研究`ReentrantLock`的源代码,会发现其中比较重要的获得锁的一个方法是`compareAndSetState`。这里其实就是调用的CPU提供的特殊指令。
3. `ReentrantLock`:具有更好的可伸缩性:比如时间锁等候、可中断锁等候、无块结构锁、多个条件变量或者锁投票。
Copy after login

How do float variables compare to 0?

There are folat types and double types. The possibility of these decimal types directly equaling 0 when approaching 0 is very small. Generally, they approach 0 infinitely, so = cannot be used. = to judge. It should be judged by |x-0|

//用程序表示就是

fabs(x) < 0.00001f
Copy after login

How to create a new non-static inner class?

The inner class must be Outer.Inner a when declared, just like int a. As for the static inner class and the non-static inner class new, there is a difference:

Outer.Inner a = new Outer().new Inner() (non-static, there must be an Outer object before the new inner class can be created)

Outer.Inner a = new Outer.Inner()(static inner class)

Java identifier naming rules

Can contain: letters, numbers, $, _ (underscore), cannot start with a number, and cannot be Java keywords or reserved words.

What design patterns do you know used in JDK?

Decoration mode: java.io

Single case mode: Runtime class

Simple factory mode: Integer.valueOf method

Flyweight mode :String constant pool, Integer.valueOf(int i), Character.valueOf(char c)

Iterator mode: Iterator

Chain of responsibility mode: ClassLoader’s parent delegation model

Interpreter mode: Regular expression java.util.regex.Pattern

How ConcurrentHashMap ensures thread safety

JDK 1.7 and before:

ConcurrentHashMap allows multiple modification operations to be performed concurrently. The key is the use of lock separation technology. It uses multiple locks to control modifications to different parts of the hash table. ConcurrentHashMap uses segments internally to represent these different parts. Each segment is actually a small hash table, and they have their own locks. Multiple modification operations can occur concurrently as long as they occur on different segments.

JDK 1.8:

Although Segment is retained, its attributes have been simplified just to be compatible with older versions.

Use CAS algorithm when inserting: unsafe.compareAndSwapInt(this, valueOffset, expect, update). CAS (Compare And Swap) means that if the value contained in the valueOffset position is the same as the expect value, then update the value of the valueOffset position to update and return true, otherwise it will not update and return false. The key or value is not allowed to be null when inserting

It is similar to Java8's HashMap. The bottom layer still consists of an "array" linked list red-black tree;

The bottom structure stores TreeBin objects, and Not a TreeNode object;

CAS is a well-known lock-free algorithm, so does ConcurrentHashMap have no locks? Of course not, when the hash value is the same as the head node of the linked list, it will still be synchronized and locked, and the linked list will be locked.

The difference between Thread.sleep() & Thread.yield()&Thread.wait()

Both sleep() and yield() will release the CPU.

sleep() can give low-priority threads a chance to execute. Of course, it can also give threads of the same priority and high-priority a chance to execute; yield() can only give threads of the same priority a chance to execute. There is a chance of execution.

Thread.sleep and Thread.yield() will not cause the lock behavior to change. If the current thread owns the lock, then Thread.sleep will not let the thread release the lock. If it helps you remember, you can simply think that the lock-related methods are defined in the Object class, so calling Thread.sleep will not affect the lock-related behavior.

Thread.sleep and Object.wait will suspend the current thread. For CPU resources, no matter which thread is suspended, it means that it no longer requires CPU execution time. The OS will allocate execution time to other threads. The difference is that after calling wait, other threads need to execute notify/notifyAll to regain the CPU execution time.

What is the difference between arraylist and linkedlist?

Both ArrayList and LinkedList implement the List interface, but there are some differences between them.

(1) ArrayList is a data structure based on an index supported by Array, so it provides random access to elements

(2) Compared with ArrayList, inserting, Adding and deleting an element will be faster

(3) LinkedList consumes more memory than ArrayList because each node in LinkedList stores the reference of the previous and following nodes

The above is the detailed content of Common Java interview questions (with answers). For more information, please follow other related articles on 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template