Difference between these two conditions?

前端 未结 6 2397
半阙折子戏
半阙折子戏 2020-12-11 08:45

Sorry if my question is silly or not it doesnot matter. But i just want to know what will happen in these two conditions.

public class Test {
    public stat         


        
6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 09:35

    Second one does not throw NullPointerException. But again it is considered as bad code because it might happen that str is null and you do not detect that bug at this point instead you detect it somewhere else

    1. Given a choice prefer 1 since it helps you to find bugs in the program at early stage.
    2. Else add check for null if str is null then you will be able to make out are strings really not equal or is second string does not present

      if(str == null){
      //Add a log that it is null otherwise it will create confusion that 
      // program is running correctly and still equals fails
      }
      if("test".equals(str)){
          System.out.println("Before");
      }
      

    For first case

        if(str.equals("test")){//Generate NullPointerException if str is null
            System.out.println("After");
        }
    

提交回复
热议问题