一家公司的幾道筆試題

來源:互聯網
上載者:User
public class Jtest{int m=1;int i=3;void Jtest(){m=2;i=4;}public static void main(String[] args){Jtest app=new Jtest();System.out.println(app.m+","+app.i);}}

寫出輸出.
結果是1,3;
因為在這裡void Jtest();並沒有並調用,它只是一個
方法,而非構造方法,這樣的編寫是有警告的,不過
可以運行.

public class Jtest{int m=1;int i=3;Jtest(){m=2;i=4;}public static void main(String[] args){Jtest app=new Jtest();System.out.println(app.m+","+app.i);}}

寫出輸出:結果是2,4;調用了構造方法,不加修飾符,預設存取權限是package access,在Java裡沒有關鍵字表示,就是包內的能訪問,包外就不行了(即使匯入也不行).

public class Test{    static void oper(int b)    {        b = b + 100;    }        public static void main(String[] args)    {        int a = 99;        oper(a);        System.out.println(a);    }}

輸出為99.
我們來分析一下記憶體:
int a = 99;
首先在棧裡面開闢一塊空間儲存a
比如:a:xxxx
然後調用oper(a);
這時把a 的值99賦給int b;
b在記憶體裡也開闢了自己的空間,此時
值也是99.
然後執行oper(a);方法體,b = b + 100;
此時b的值為199,a的值為99.

public class Test {  public static void main(String[] args) {        String a=new String("A");        String b=new String("B");        oper(a,b);        System.out.print(a+","+b);    }  static void oper(String c,String d){      c.concat("B");      d=c;  }}

此程式輸出:A和B.
原因就是String是final類型的.並不會被改變.

public class Test{    public static void main(String[] args)    {        String a = new String("A");        String b = new String("B");        a.concat("aa");        System.out.println(a + "," + b);    }}

這個還是會輸出A,B
原因同上.

package intervie;public class Test{    public static void main(String[] args)    {        String a = new String("A");        String b = new String("B");        a = a.concat("aa");        System.out.println(a + "," + b);    }}

做了下改動,再來看看.結果就不同了.
輸出的是Aaa,B
因為String 是final類型的.所以執行到
a = c.concat("aa");
會在heap裡新建立一個對象,而a指向它.
這是一新的地址,同String a 這個已經不同了.
所以輸出的是後一個.即改變後的值.

public class Test{    static void oper(StringBuffer c,StringBuffer d)    {        d = c.append("B");    }        public static void main(String[] args)    {        StringBuffer a = new StringBuffer("A");        StringBuffer b = new StringBuffer("B");        oper(a, b);        System.out.println(a + "," + b);    }}

此程式會輸出:AB,B

StringBuffer是可變的安全執行緒的.
原試題:點此下載

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.