what is the difference when string == is used for comparison with in System.out.println() and in a if statement

StackOverflow https://stackoverflow.com/questions/22504260

  •  17-06-2023
  •  | 
  •  

Pregunta

String att = "siva";   
String ptt = "siva";

System.out.println("__________________________ptt.equals(att)_______"+ptt.equals(att));
**System.out.println("__________________________att == ptt________"+att == ptt);**   
if(att == ptt){   
    System.out.println("true");  
}else{   
    System.out.println("false");   
}

On my log i find the following output:

__________________________ptt.equals(att)_______true   
**false**   
true   

here if you look at the java code and the log (in bold). there is a difference .

  1. In the print statement i have given a long underscore with some text. it is not appearing.
  2. att==ptt gives false when it is given with in print statement. and true when it is given in if condition.

already i know, what is a reference and what is a object.
what is difference between att==ptt and att.equals(ptt).
immutability of a string.

but just what to know why it returns false and true when printed in different forms? and why the text that i have entered in the print statement not reflected in log?

please correct it if am wrong.. or if any extra input is required.

¿Fue útil?

Solución

In the print statement i have given a long underscore with some text. it is not appearing.

Because, those underscore was concatenated with att and checked to referential equality(==) with ptt, and prints false, becuase concataneted String and ptt are not referentially equal. Change it like following to get you desired output

System.out.println("__________________________att == ptt________"+(att == ptt));

att==ptt gives false when it is given with in print statement. and true when it is given in if condition.

Both are referring same String literal in String constant pool, but, in the previous case(your 1st question), att was concatenated with the under score and compared with ==

Otros consejos

Change the Line to:

System.out.println("__________________________att == ptt________"+(att == ptt));

Now your output will be as expected. First it compare the reference of att and ptt and then it is printed. You only forgott the parentheses . Now the result will be the same like in the if-statement. And the result is true because you are using String literals to assign the value "siva". Internally this literals got the same reference. If you creat String objects like new String("siva") the output of your code will be false because you are comparing the reference with == and if you creat two objects the reference is different.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top