= and == difference in If statement Java

后端 未结 5 1282
感情败类
感情败类 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:01

    An assignment is an expression which returns the value you assigned. e.g. a = b = true will assign true to a and b.

    The reason boolean type was added was to avoid this sort of bug. In C for example you can write

    if (a = 1)
    

    and anything non-negative is true.

    While you can still make a mistake with boolean types, instead of writing

    if (a == true)
    if (b == false)
    

    you can write

    if (a)
    if (!b)
    

    A more common example is

    for(String line; ((line = br.readLine()) != null;) {
        // process the line.
    }
    

提交回复
热议问题