Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 793
siva Avatar asked Jan 22 '26 11:01

siva


1 Answers

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 ==

like image 103
Abimaran Kugathasan Avatar answered Jan 25 '26 01:01

Abimaran Kugathasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!