0
public class Whatever {
    static double d;
    static char c;
    static String[] s;
    static char[] b;
    static double[] dd;
    static Whatever w;
    static Whatever[] ww;

    public static void main(String[] args) {
        System.out.println(Whatever.d); //prints out 0.0
        System.out.println("hi"+Whatever.c+"hi"); //prints out hi hi
        System.out.println(s); //prints out null
        System.out.println(b); //null pointer exception!
        System.out.println(Whatever.dd);
        System.out.println(Whatever.w);
        System.out.println(Whatever.ww);
    }
}

null ポインター例外が発生するのはなぜですか?

できればメモリの観点から説明してください。ただし、私はメモリの基本的な理解があるので、あまり深入りしないでください。

4

3 に答える 3

0

ここにはいくつかの問題があります:

1. You're not allocating any space for `int x`
2. If you want to print the contents of `x`, it should be `x.toString()`
3. What did you expect the output to be from your sample code?

#3はあなたが実際に取り組んでいるものではないと思います。本当の答えを得るために実際のコードを表示することをお勧めします:)

うまくいけば、これで少しはすっきりするでしょう。

$ cat Whatever.java 
public class Whatever {
    static final int MAX = 5;
    int[] x = new int[MAX]; // allocate array to sizeof '5'

    public Whatever() {
        // do stuff
    }

    public void addStuff() {
        for(int i=0; i<MAX; i++)
            x[i] = i + 2;

    }

    public void printX() {
        for(int i=0; i<MAX; i++)
            System.out.println(i + ": " + x[i]);

    }

    public static void main(String[] args){
        Whatever w = new Whatever();  // new instance of 'Whatever'
        w.addStuff();                 // add some ints to the array
        w.printX();                   // print out the array
        // print the Array 'x'
        System.out.println("Array: " + w.x);
    }
}
$ java Whatever 
0:  2
1:  3
2:  4
3:  5
4:  6
Array: [I@870114c
于 2013-04-02T00:16:49.927 に答える