Why does if(Boolean.TRUE) {…} and if(true) {…} work differently in Java

前端 未结 3 734
小蘑菇
小蘑菇 2020-12-19 00:08

I want to know the difference between Boolean.TRUE and true values inside an if clause. Why does it give me a compilation error (that

3条回答
  •  误落风尘
    2020-12-19 00:51

    The difference exists because one is a true constant while the other is just mimicking one.

    The compiler will look at things like if statements and try to figure out whether they will always be a given expression (== true, == false, == null, etc) but it will only do this up to a certain level.

    In the case of true there is no ambiguity: it will always undoubtedly represent "true". However Boolean.TRUE is just a field, which is apparently not as far as the compiler is willing to go.

    public static final Boolean TRUE = new Boolean(true);
    

    Think for example about what would be done if reflection is involved.

    You can see this clearly when you introduce an extra level of complexity:

    public static void main(String[] args) {
        int x;
        if(getCondition()) {
            x = 5;
        }
        System.out.println(x);
    } 
    
    private static boolean getCondition(){
        return true;
    }
    

    Even though the expression will always be true, the compiler still complains that x might be unassigned. Only the most rudimentary verification is done to help you.

提交回复
热议问题