Getting confused with == and = in “if” statement

前端 未结 5 477
时光说笑
时光说笑 2020-12-18 23:06

I know that we cant use assignment operator in if statements in java as we use in any other few languages.

that is

            int a;

            i         


        
5条回答
  •  悲&欢浪女
    2020-12-18 23:50

    The rule is not that "assignment can't be used in an if statement", but that "the condition in an if statement must be of type boolean". An assignment expression produces a value of the type being assigned, so Java only permits assignment in an if statement if you're assigning a boolean value.

    This is a good reason why the style if (foo == true) should be avoided, and instead simply write if (foo).

提交回复
热议问题