mercredi 22 juin 2016

Why NullPointerException in if-then-else short statement? [duplicate]

This question already has an answer here:

I like to use the short statements in java programming, but I experienced an issue in a if-then-else statement.

The following code is a small example, but it shows the problem that I have found.

public class Example {

    public Example() {
        Double x = 0.0;

        A a = new A();

        x = a == null ? 0.0 : a.getY();   // Happens on this line

        System.out.println(x);
    }

    class A {
        Double y = null;

        private Double getY() {
            return y;
        }
    }

    public static void main(String[] args) {
        new Example();

    }
}

What's causing the exception?

Aucun commentaire:

Enregistrer un commentaire