Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing string references in Java [duplicate]

Tags:

java

string

The code in the following snippet just compares string references.

String str1 = "mystring9";
String str2 = "mystring"+String.valueOf(9);

System.out.println(str1==str2);

In this case, str1==str2 returns false.


The following segment of code also returns false.

String str1 = "mystring9";
String str2="mystring"+str1.length();

System.out.println(str1==str2);

The following code however, returns true.

String str1 = "mystring9";
String str2 = "mystring"+9;

System.out.println(str1==str2);

I think, the expression "mystring"+9 in this code should internally be evaluated to String.valueOf(9) though why do the first two examples return different output than the preceding example?

like image 703
Tiny Avatar asked Aug 03 '26 23:08

Tiny


1 Answers

The Java compiler will pre-evaluate all constant-only operations. (this is called constant folding)

Therefore, "A" + "b" + 3 compiles to "Ab3".

like image 137
SLaks Avatar answered Aug 06 '26 12:08

SLaks



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!