国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
#1. What are the three basic characteristics of object-oriented?
2. What is the difference between access modifiers public, private, protected, and not written?
3. Can the following two code blocks be compiled and executed normally?
4. Basic inspection, point out The output result of the next question
5 , use the most efficient method to calculate 2 times 8?
6、&和&&的區(qū)別?
7、String 是 Java 基本數(shù)據(jù)類型嗎?
8、String 類可以繼承嗎?
9、String和StringBuilder、StringBuffer的區(qū)別?
10、String s = new String("xyz") 創(chuàng)建了幾個(gè)字符串對(duì)象?
11、String s = "xyz" 和 String s = new String("xyz") 區(qū)別?
12、== 和 equals 的區(qū)別是什么?
13、兩個(gè)對(duì)象的 hashCode() 相同,則 equals() 也一定為 true,對(duì)嗎?
14、什么是反射
15、深拷貝和淺拷貝區(qū)別是什么?
16、并發(fā)和并行有什么區(qū)別?
17、構(gòu)造器是否可被 重寫?
18、當(dāng)一個(gè)對(duì)象被當(dāng)作參數(shù)傳遞到一個(gè)方法后,此方法可改變這個(gè)對(duì)象的屬性,并可返回變化后的結(jié)果,那么這里到底是值傳遞還是引用傳遞?
19、Java 靜態(tài)變量和成員變量的區(qū)別。
20、是否可以從一個(gè)靜態(tài)(static)方法內(nèi)部發(fā)出對(duì)非靜態(tài)(non-static)方法的調(diào)用?
21、初始化考察,請指出下面程序的運(yùn)行結(jié)果。
22、重載(Overload)和重寫(Override)的區(qū)別?
23、為什么不能根據(jù)返回類型來區(qū)分重載?
24、抽象類(abstract class)和接口(interface)有什么區(qū)別?
25、Error 和 Exception 有什么區(qū)別?
26、Java 中的 final 關(guān)鍵字有哪些用法?
27、闡述 final、finally、finalize 的區(qū)別。
30、try、catch、finally 考察3,請指出下面程序的運(yùn)行結(jié)果。
31. What are the new features after JDK1.8?
32. The difference between wait() and sleep() methods
33. What is the difference between the sleep() method and the yield() method of a thread?
34. What is the join() method of thread used for?
35. How many ways are there to write multi-threaded programs?
36. The difference between Thread calling start() method and calling run() method
37. Thread state flow
38、synchronized 和 Lock 的區(qū)別
39、synchronized 各種加鎖場景的作用范圍
40、如何檢測死鎖?
41、怎么預(yù)防死鎖?
42. Why use thread pool? Isn’t it comfortable to create a new thread directly?
43. What are the core attributes of the thread pool?
44. Let’s talk about the operation process of the thread pool.
#45. What are the rejection strategies for the thread pool?
46. What are the differences between List, Set and Map?
47. The difference between ArrayList and LinkedList.
48. The difference between ArrayList and Vector.
49. Introduce the underlying data structure of HashMap
" >#50. Why should it be changed to "array, linked list, red-black tree"?
51. When should you use a linked list? When to use red-black trees?
52. What is the default initial capacity of HashMap? Is there any limit to the capacity of HashMap?
53. What is the insertion process of HashMap?
54. What is the expansion (resize) process of HashMap?
55. In addition to HashMap, what other Maps have been used, and how to choose when using them?
56. What is the difference between HashMap and Hashtable?
57. Java memory structure (runtime data area)
58、什么是雙親委派模型?
59、Java虛擬機(jī)中有哪些類加載器?
60、類加載的過程
61、介紹下垃圾收集機(jī)制(在什么時(shí)候,對(duì)什么,做了什么)?
62、GC Root有哪些?
63. What are the garbage collection algorithms and their respective characteristics?
Finally
Home Java JavaInterview questions [Hematemesis compilation] 2023 Java basic high-frequency interview questions and answers (Collection)

[Hematemesis compilation] 2023 Java basic high-frequency interview questions and answers (Collection)

Jul 08, 2022 am 11:00 AM
java interview questions

This article summarizes some 2023 selected basic Java high-frequency interview questions worth collecting (with answers). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

[Hematemesis compilation] 2023 Java basic high-frequency interview questions and answers (Collection)

#1. What are the three basic characteristics of object-oriented?

The three basic characteristics of object-oriented are: encapsulation, inheritance and polymorphism.

Inheritance: A method that allows an object of a certain type to obtain the properties of an object of another type. Inheritance means that a subclass inherits the characteristics and behaviors of the parent class, so that the subclass object (instance) has the instance fields and methods of the parent class, or the subclass inherits methods from the parent class, so that the subclass has the same behavior as the parent class. (Recommended tutorial: java introductory tutorial)

Encapsulation: Hide the properties and implementation details of some objects, and access to data can only be through externally exposed interfaces. In this way, objects provide varying levels of protection for internal data to prevent unrelated parts of the program from accidentally changing or incorrectly using the private parts of the object.

Polymorphism: For the same behavior, different subclass objects have different manifestations. There are three conditions for the existence of polymorphism: 1) inheritance; 2) overwriting; 3) parent class reference points to subclass object.

A simple example: In League of Legends, we press the Q key:

  • For Yasuo, it is Steel Flash
  • For Teemo, It’s the Blinding Dart
  • For Juggernaut, it’s Alpha Strike

The same event will produce different results when it happens to different objects.

Let me give you another simple example to help you understand. This example may not be completely accurate, but I think it is helpful for understanding.

public?class?Animal?{?//?動(dòng)物
????public?void?sleep()?{
????????System.out.println("躺著睡");
????}
}
class?Horse?extends?Animal?{?//?馬?是一種動(dòng)物
????public?void?sleep()?{
????????System.out.println("站著睡");
????}
}
class?Cat?extends?Animal?{?//?貓?是一種動(dòng)物
????private?int?age;
????public?int?getAge()?{
????????return?age?+?1;
????}
????@Override
????public?void?sleep()?{
????????System.out.println("四腳朝天的睡");
????}
}

In this example:

Both House and Cat are Animal, so they both inherit Animal and also inherit the sleep behavior from Animal.

But for the sleep behavior, House and Cat have been rewritten and have different expressions (implementations). This is called polymorphism.

In Cat, the age attribute is defined as private and cannot be directly accessed by the outside world. The only way to obtain Cat's age information is through the getAge method, thus hiding the age attribute from the outside. This is called encapsulation. Of course, age here is just an example, and it may be a much more complex object in actual use.

2. What is the difference between access modifiers public, private, protected, and not written?

3. Can the following two code blocks be compiled and executed normally?

//?代碼塊1
short?s1?=?1;?s1?=?s1?+?1;
//?代碼塊2
short?s1?=?1;?s1?+=?1;

Code block 1 compiles and reports an error. The reason for the error is: Incompatible type: Conversion from int to short may cause loss.

Code block 2 compiles and executes normally.

We compile code block 2. The bytecode is as follows:

public?class?com.joonwhee.open.demo.Convert?{
??public?com.joonwhee.open.demo.Convert();
????Code:
???????0:?aload_0
???????1:?invokespecial?#1?//?Method?java/lang/Object."<init>":()V
???????4:?return

??public?static?void?main(java.lang.String[]);
????Code:
???????0:?iconst_1?//?將int類型值1入(操作數(shù))棧
???????1:?istore_1?//?將棧頂int類型值保存到局部變量1中
???????2:?iload_1?//?從局部變量1中裝載int類型值入棧
???????3:?iconst_1?//?將int類型值1入棧
???????4:?iadd?//?將棧頂兩int類型數(shù)相加,結(jié)果入棧
???????5:?i2s?//?將棧頂int類型值截?cái)喑蓅hort類型值,后帶符號(hào)擴(kuò)展成int類型值入棧。
???????6:?istore_1?//?將棧頂int類型值保存到局部變量1中
???????7:?return
}

You can see that the bytecode contains the i2s instruction, which is used to convert int to short. i2s is Abbreviation of int to short.

In fact, s1 = 1 is equivalent to s1 = (short)(s1 1). If you are interested, you can compile the bytecode of these two lines of code yourself. You will find that it is It’s the same.

The basic Java questions that we said started to change again???

4. Basic inspection, point out The output result of the next question

public?static?void?main(String[]?args)?{
????Integer?a?=?128,?b?=?128,?c?=?127,?d?=?127;
????System.out.println(a?==?b);
????System.out.println(c?==?d);
}

The answer is: false, true.

Executing Integer a = 128 is equivalent to executing: Integer a = Integer.valueOf(128), basic type The process of automatically converting to a packaging class is called autoboxing.

public?static?Integer?valueOf(int?i)?{
????if?(i?>=?IntegerCache.low?&&?i?<= IntegerCache.high)
        return IntegerCache.cache[i + (-IntegerCache.low)];
    return new Integer(i);
}

IntegerCache is introduced in Integer to cache a certain range of values. By default, IntegerCache range is: -128~127.

127 in this question hits the IntegerCache, so c and d are the same object, while 128 does not hit, so a and b are different objects.

But this cache range can be modified, maybe Some people don’t know. You can modify the upper limit value through the JVM startup parameter: -XX:AutoBoxCacheMax=, as shown in the figure below:

5 , use the most efficient method to calculate 2 times 8?

2 << 3.

Advanced: Under normal circumstances, bit operations can be considered to have the highest performance . However, in fact, compilers are now "very smart", and many instruction compilers can do optimizations by themselves. Therefore, in actual practice, we do not need to pursue practical bit operations. This will not only lead to poor code readability, Moreover, some clever optimizations will mislead the compiler, preventing the compiler from performing better optimizations.

This may be the so-called "pig teammate".

6、&和&&的區(qū)別?

&&:邏輯與運(yùn)算符。當(dāng)運(yùn)算符左右兩邊的表達(dá)式都為 true,才返回 true。同時(shí)具有短路性,如果第一個(gè)表達(dá)式為 false,則直接返回 false。

&:邏輯與運(yùn)算符、按位與運(yùn)算符。

按位與運(yùn)算符:用于二進(jìn)制的計(jì)算,只有對(duì)應(yīng)的兩個(gè)二進(jìn)位均為1時(shí),結(jié)果位才為1 ,否則為0。

邏輯與運(yùn)算符:& 在用于邏輯與時(shí),和 && 的區(qū)別是不具有短路性。所在通常使用邏輯與運(yùn)算符都會(huì)使用 &&,而 & 更多的適用于位運(yùn)算。

7、String 是 Java 基本數(shù)據(jù)類型嗎?

答:不是。Java 中的基本數(shù)據(jù)類型只有8個(gè):byte、short、int、long、float、double、char、boolean;除了基本類型(primitive type),剩下的都是引用類型(reference type)。

基本數(shù)據(jù)類型:數(shù)據(jù)直接存儲(chǔ)在棧上

引用數(shù)據(jù)類型區(qū)別:數(shù)據(jù)存儲(chǔ)在堆上,棧上只存儲(chǔ)引用地址

8、String 類可以繼承嗎?

不行。String 類使用 final 修飾,無法被繼承。

9、String和StringBuilder、StringBuffer的區(qū)別?

String:String 的值被創(chuàng)建后不能修改,任何對(duì) String 的修改都會(huì)引發(fā)新的 String 對(duì)象的生成。

StringBuffer:跟 String 類似,但是值可以被修改,使用 synchronized 來保證線程安全。

StringBuilder:StringBuffer 的非線程安全版本,沒有使用 synchronized,具有更高的性能,推薦優(yōu)先使用。

10、String s = new String("xyz") 創(chuàng)建了幾個(gè)字符串對(duì)象?

一個(gè)或兩個(gè)。如果字符串常量池已經(jīng)有“xyz”,則是一個(gè);否則,兩個(gè)。

當(dāng)字符創(chuàng)常量池沒有 “xyz”,此時(shí)會(huì)創(chuàng)建如下兩個(gè)對(duì)象:

一個(gè)是字符串字面量 "xyz" 所對(duì)應(yīng)的、駐留(intern)在一個(gè)全局共享的字符串常量池中的實(shí)例,此時(shí)該實(shí)例也是在堆中,字符串常量池只放引用。

另一個(gè)是通過 new String() 創(chuàng)建并初始化的,內(nèi)容與"xyz"相同的實(shí)例,也是在堆中。

11、String s = "xyz" 和 String s = new String("xyz") 區(qū)別?

兩個(gè)語句都會(huì)先去字符串常量池中檢查是否已經(jīng)存在 “xyz”,如果有則直接使用,如果沒有則會(huì)在常量池中創(chuàng)建 “xyz” 對(duì)象。

另外,String s = new String("xyz") 還會(huì)通過 new String() 在堆里創(chuàng)建一個(gè)內(nèi)容與 "xyz" 相同的對(duì)象實(shí)例。

所以前者其實(shí)理解為被后者的所包含。

12、== 和 equals 的區(qū)別是什么?

==:運(yùn)算符,用于比較基礎(chǔ)類型變量和引用類型變量。

對(duì)于基礎(chǔ)類型變量,比較的變量保存的值是否相同,類型不一定要相同。

short s1 = 1; long l1 = 1;
// 結(jié)果:true。類型不同,但是值相同
System.out.println(s1 == l1);

對(duì)于引用類型變量,比較的是兩個(gè)對(duì)象的地址是否相同。

Integer i1 = new Integer(1);
Integer i2 = new Integer(1);
// 結(jié)果:false。通過new創(chuàng)建,在內(nèi)存中指向兩個(gè)不同的對(duì)象
System.out.println(i1 == i2);

equals:Object 類中定義的方法,通常用于比較兩個(gè)對(duì)象的值是否相等。

equals 在 Object 方法中其實(shí)等同于 ==,但是在實(shí)際的使用中,equals 通常被重寫用于比較兩個(gè)對(duì)象的值是否相同。

Integer i1 = new Integer(1);
Integer i2 = new Integer(1);
// 結(jié)果:true。兩個(gè)不同的對(duì)象,但是具有相同的值
System.out.println(i1.equals(i2));

// Integer的equals重寫方法
public boolean equals(Object obj) {
    if (obj instanceof Integer) {
        // 比較對(duì)象中保存的值是否相同
        return value == ((Integer)obj).intValue();
    }
    return false;
}

13、兩個(gè)對(duì)象的 hashCode() 相同,則 equals() 也一定為 true,對(duì)嗎?

不對(duì)。hashCode() 和 equals() 之間的關(guān)系如下:

當(dāng)有 a.equals(b) == true 時(shí),則 a.hashCode() == b.hashCode() 必然成立,

反過來,當(dāng) a.hashCode() == b.hashCode() 時(shí),a.equals(b) 不一定為 true。

14、什么是反射

反射是指在運(yùn)行狀態(tài)中,對(duì)于任意一個(gè)類都能夠知道這個(gè)類所有的屬性和方法;并且對(duì)于任意一個(gè)對(duì)象,都能夠調(diào)用它的任意一個(gè)方法;這種動(dòng)態(tài)獲取信息以及動(dòng)態(tài)調(diào)用對(duì)象方法的功能稱為反射機(jī)制。

15、深拷貝和淺拷貝區(qū)別是什么?

數(shù)據(jù)分為基本數(shù)據(jù)類型和引用數(shù)據(jù)類型。基本數(shù)據(jù)類型:數(shù)據(jù)直接存儲(chǔ)在棧中;引用數(shù)據(jù)類型:存儲(chǔ)在棧中的是對(duì)象的引用地址,真實(shí)的對(duì)象數(shù)據(jù)存放在堆內(nèi)存里。

淺拷貝:對(duì)于基礎(chǔ)數(shù)據(jù)類型:直接復(fù)制數(shù)據(jù)值;對(duì)于引用數(shù)據(jù)類型:只是復(fù)制了對(duì)象的引用地址,新舊對(duì)象指向同一個(gè)內(nèi)存地址,修改其中一個(gè)對(duì)象的值,另一個(gè)對(duì)象的值隨之改變。

深拷貝:對(duì)于基礎(chǔ)數(shù)據(jù)類型:直接復(fù)制數(shù)據(jù)值;對(duì)于引用數(shù)據(jù)類型:開辟新的內(nèi)存空間,在新的內(nèi)存空間里復(fù)制一個(gè)一模一樣的對(duì)象,新老對(duì)象不共享內(nèi)存,修改其中一個(gè)對(duì)象的值,不會(huì)影響另一個(gè)對(duì)象。

深拷貝相比于淺拷貝速度較慢并且花銷較大。

16、并發(fā)和并行有什么區(qū)別?

并發(fā):兩個(gè)或多個(gè)事件在同一時(shí)間間隔發(fā)生。

并行:兩個(gè)或者多個(gè)事件在同一時(shí)刻發(fā)生。

并行是真正意義上,同一時(shí)刻做多件事情,而并發(fā)在同一時(shí)刻只會(huì)做一件事件,只是可以將時(shí)間切碎,交替做多件事情。

網(wǎng)上有個(gè)例子挺形象的:

你吃飯吃到一半,電話來了,你一直到吃完了以后才去接,這就說明你不支持并發(fā)也不支持并行。

你吃飯吃到一半,電話來了,你停了下來接了電話,接完后繼續(xù)吃飯,這說明你支持并發(fā)。

你吃飯吃到一半,電話來了,你一邊打電話一邊吃飯,這說明你支持并行。

17、構(gòu)造器是否可被 重寫?

Constructor 不能被 override(重寫),但是可以 overload(重載),所以你可以看到?個(gè)類中有多個(gè)構(gòu)造函數(shù)的情況。

18、當(dāng)一個(gè)對(duì)象被當(dāng)作參數(shù)傳遞到一個(gè)方法后,此方法可改變這個(gè)對(duì)象的屬性,并可返回變化后的結(jié)果,那么這里到底是值傳遞還是引用傳遞?

值傳遞。Java 中只有值傳遞,對(duì)于對(duì)象參數(shù),值的內(nèi)容是對(duì)象的引用。

19、Java 靜態(tài)變量和成員變量的區(qū)別。

public class Demo {
    /**
     * 靜態(tài)變量:又稱類變量,static修飾
     */
    public static String STATIC_VARIABLE = "靜態(tài)變量";
    /**
     * 實(shí)例變量:又稱成員變量,沒有static修飾
     */
    public String INSTANCE_VARIABLE = "實(shí)例變量";
}

成員變量存在于堆內(nèi)存中。靜態(tài)變量存在于方法區(qū)中。

成員變量與對(duì)象共存亡,隨著對(duì)象創(chuàng)建而存在,隨著對(duì)象被回收而釋放。靜態(tài)變量與類共存亡,隨著類的加載而存在,隨著類的消失而消失。

成員變量所屬于對(duì)象,所以也稱為實(shí)例變量。靜態(tài)變量所屬于類,所以也稱為類變量。

成員變量只能被對(duì)象所調(diào)用 。靜態(tài)變量可以被對(duì)象調(diào)用,也可以被類名調(diào)用。

20、是否可以從一個(gè)靜態(tài)(static)方法內(nèi)部發(fā)出對(duì)非靜態(tài)(non-static)方法的調(diào)用?

區(qū)分兩種情況,發(fā)出調(diào)用時(shí)是否顯示創(chuàng)建了對(duì)象實(shí)例。

1)沒有顯示創(chuàng)建對(duì)象實(shí)例:不可以發(fā)起調(diào)用,非靜態(tài)方法只能被對(duì)象所調(diào)用,靜態(tài)方法可以通過對(duì)象調(diào)用,也可以通過類名調(diào)用,所以靜態(tài)方法被調(diào)用時(shí),可能還沒有創(chuàng)建任何實(shí)例對(duì)象。因此通過靜態(tài)方法內(nèi)部發(fā)出對(duì)非靜態(tài)方法的調(diào)用,此時(shí)可能無法知道非靜態(tài)方法屬于哪個(gè)對(duì)象。

public class Demo {
    public static void staticMethod() {
        // 直接調(diào)用非靜態(tài)方法:編譯報(bào)錯(cuò)
        instanceMethod();
    }
    public void instanceMethod() {
        System.out.println("非靜態(tài)方法");
    }
}

2)顯示創(chuàng)建對(duì)象實(shí)例:可以發(fā)起調(diào)用,在靜態(tài)方法中顯示的創(chuàng)建對(duì)象實(shí)例,則可以正常的調(diào)用。

public class Demo {
    public static void staticMethod() {
        // 先創(chuàng)建實(shí)例對(duì)象,再調(diào)用非靜態(tài)方法:成功執(zhí)行
        Demo demo = new Demo();
        demo.instanceMethod();
    }
    public void instanceMethod() {
        System.out.println("非靜態(tài)方法");
    }
}

21、初始化考察,請指出下面程序的運(yùn)行結(jié)果。

public class InitialTest {
    public static void main(String[] args) {
        A ab = new B();
        ab = new B();
    }
}
class A {
    static { // 父類靜態(tài)代碼塊
        System.out.print("A");
    }
    public A() { // 父類構(gòu)造器
        System.out.print("a");
    }
}
class B extends A {
    static { // 子類靜態(tài)代碼塊
        System.out.print("B");
    }
    public B() { // 子類構(gòu)造器
        System.out.print("b");
    }
}

執(zhí)行結(jié)果:ABabab,兩個(gè)考察點(diǎn):

1)靜態(tài)變量只會(huì)初始化(執(zhí)行)一次。

2)當(dāng)有父類時(shí),完整的初始化順序?yàn)椋焊割愳o態(tài)變量(靜態(tài)代碼塊)->子類靜態(tài)變量(靜態(tài)代碼塊)->父類非靜態(tài)變量(非靜態(tài)代碼塊)->父類構(gòu)造器 ->子類非靜態(tài)變量(非靜態(tài)代碼塊)->子類構(gòu)造器 。

關(guān)于初始化,這題算入門題,我之前還寫過一道有(fei)點(diǎn)(chang)意(bian)思(tai)的進(jìn)階題目,有興趣的可以看看:一道有意思的“初始化”面試題

22、重載(Overload)和重寫(Override)的區(qū)別?

方法的重載和重寫都是實(shí)現(xiàn)多態(tài)的方式,區(qū)別在于前者實(shí)現(xiàn)的是編譯時(shí)的多態(tài)性,而后者實(shí)現(xiàn)的是運(yùn)行時(shí)的多態(tài)性。

重載:一個(gè)類中有多個(gè)同名的方法,但是具有有不同的參數(shù)列表(參數(shù)類型不同、參數(shù)個(gè)數(shù)不同或者二者都不同)。

重寫:發(fā)生在子類與父類之間,子類對(duì)父類的方法進(jìn)行重寫,參數(shù)都不能改變,返回值類型可以不相同,但是必須是父類返回值的派生類。即外殼不變,核心重寫!重寫的好處在于子類可以根據(jù)需要,定義特定于自己的行為。

23、為什么不能根據(jù)返回類型來區(qū)分重載?

如果我們有兩個(gè)方法如下,當(dāng)我們調(diào)用:test(1) 時(shí),編譯器無法確認(rèn)要調(diào)用的是哪個(gè)。

//?方法1
int?test(int?a);
//?方法2
long?test(int?a);

方法的返回值只是作為方法運(yùn)行之后的一個(gè)“狀態(tài)”,但是并不是所有調(diào)用都關(guān)注返回值,所以不能將返回值作為重載的唯一區(qū)分條件。

24、抽象類(abstract class)和接口(interface)有什么區(qū)別?

抽象類只能單繼承,接口可以多實(shí)現(xiàn)。

抽象類可以有構(gòu)造方法,接口中不能有構(gòu)造方法。

抽象類中可以有成員變量,接口中沒有成員變量,只能有常量(默認(rèn)就是 public static final)

抽象類中可以包含非抽象的方法,在 Java 7 之前接口中的所有方法都是抽象的,在 Java 8 之后,接口支持非抽象方法:default 方法、靜態(tài)方法等。Java 9 支持私有方法、私有靜態(tài)方法。

抽象類中的方法類型可以是任意修飾符,Java 8 之前接口中的方法只能是 public 類型,Java 9 支持 private 類型。

設(shè)計(jì)思想的區(qū)別:

接口是自上而下的抽象過程,接口規(guī)范了某些行為,是對(duì)某一行為的抽象。我需要這個(gè)行為,我就去實(shí)現(xiàn)某個(gè)接口,但是具體這個(gè)行為怎么實(shí)現(xiàn),完全由自己決定。

抽象類是自下而上的抽象過程,抽象類提供了通用實(shí)現(xiàn),是對(duì)某一類事物的抽象。我們在寫實(shí)現(xiàn)類的時(shí)候,發(fā)現(xiàn)某些實(shí)現(xiàn)類具有幾乎相同的實(shí)現(xiàn),因此我們將這些相同的實(shí)現(xiàn)抽取出來成為抽象類,然后如果有一些差異點(diǎn),則可以提供抽象方法來支持自定義實(shí)現(xiàn)。

我在網(wǎng)上看到有個(gè)說法,挺形象的:

普通類像親爹 ,他有啥都是你的。

抽象類像叔伯,有一部分會(huì)給你,還能指導(dǎo)你做事的方法。

接口像干爹,可以給你指引方法,但是做成啥樣得你自己努力實(shí)現(xiàn)。

25、Error 和 Exception 有什么區(qū)別?

Error 和 Exception 都是 Throwable 的子類,用于表示程序出現(xiàn)了不正常的情況。區(qū)別在于:

Error 表示系統(tǒng)級(jí)的錯(cuò)誤和程序不必處理的異常,是恢復(fù)不是不可能但很困難的情況下的一種嚴(yán)重問題,比如內(nèi)存溢出,不可能指望程序能處理這樣的情況。

Exception 表示需要捕捉或者需要程序進(jìn)行處理的異常,是一種設(shè)計(jì)或?qū)崿F(xiàn)問題,也就是說,它表示如果程序運(yùn)行正常,從不會(huì)發(fā)生的情況。

26、Java 中的 final 關(guān)鍵字有哪些用法?

修飾類:該類不能再派生出新的子類,不能作為父類被繼承。因此,一個(gè)類不能同時(shí)被聲明為abstract 和 final。

修飾方法:該方法不能被子類重寫。

修飾變量:該變量必須在聲明時(shí)給定初值,而在以后只能讀取,不可修改。 如果變量是對(duì)象,則指的是引用不可修改,但是對(duì)象的屬性還是可以修改的。

public?class?FinalDemo?{
????//?不可再修改該變量的值
????public?static?final?int?FINAL_VARIABLE?=?0;
????//?不可再修改該變量的引用,但是可以直接修改屬性值
????public?static?final?User?USER?=?new?User();
????public?static?void?main(String[]?args)?{
????????//?輸出:User(id=0,?name=null,?age=0)
????????System.out.println(USER);
????????//?直接修改屬性值
????????USER.setName("test");
????????//?輸出:User(id=0,?name=test,?age=0)
????????System.out.println(USER);
????}
}

27、闡述 final、finally、finalize 的區(qū)別。

其實(shí)是三個(gè)完全不相關(guān)的東西,只是長的有點(diǎn)像。。

final 如上所示。

finally:finally 是對(duì) Java 異常處理機(jī)制的最佳補(bǔ)充,通常配合 try、catch 使用,用于存放那些無論是否出現(xiàn)異常都一定會(huì)執(zhí)行的代碼。在實(shí)際使用中,通常用于釋放鎖、數(shù)據(jù)庫連接等資源,把資源釋放方法放到 finally 中,可以大大降低程序出錯(cuò)的幾率。

finalize:Object 中的方法,在垃圾收集器將對(duì)象從內(nèi)存中清除出去之前做必要的清理工作。finalize()方法僅作為了解即可,在 Java 9 中該方法已經(jīng)被標(biāo)記為廢棄,并添加新的 java.lang.ref.Cleaner,提供了更靈活和有效的方法來釋放資源。這也側(cè)面說明了,這個(gè)方法的設(shè)計(jì)是失敗的,因此更加不能去使用它。

28、try、catch、finally 考察,請指出下面程序的運(yùn)行結(jié)果。

public?class?TryDemo?{
????public?static?void?main(String[]?args)?{
????????System.out.println(test());
????}
????public?static?int?test()?{
????????try?{
????????????return?1;
????????}?catch?(Exception?e)?{
????????????return?2;
????????}?finally?{
????????????System.out.print("3");
????????}
????}
}

執(zhí)行結(jié)果:31。

相信很多同學(xué)應(yīng)該都做對(duì)了,try、catch。finally 的基礎(chǔ)用法,在 return 前會(huì)先執(zhí)行 finally 語句塊,所以是先輸出 finally 里的 3,再輸出 return 的 1。

29、try、catch、finally 考察2,請指出下面程序的運(yùn)行結(jié)果。

public?class?TryDemo?{
????public?static?void?main(String[]?args)?{
????????System.out.println(test1());
????}
????public?static?int?test1()?{
????????try?{
????????????return?2;
????????}?finally?{
????????????return?3;
????????}
????}
}

執(zhí)行結(jié)果:3。

這題有點(diǎn)陷阱,但也不難,try 返回前先執(zhí)行 finally,結(jié)果 finally 里不按套路出牌,直接 return 了,自然也就走不到 try 里面的 return 了。

finally 里面使用 return 僅存在于面試題中,實(shí)際開發(fā)中千萬不要這么用。

30、try、catch、finally 考察3,請指出下面程序的運(yùn)行結(jié)果。

public?class?TryDemo?{
????public?static?void?main(String[]?args)?{
????????System.out.println(test1());
????}
????public?static?int?test1()?{
????????int?i?=?0;
????????try?{
????????????i?=?2;
????????????return?i;
????????}?finally?{
????????????i?=?3;
????????}
????}
}

執(zhí)行結(jié)果:2。

這邊估計(jì)有不少同學(xué)會(huì)以為結(jié)果應(yīng)該是 3,因?yàn)槲覀冎涝?return 前會(huì)執(zhí)行 finally,而 i 在 finally 中被修改為 3 了,那最終返回 i 不是應(yīng)該為 3 嗎?確實(shí)很容易這么想,我最初也是這么想的,當(dāng)初的自己還是太年輕了啊。

這邊的根本原因是,在執(zhí)行 finally 之前,JVM 會(huì)先將 i 的結(jié)果暫存起來,然后 finally 執(zhí)行完畢后,會(huì)返回之前暫存的結(jié)果,而不是返回 i,所以即使這邊 i 已經(jīng)被修改為 3,最終返回的還是之前暫存起來的結(jié)果 2。

In fact, it can be easily seen based on the bytecode. Before entering finally, the JVM will use the iload and istore instructions to temporarily store the results. When it finally returns, it will return the temporary results through the iload and ireturn instructions. result.

In order to prevent the atmosphere from becoming abnormal again, I will not post the specific bytecode program here. Interested students can compile and check it out by themselves.

31. What are the new features after JDK1.8?

Interface default method: Java 8 allows us to add a non-abstract method implementation to the interface, just use the default keyword

Lambda expression and functional interface: Lambda An expression is essentially an anonymous inner class, or it can be a piece of code that can be passed around. Lambda allows the function to be used as a parameter of a method (the function is passed to the method as a parameter). Use Lambda expressions to make the code more concise, but do not abuse it, otherwise there will be readability problems, Josh Bloch, author of "Effective Java" suggested It is best to use lambda expressions in no more than 3 lines.

Stream API: A tool for performing complex operations on collection classes using functional programming. It can be used with Lambda expressions to easily process collections. A key abstraction for working with collections in Java 8. It allows you to specify the operations you want to perform on collections, and can perform very complex operations such as finding, filtering, and mapping data. Using the Stream API to operate on collection data is similar to using SQL to perform database queries. You can also use the Stream API to perform operations in parallel. In short, the Stream API provides an efficient and easy-to-use way to process data.

Method reference: Method reference provides a very useful syntax that can directly reference methods or constructors of existing Java classes or objects (instances). Used in conjunction with lambda, method references can make the language structure more compact and concise and reduce redundant code.

Date and time API: Java 8 introduces a new date and time API to improve date and time management.

Optional class: The famous NullPointerException is the most common cause of system failure. The Google Guava project introduced Optional a long time ago as a way to solve null pointer exceptions, disapproving of code being polluted by null-checking code, and expecting programmers to write clean code. Inspired by Google Guava, Optional is now part of the Java 8 library.

New tools: new compilation tools, such as: Nashorn engine jjs, class dependency analyzer jdeps.

32. The difference between wait() and sleep() methods

The sources are different: sleep() comes from the Thread class, and wait() comes from the Object class.

The impact on synchronization locks is different: sleep() will not behave as a synchronization lock on the table. If the current thread holds a synchronization lock, sleep will not allow the thread to release the synchronization lock. wait() will release the synchronization lock and allow other threads to enter the synchronized code block for execution.

Different scope of use: sleep() can be used anywhere. wait() can only be used in synchronized control methods or synchronized control blocks, otherwise IllegalMonitorStateException will be thrown.

The recovery methods are different: the two will suspend the current thread, but the recovery is different. sleep() will resume after the time is up; wait() requires other threads to call notify()/nofityAll() of the same object to resume again.

33. What is the difference between the sleep() method and the yield() method of a thread?

The thread enters the timeout waiting (TIMED_WAITING) state after executing the sleep() method, and enters the READY state after executing the yield() method.

The sleep() method does not consider the priority of the thread when giving other threads a chance to run, so it will give low-priority threads a chance to run; the yield() method will only give the same priority or higher priority. The thread has a chance to run.

34. What is the join() method of thread used for?

is used to wait for the current thread to terminate. If a thread A executes the threadB.join() statement, the meaning is: the current thread A waits for the threadB thread to terminate before returning from threadB.join() and continuing to execute its own code.

35. How many ways are there to write multi-threaded programs?

Generally speaking, there are three ways: 1) inherit the Thread class; 2) implement the Runnable interface; 3) implement the Callable interface.

Among them, Thread actually implements the Runable interface. The main difference between Runnable and Callable is whether there is a return value.

36. The difference between Thread calling start() method and calling run() method

run(): ordinary method call, executed in the main thread, not A new thread will be created for execution.

start(): Start a new thread. At this time, the thread is in the ready (runnable) state and is not running. Once the CPU time slice is obtained, the run() method starts to be executed.

37. Thread state flow

A thread can be in one of the following states:

NEW:新建但是尚未啟動(dòng)的線程處于此狀態(tài),沒有調(diào)用 start() 方法。

RUNNABLE:包含就緒(READY)和運(yùn)行中(RUNNING)兩種狀態(tài)。線程調(diào)用 start() 方法會(huì)會(huì)進(jìn)入就緒(READY)狀態(tài),等待獲取 CPU 時(shí)間片。如果成功獲取到 CPU 時(shí)間片,則會(huì)進(jìn)入運(yùn)行中(RUNNING)狀態(tài)。

BLOCKED:線程在進(jìn)入同步方法/同步塊(synchronized)時(shí)被阻塞,等待同步鎖的線程處于此狀態(tài)。

WAITING:無限期等待另一個(gè)線程執(zhí)行特定操作的線程處于此狀態(tài),需要被顯示的喚醒,否則會(huì)一直等待下去。例如對(duì)于 Object.wait(),需要等待另一個(gè)線程執(zhí)行 Object.notify() 或 Object.notifyAll();對(duì)于 Thread.join(),則需要等待指定的線程終止。

TIMED_WAITING:在指定的時(shí)間內(nèi)等待另一個(gè)線程執(zhí)行某項(xiàng)操作的線程處于此狀態(tài)。跟 WAITING 類似,區(qū)別在于該狀態(tài)有超時(shí)時(shí)間參數(shù),在超時(shí)時(shí)間到了后會(huì)自動(dòng)喚醒,避免了無期限的等待。

TERMINATED:執(zhí)行完畢已經(jīng)退出的線程處于此狀態(tài)。

線程在給定的時(shí)間點(diǎn)只能處于一種狀態(tài)。這些狀態(tài)是虛擬機(jī)狀態(tài),不反映任何操作系統(tǒng)線程狀態(tài)。

38、synchronized 和 Lock 的區(qū)別

1)Lock 是一個(gè)接口;synchronized 是 Java 中的關(guān)鍵字,synchronized 是內(nèi)置的語言實(shí)現(xiàn);

2)Lock 在發(fā)生異常時(shí),如果沒有主動(dòng)通過 unLock() 去釋放鎖,很可能會(huì)造成死鎖現(xiàn)象,因此使用 Lock 時(shí)需要在 finally 塊中釋放鎖;synchronized 不需要手動(dòng)獲取鎖和釋放鎖,在發(fā)生異常時(shí),會(huì)自動(dòng)釋放鎖,因此不會(huì)導(dǎo)致死鎖現(xiàn)象發(fā)生;

3)Lock 的使用更加靈活,可以有響應(yīng)中斷、有超時(shí)時(shí)間等;而 synchronized 卻不行,使用 synchronized 時(shí),等待的線程會(huì)一直等待下去,直到獲取到鎖;

4)在性能上,隨著近些年 synchronized 的不斷優(yōu)化,Lock 和 synchronized 在性能上已經(jīng)沒有很明顯的差距了,所以性能不應(yīng)該成為我們選擇兩者的主要原因。官方推薦盡量使用 synchronized,除非 synchronized 無法滿足需求時(shí),則可以使用 Lock。

39、synchronized 各種加鎖場景的作用范圍

1.作用于非靜態(tài)方法,鎖住的是對(duì)象實(shí)例(this),每一個(gè)對(duì)象實(shí)例有一個(gè)鎖。

public?synchronized?void?method()?{}

2.作用于靜態(tài)方法,鎖住的是類的Class對(duì)象,因?yàn)镃lass的相關(guān)數(shù)據(jù)存儲(chǔ)在永久代元空間,元空間是全局共享的,因此靜態(tài)方法鎖相當(dāng)于類的一個(gè)全局鎖,會(huì)鎖所有調(diào)用該方法的線程。

public?static?synchronized?void?method()?{}

3.作用于 Lock.class,鎖住的是 Lock 的Class對(duì)象,也是全局只有一個(gè)。

synchronized?(Lock.class)?{}

4.作用于 this,鎖住的是對(duì)象實(shí)例,每一個(gè)對(duì)象實(shí)例有一個(gè)鎖。

synchronized?(this)?{}

5.作用于靜態(tài)成員變量,鎖住的是該靜態(tài)成員變量對(duì)象,由于是靜態(tài)變量,因此全局只有一個(gè)。

public?static?Object?monitor?=?new?Object();?synchronized?(monitor)?{}

40、如何檢測死鎖?

死鎖的四個(gè)必要條件:

1)互斥條件:進(jìn)程對(duì)所分配到的資源進(jìn)行排他性控制,即在一段時(shí)間內(nèi)某資源僅為一個(gè)進(jìn)程所占有。此時(shí)若有其他進(jìn)程請求該資源,則請求進(jìn)程只能等待。

2)請求和保持條件:進(jìn)程已經(jīng)獲得了至少一個(gè)資源,但又對(duì)其他資源發(fā)出請求,而該資源已被其他進(jìn)程占有,此時(shí)該進(jìn)程的請求被阻塞,但又對(duì)自己獲得的資源保持不放。

3)不可剝奪條件:進(jìn)程已獲得的資源在未使用完畢之前,不可被其他進(jìn)程強(qiáng)行剝奪,只能由自己釋放。

4)環(huán)路等待條件:存在一種進(jìn)程資源的循環(huán)等待鏈,鏈中每一個(gè)進(jìn)程已獲得的資源同時(shí)被 鏈中下一個(gè)進(jìn)程所請求。即存在一個(gè)處于等待狀態(tài)的進(jìn)程集合{Pl, P2, …, pn},其中 Pi 等待的資源被 P(i+1) 占有(i=0, 1, …, n-1),Pn 等待的資源被 P0占 有,如下圖所示。

41、怎么預(yù)防死鎖?

預(yù)防死鎖的方式就是打破四個(gè)必要條件中的任意一個(gè)即可。

1)打破互斥條件:在系統(tǒng)里取消互斥。若資源不被一個(gè)進(jìn)程獨(dú)占使用,那么死鎖是肯定不會(huì)發(fā)生的。但一般來說在所列的四個(gè)條件中,“互斥”條件是無法破壞的。因此,在死鎖預(yù)防里主要是破壞其他幾個(gè)必要條件,而不去涉及破壞“互斥”條件。。

2)打破請求和保持條件:1)采用資源預(yù)先分配策略,即進(jìn)程運(yùn)行前申請全部資源,滿足則運(yùn)行,不然就等待。 2)每個(gè)進(jìn)程提出新的資源申請前,必須先釋放它先前所占有的資源。

3) Break the inalienable condition: When a process occupies certain resources and then further applies for other resources but cannot satisfy them, the process must release the resources it originally occupied.

4) Break the loop waiting condition: implement an orderly resource allocation strategy, number all resources in the system uniformly, and all processes can only apply for resources in the form of increasing sequence numbers.

42. Why use thread pool? Isn’t it comfortable to create a new thread directly?

If we directly create a new thread in the method, many threads will be created when this method is called frequently, which will not only consume system resources, but also reduce the stability of the system. Be careful to crash the system, and you can go directly to the finance department to settle the bill.

If we use the thread pool reasonably, we can avoid the dilemma of crashing the system. In general, using a thread pool can bring the following benefits:

  • Reduce resource consumption. Reduce the cost of thread creation and destruction by reusing created threads.
  • Improve response speed. When a task arrives, the task can be executed immediately without waiting for the thread to be created.
  • Increase the manageability of threads. Threads are scarce resources, and thread pools can be used for unified allocation, tuning and monitoring.

43. What are the core attributes of the thread pool?

threadFactory (thread factory): Factory used to create worker threads.

corePoolSize (number of core threads): When the thread pool is running less than corePoolSize threads, a new thread will be created to handle the request, even if other worker threads are idle.

workQueue (queue): A blocking queue used to retain tasks and hand them over to worker threads.

maximumPoolSize (maximum number of threads): The maximum number of threads allowed to be opened in the thread pool.

handler (rejection policy): When adding a task to the thread pool, the rejection policy will be triggered in the following two situations: 1) The running status of the thread pool is not RUNNING; 2) The thread pool has reached the maximum number of threads and is blocked. When the queue is full.

keepAliveTime (keep alive time): If the current number of threads in the thread pool exceeds corePoolSize, the excess threads will be terminated when their idle time exceeds keepAliveTime.

44. Let’s talk about the operation process of the thread pool.

#45. What are the rejection strategies for the thread pool?

AbortPolicy: Abort policy. The default rejection strategy directly throws RejectedExecutionException. The caller can catch this exception and write its own handling code according to the needs.

DiscardPolicy: Discard policy. Do nothing and simply discard the rejected task.

DiscardOldestPolicy: Discard the oldest policy. Abandoning the oldest task in the blocking queue is equivalent to the next task in the queue to be executed, and then resubmitting the rejected task. If the blocking queue is a priority queue, then the "drop oldest" strategy will cause the highest priority tasks to be dropped, so it is best not to use this strategy with a priority queue.

CallerRunsPolicy: Caller run policy. Execute the task in the caller thread. This strategy implements an adjustment mechanism that neither abandons the task nor throws an exception, but rolls the task back to the caller (the main thread that calls the thread pool to execute the task). Since executing the task takes a certain amount of time , so the main thread cannot submit tasks for at least a period of time, allowing the thread pool time to finish processing the tasks being executed.

46. What are the differences between List, Set and Map?

List (a good helper for dealing with sequences): The List interface stores a set of non-unique ( There can be multiple elements referencing the same object), ordered objects.

Set (focus on unique properties): Duplicate sets are not allowed, and multiple elements will not reference the same object.

Map (professional users who use Key to search): Use key-value pair storage. Map maintains values ??associated with Key. Two Keys can refer to the same object, but the Key cannot be repeated. A typical Key is a String type, but it can also be any object.

47. The difference between ArrayList and LinkedList.

The bottom layer of ArrayList is based on dynamic array implementation, and the bottom layer of LinkedList is based on linked list implementation.

For index data (get/set method): ArrayList directly locates the node at the corresponding position of the array through index, while LinkedList needs to start traversing from the head node or tail node until the target node is found, so in In terms of efficiency, ArrayList is better than LinkedList.

For random insertion and deletion: ArrayList needs to move the nodes behind the target node (use the System.arraycopy method to move the nodes), while LinkedList only needs to modify the next or prev attributes of the nodes before and after the target node, so it is more efficient. LinkedList is better than ArrayList.

For sequential insertion and deletion: Since ArrayList does not need to move nodes, it is better than LinkedList in terms of efficiency. This is why there are more ArrayLists in actual use, because in most cases our usage is sequential insertion.

48. The difference between ArrayList and Vector.

Vector and ArrayList are almost the same. The only difference is that Vector uses synchronized on the method to ensure thread safety, so ArrayList has better performance in terms of performance.

Similar relationships include: StringBuilder and StringBuffer, HashMap and Hashtable.

49. Introduce the underlying data structure of HashMap

We are now using JDK 1.8. The bottom layer is composed of "array linked list red-black tree", as shown below , and before JDK 1.8, it was composed of "array linked list".

#50. Why should it be changed to "array, linked list, red-black tree"?

Mainly to improve the search performance when hash conflicts are severe (the linked list is too long). The search performance using a linked list is O(n), while using a red-black tree is O(logn).

51. When should you use a linked list? When to use red-black trees?

For insertion, linked list nodes are used by default. When the number of nodes at the same index position exceeds 8 (threshold 8) after being added: if the array length is greater than or equal to 64 at this time, it will trigger the conversion of the linked list node into a red-black tree node (treeifyBin); and if the array length is less than 64, then The linked list will not be triggered to convert to a red-black tree, but will be expanded because the amount of data at this time is still relatively small.

For removal, when the number of nodes at the same index position reaches 6 after removal, and the node at the index position is a red-black tree node, the conversion of the red-black tree node to the linked list node (untreeify) will be triggered.

52. What is the default initial capacity of HashMap? Is there any limit to the capacity of HashMap?

The default initial capacity is 16. The capacity of HashMap must be 2 to the Nth power. HashMap will calculate the smallest 2 to the Nth power that is greater than or equal to the capacity based on the capacity we pass in. For example, if 9 is passed, the capacity is 16.

53. What is the insertion process of HashMap?

54. What is the expansion (resize) process of HashMap?

55. In addition to HashMap, what other Maps have been used, and how to choose when using them?

56. What is the difference between HashMap and Hashtable?

HashMap allows key and value to be null, but Hashtable does not.

The default initial capacity of HashMap is 16 and Hashtable is 11.

The expansion of HashMap is 2 times of the original, and the expansion of Hashtable is 2 times of the original plus 1.

HashMap is not thread-safe, Hashtable is thread-safe.

The hash value of HashMap has been recalculated, and Hashtable uses hashCode directly.

HashMap removes the contains method in Hashtable.

HashMap inherits from the AbstractMap class, and Hashtable inherits from the Dictionary class.

57. Java memory structure (runtime data area)

Program counter: Thread private. A small memory space that can be regarded as a line number indicator of the bytecode executed by the current thread. If the thread is executing a Java method, this counter records the address of the virtual machine bytecode instruction being executed; if the thread is executing a Native method, the counter value is empty.

Java virtual machine stack: thread private. Its life cycle is the same as that of a thread. The virtual machine stack describes the memory model of Java method execution: when each method is executed, a stack frame is created to store local variable tables, operand stacks, dynamic links, method exits and other information. The process from the call to the completion of execution of each method corresponds to the process from pushing a stack frame into the virtual machine stack to popping it out.

Local method stack: thread private. The functions played by the local method stack and the virtual machine stack are very similar. The only difference between them is that the virtual machine stack serves the virtual machine to execute Java methods (that is, bytecode), while the local method stack is used by the virtual machine. To the Native method service.

Java heap: thread sharing. For most applications, the Java heap is the largest piece of memory managed by the Java virtual machine. The Java heap is a memory area shared by all threads and is created when the virtual machine starts. The only purpose of this memory area is to store object instances, and almost all object instances allocate memory here.

Method area: Like the Java heap, it is a memory area shared by each thread. It is used to store class information (construction methods, interface definitions), constants, static variables, and just-in-time compilers that have been loaded by the virtual machine. Compiled code (bytecode) and other data. The method area is a concept defined in the JVM specification. Where it is placed, different implementations can be placed in different places.

運(yùn)行時(shí)常量池:運(yùn)行時(shí)常量池是方法區(qū)的一部分。Class文件中除了有類的版本、字段、方法、接口等描述信息外,還有一項(xiàng)信息是常量池,用于存放編譯期生成的各種字面量和符號(hào)引用,這部分內(nèi)容將在類加載后進(jìn)入方法區(qū)的運(yùn)行時(shí)常量池中存放。

String?str?=?new?String("hello");

上面的語句中變量 str 放在棧上,用 new 創(chuàng)建出來的字符串對(duì)象放在堆上,而"hello"這個(gè)字面量是放在堆中。

58、什么是雙親委派模型?

如果一個(gè)類加載器收到了類加載的請求,它首先不會(huì)自己去嘗試加載這個(gè)類,而是把這個(gè)請求委派給父類加載器去完成,每一個(gè)層次的類加載器都是如此,因此所有的加載請求最終都應(yīng)該傳送到頂層的啟動(dòng)類加載器中,只有當(dāng)父加載器反饋?zhàn)约簾o法完成這個(gè)加載請求(它的搜索范圍中沒有找到所需的類)時(shí),子加載器才會(huì)嘗試自己去加載。

59、Java虛擬機(jī)中有哪些類加載器?

啟動(dòng)類加載器(Bootstrap ClassLoader):

這個(gè)類加載器負(fù)責(zé)將存放在\lib目錄中的,或者被-Xbootclasspath參數(shù)所指定的路徑中的,并且是虛擬機(jī)識(shí)別的(僅按照文件名識(shí)別,如rt.jar,名字不符合的類庫即使放在lib目錄中也不會(huì)被加載)類庫加載到虛擬機(jī)內(nèi)存中。

擴(kuò)展類加載器(Extension ClassLoader):

這個(gè)加載器由sun.misc.Launcher$ExtClassLoader實(shí)現(xiàn),它負(fù)責(zé)加載\lib\ext目錄中的,或者被java.ext.dirs系統(tǒng)變量所指定的路徑中的所有類庫,開發(fā)者可以直接使用擴(kuò)展類加載器。

應(yīng)用程序類加載器(Application ClassLoader):

這個(gè)類加載器由sun.misc.Launcher$AppClassLoader實(shí)現(xiàn)。由于這個(gè)類加載器是ClassLoader中的getSystemClassLoader()方法的返回值,所以一般也稱它為系統(tǒng)類加載器。它負(fù)責(zé)加載用戶類路徑(ClassPath)上所指定的類庫,開發(fā)者可以直接使用這個(gè)類加載器,如果應(yīng)用程序中沒有自定義過自己的類加載器,一般情況下這個(gè)就是程序中默認(rèn)的類加載器。

自定義類加載器:

用戶自定義的類加載器。

60、類加載的過程

類加載的過程包括:加載、驗(yàn)證、準(zhǔn)備、解析、初始化,其中驗(yàn)證、準(zhǔn)備、解析統(tǒng)稱為連接。

加載:通過一個(gè)類的全限定名來獲取定義此類的二進(jìn)制字節(jié)流,在內(nèi)存中生成一個(gè)代表這個(gè)類的java.lang.Class對(duì)象。

驗(yàn)證:確保Class文件的字節(jié)流中包含的信息符合當(dāng)前虛擬機(jī)的要求,并且不會(huì)危害虛擬機(jī)自身的安全。

準(zhǔn)備:為靜態(tài)變量分配內(nèi)存并設(shè)置靜態(tài)變量初始值,這里所說的初始值“通常情況”下是數(shù)據(jù)類型的零值。

解析:將常量池內(nèi)的符號(hào)引用替換為直接引用。

初始化:到了初始化階段,才真正開始執(zhí)行類中定義的 Java 初始化程序代碼。主要是靜態(tài)變量賦值動(dòng)作和靜態(tài)語句塊(static{})中的語句。

61、介紹下垃圾收集機(jī)制(在什么時(shí)候,對(duì)什么,做了什么)?

在什么時(shí)候?

在觸發(fā)GC的時(shí)候,具體如下,這里只說常見的 Young GC 和 Full GC。

觸發(fā)Young GC:當(dāng)新生代中的 Eden 區(qū)沒有足夠空間進(jìn)行分配時(shí)會(huì)觸發(fā)Young GC。

觸發(fā)Full GC:

  • 當(dāng)準(zhǔn)備要觸發(fā)一次Young GC時(shí),如果發(fā)現(xiàn)統(tǒng)計(jì)數(shù)據(jù)說之前Young GC的平均晉升大小比目前老年代剩余的空間大,則不會(huì)觸發(fā)Young GC而是轉(zhuǎn)為觸發(fā)Full GC。(通常情況)
  • 如果有永久代的話,在永久代需要分配空間但已經(jīng)沒有足夠空間時(shí),也要觸發(fā)一次Full GC。
  • System.gc()默認(rèn)也是觸發(fā)Full GC。
  • heap dump帶GC默認(rèn)也是觸發(fā)Full GC。
  • CMS GC時(shí)出現(xiàn)Concurrent Mode Failure會(huì)導(dǎo)致一次Full GC的產(chǎn)生。

對(duì)什么?

對(duì)那些JVM認(rèn)為已經(jīng)“死掉”的對(duì)象。即從GC Root開始搜索,搜索不到的,并且經(jīng)過一次篩選標(biāo)記沒有復(fù)活的對(duì)象。

做了什么?

對(duì)這些JVM認(rèn)為已經(jīng)“死掉”的對(duì)象進(jìn)行垃圾收集,新生代使用復(fù)制算法,老年代使用標(biāo)記-清除和標(biāo)記-整理算法。

62、GC Root有哪些?

在Java語言中,可作為GC Roots的對(duì)象包括下面幾種:

  • Object referenced in the virtual machine stack (local variable table in the stack frame).
  • The object referenced by the class static property in the method area.
  • Object referenced by constants in the method area.
  • The object referenced by JNI (generally speaking Native method) in the local method stack.

63. What are the garbage collection algorithms and their respective characteristics?

Marking - Clearing Algorithm

First mark all objects that need to be recycled, and after the marking is completed, all marked objects will be recycled uniformly. There are two main shortcomings: one is the efficiency problem, the efficiency of the marking and clearing processes is not high; the other is the space problem. After marking and clearing, a large number of discontinuous memory fragments will be generated. Too many space fragments may cause In the future, when a larger object needs to be allocated while the program is running, sufficient contiguous memory cannot be found and another garbage collection action has to be triggered in advance.

Copy algorithm

In order to solve the efficiency problem, a collection algorithm called "Copying" (Copying) appeared, which divides the available memory into sizes according to capacity. Two equal pieces, only use one of them at a time. When this block of memory runs out, copy the surviving objects to another block, and then clean up the used memory space at once. In this way, the entire half area is recycled every time, and there is no need to consider complex situations such as memory fragmentation when allocating memory. Just move the top pointer of the heap and allocate memory in order. It is simple to implement and efficient to run. It's just that the cost of this algorithm is to reduce the memory to half of its original size, which is a bit too high.

Mark - Collation Algorithm

The copy collection algorithm will perform more copy operations when the object survival rate is high, and the efficiency will become lower. More importantly, if you don't want to waste 50% of the space, you need to have additional space for allocation guarantee to cope with the extreme situation where all objects in the used memory are 100% alive, so this method generally cannot be directly used in the old generation. algorithm.

According to the characteristics of the old generation, someone has proposed another "mark-compact" algorithm. The marking process is still the same as the "mark-clear" algorithm, but the subsequent steps are not directly related to the recyclables. Objects are cleaned up, but all surviving objects are moved to one end, and then the memory outside the end boundary is directly cleared.

Generational Collection Algorithm

Currently commercial virtual machines use the "Generational Collection" (Generational Collection) algorithm for garbage collection. There is nothing new about this algorithm. The idea is just to divide the memory into several blocks according to the different life cycles of the objects.

Generally, the Java heap is divided into the new generation and the old generation, so that the most appropriate collection algorithm can be used according to the characteristics of each generation.

In the new generation, it is found that a large number of objects die every time during garbage collection, and only a few survive. Then use the copy algorithm, and only need to pay the copy cost of a small number of surviving objects to complete the collection.

In the old generation, because the object survival rate is high and there is no extra space to allocate it to guarantee it, the mark-clean or mark-clean algorithm must be used for recycling.

Finally

In the season of gold, three and silver, I believe many students are preparing to change jobs.

I have summarized my recent original articles: original summary, which contains analysis of many high-frequency interview questions, many of which I encountered when interviewing with big companies. I am reviewing each When analyzing the questions, they will be analyzed in depth according to higher standards. You may not be able to fully understand it after reading it only once, but I believe that you will gain something by reading it repeatedly.

For more programming-related knowledge, please visit: Programming Courses! !

The above is the detailed content of [Hematemesis compilation] 2023 Java basic high-frequency interview questions and answers (Collection). For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Interviewer: Spring Aop common annotations and execution sequence Interviewer: Spring Aop common annotations and execution sequence Aug 15, 2023 pm 04:32 PM

You must know Spring, so let’s talk about the order of all notifications of Aop. How does Spring Boot or Spring Boot 2 affect the execution order of aop? Tell us about the pitfalls you encountered in AOP?

Interview with a certain group: If you encounter OOM online, how should you troubleshoot it? How to solve? What options? Interview with a certain group: If you encounter OOM online, how should you troubleshoot it? How to solve? What options? Aug 23, 2023 pm 02:34 PM

OOM means that there is a vulnerability in the program, which may be caused by the code or JVM parameter configuration. This article talks to readers about how to troubleshoot when a Java process triggers OOM.

Ele.me's written test questions seem simple, but it stumps a lot of people Ele.me's written test questions seem simple, but it stumps a lot of people Aug 24, 2023 pm 03:29 PM

Don’t underestimate the written examination questions of many companies. There are pitfalls and you can fall into them accidentally. When you encounter this kind of written test question about cycles, I suggest you think calmly and take it step by step.

5 String interview questions, less than 10% of people can answer them all correctly! (with answer) 5 String interview questions, less than 10% of people can answer them all correctly! (with answer) Aug 23, 2023 pm 02:49 PM

?This article will take a look at 5 interview questions about the Java String class. I have personally experienced several of these five questions during the interview process. This article will help you understand why the answers to these questions are like this.

Last week, I had an interview with XX Insurance and it was cool! ! ! Last week, I had an interview with XX Insurance and it was cool! ! ! Aug 25, 2023 pm 03:44 PM

Last week, a friend in the group went for an interview with Ping An Insurance. The result was a bit regretful, which is quite a pity, but I hope you don’t get discouraged. As you said, basically all the questions encountered in the interview can be solved by memorizing the interview questions. It’s solved, so please work hard!

Novices can also compete with BAT interviewers: CAS Novices can also compete with BAT interviewers: CAS Aug 24, 2023 pm 03:09 PM

The extra chapter of the Java concurrent programming series, C A S (Compare and swap), is still in an easy-to-understand style with pictures and texts, allowing readers to have a crazy conversation with the interviewer.

A question asked in almost all Java interviews: talk about the difference between ArrayList and LinkedList A question asked in almost all Java interviews: talk about the difference between ArrayList and LinkedList Jul 26, 2023 pm 03:11 PM

The data structure of Java is the focus of the interview. Anyone who has participated in a Java interview must have some experience. When interviewers ask such questions, they often want to check whether you have studied the underlying structures of commonly used data types in Java, rather than simply staying at the level of "knowing how to use".

Interviewer: Tell me about the class loading process (10 diagrams) Interviewer: Tell me about the class loading process (10 diagrams) Aug 23, 2023 pm 03:05 PM

When we want to use a class, we need to load the class into memory through ClassLoader.

See all articles