Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+ operator for String in Java [duplicate]

I saw this question a few minutes ago, and decided to take a look in the java String class to check if there was some overloading for the + operator.

I couldn't find anything, but I know I can do this

String ab = "ab";
String cd = "cd";
String both = ab + cd; //both = "abcd"

Where's that implemented?

like image 758
Samuel Carrijo Avatar asked Feb 24 '10 18:02

Samuel Carrijo


2 Answers

From the Fine Manual:

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

See String Concatenation in the JLS.

like image 146
Josh Lee Avatar answered Oct 08 '22 11:10

Josh Lee


The compiler treats your code as if you had written something like:

String both = new StringBuilder().append(ab).append(cd).toString();

Edit: Any reference? Well, if I compile and decompile the OP's code, I get this:

0:  ldc #2; //String ab
2:  astore_1
3:  ldc #3; //String cd
5:  astore_2
6:  new #4; //class java/lang/StringBuilder
9:  dup
10: invokespecial   #5; //Method java/lang/StringBuilder."<init>":()V
13: aload_1
14: invokevirtual   #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
17: aload_2
18: invokevirtual   #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: invokevirtual   #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
24: astore_3
25: return

So, it's like I said.

like image 26
Sean Avatar answered Oct 08 '22 10:10

Sean