• Post Reply Bookmark Topic Watch Topic
  • New Topic

Concatenating boolean and String literals  RSS feed

 
Jenna Thomas
Ranch Hand
Posts: 31
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It blew my mind when I typed this:

String s1="Hello";
String s2="Hello";

System.out.println("s1==s2 "+ s1==s2);

And got false as the output.

I didnt know that String and bool operands combined with the + operator, returns a bool.

I suppose this has to do with rules regarding mixed data types. Could someone tell me what the exact rule is?

I needed to type the following
System.out.println("s1==s2 "+ new Boolean((s1==s2)).toString());

to get my desired output of
s1==s2 true

Also, is there any easier way. Thanks!
 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jenna Thomas wrote:I didnt know that String and bool operands combined with the + operator, returns a bool.


Well, it doesn't. That isn't the actual source of your confusion, what's happening is that you made an incorrect assumption about the order in which that expression is evaluated. (I have to say I'm slightly surprised at your results too but I can see what's happening there.)

Try this change and see what it does:



This code actually concatenates a String and a boolean; your original code first concatenated a String and a boolean and then compared the result to a String. Effectively your original code did this:

 
Jenna Thomas
Ranch Hand
Posts: 31
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Similar threads has the answer to my question.

Its an operand precedence issue as mentioned here

https://coderanch.com/t/195015/certification/System-println

Im closing this thread off now
 
Jenna Thomas
Ranch Hand
Posts: 31
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul Clapham!! For your quick reply, I didnt see your reply before I marked as resolved. But thanks a lot!
 
Paul Clapham
Sheriff
Posts: 22841
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey, glad to hear that the Similar Threads is doing its job! I gave you a cow for that feedback.
 
Jenna Thomas
Ranch Hand
Posts: 31
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My first cow! Woohoo!

Seriously. Woohoo!
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not many people make the effort to look at the suggestions given in Similar Threads. The cow is certainly well-deserved.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!