1. 程式人生 > >Java筆試題(5)

Java筆試題(5)

stat 裏的 pre 做的 靜態 string main clas 答案

class Test{
    int getValue(){
        static int i=0;
        i++;
        return i;
    }
    public static void main(String[] args){
        Test test = Test();
        test.getValue();
        int j = test.getValue();
        System.out.println(j);
    }
}

輸出結果?

剛開始做的時候以為雖然getValue方法中的i是靜態的,但i屬於方法中的局部變量,main方法中調用2次該方法,結果還是輸出1;

看完答案我蒙了,原來方法裏的局部變量不能使用static修飾,這段代碼編譯時就會報錯。

Java筆試題(5)