java基礎:面試題【不斷更新】

十五樓亮哥發表於2015-01-30

1:

Q:String s1 = new String("hello");這句話建立了幾個物件?

A:兩個或者一個。字串是一個常用的型別。JVM中存在常量池,儲存了大量的字串物件,並共享使用。

如果常量池中沒有“hello”,則在常量池中建立“hello”,然後在堆中開闢一塊空間儲存new的物件。如果常量池中已經存在“hello”,則只需要建立new一個物件。


2:

String a = "hello";
changeValue(a);
System.out.println(a);

輸出結果為hello。因為String只要初始化,就不可變。changeValue(a)建立了一個新的物件。


3:

String str1 = "china";
String str2  = "hello";

Q:如何比較兩個字串的字典順序

A:使用compareTo方法

//compareTo結果大於0 表示呼叫方法的字串字典順序在後面
//compareTo結果小於0 表示呼叫方法的字串字典順序在前面


4:public class TestLoop {
public static void main(String[] args) {
int a = 1;
int b = 10;
do {
b-= a; 
a++;  
} while (b--<0);

System.out.println("a="+a);
System.out.println("b="+b);
}
}

知識點:

(1)b-= a; //等價於 b = b - a
  a++;   //等價於 a = a + 1

 (2)do while至少執行一次,第二次是否執行do看while條件是否滿足。

     

相關文章