search

Home  >  Q&A  >  body text

Java中null==1,为什么会报错?

if(a=1){
}
当a=null的时候,会报错,为什么呀?
是不是每一个判断都要先判断a是否等于null?

    String a=null;
    if (a.equals("")) {
        System.out.println(1);
    }
PHP中文网PHP中文网2807 days ago852

reply all(4)I'll reply

  • 黄舟

    黄舟2017-04-18 10:11:58

    First of all, you wrote the if conditional statement if(a=1){} wrong. It should be written as if(a==1){}
    Secondly, if the reference type a of String is empty, if the method of a is called Will throw the null pointer
     

    String a=null;
    if (a.equals("")) {
        System.out.println(1);
    }
    

    If you write like this, you must determine that a is not null. If you don’t want to write the operation of determining that a is not null, you can write it as

    String a=null;
    if("".equals(a)){
         System.out.println(1);
    }

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-18 10:11:58

    What is the syntax of

    a=1
    If a is String type;
    a= "1";
    If a is int type;
    a = 1;
    If a is int type, int type does not have null
    null can only Judge String

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:11:58

    What is written in the brackets of the if statement is a judgment expression, the result is true or false, and the a=1 you wrote is an assignment expression

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:11:58

    The type in the brackets is bool, yours is an assignment

    reply
    0
  • Cancelreply