Is CONSTANT.equals(VARIABLE) faster than VARIABLE.equals(CONSTANT)?

后端 未结 7 1807
小蘑菇
小蘑菇 2021-02-07 11:43

I had an interesting conversation with one of my team mate.

Is CONSTANT.equals(VARIABLE) faster than VARIABLE.equals(CONSTANT)in Java?

7条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-07 12:18

    If we compare CONSTANT key(Left side of equals method) with any Object(Right side of equals method) then compiler can do check comparison and give the expected result, but if we do vice versa Object((Left side of equals method)) comparison with Constant key((Right side of equals method)) then your program might through the NULL POINTER EXCEPTION.

    public static void main(String[] args) {
        String CONSTANT_KEY = "JAVA";
        String string = null;
    
        // CASE 1
        if (CONSTANT_KEY.equals(string)) {
            System.out.println("I am in if block");
        }
    
        // CASE 2   
        if (string.equals(string)) {
            System.out.println("I am in if block");
        }
    }
    

    In above code case 1 is always safe to compare the objects to avoid NULL POINTER EXCEPTION instead of case 2.

提交回复
热议问题