= and == difference in If statement Java

后端 未结 5 1216
感情败类
感情败类 2021-01-19 04:39

I am facing something strange here. Please help me understand if I am missing something. My if condition was supposed to be:

if(configuredPdf == true)
         


        
5条回答
  •  余生分开走
    2021-01-19 05:05

    An assignment expression's result is always the value that was assigned, including when assigning to a boolean. This is covered by JLS§15.26:

    At run time, the result of the assignment expression is the value of the variable after the assignment has occurred.

    So yes, configuredPdf = true assigns true to configuredPdf, and the result of that expression is true.

    Similarly, x = y = 5; assigns 5 to y, and the result of y = 5 is 5, which is then assigned to x.

    Fundamentally, what you wanted was:

    if (configuredPdf)
    

    There's never any need to compare a boolean variable with true or false, just use the if (theVariable) (for comparing with true) or if (!theVariable) (for comparing with false). Getting in that habit will protect you from inadvertent assignment.

    The only time actually comparing boolean values is useful is when they're both variables, e.g. if (thisFlag == thatFlag) or if (thisFlag != thatFlag).

    To avoid accidental assignment in that situation, either:

    1. Use a linter that checks for this

    2. "double bang" the first flag:

      if (!!thisFlag == thatFlag)
      

      ...although as you pointed out if you can accidentally type = instead of ==, presumably you can accidentally type ! instead of !! :-)

    3. Use an old C idiom (this is what I use):

      if (!thisFlag == !thatFlag)
      

提交回复
热议问题