3

I'm a beginner in java. I'm having doubts with the += operation on String. Why is it that I could use the += operator to append String objects without double-quotes?

For example I get no compiler error on this piece of code

String s1 = "abc";
String s1+=42;

When I was actually thinking that I have to use s1+="42";

lxcky
  • 1,668
  • 2
  • 13
  • 26
gsha
  • 31
  • 5

3 Answers3

2
 String s1+=def;

That line is valid then and then def is another Java String. Since it is compiling successfully, some where before in your code, you have

 String def ="someDeclaredStringBefore";

**Update:**

To get clarity on whats happennig there, first let see how + works on Strings.

It uses StringBuilder append method. For ex

 StringBuilder compilerGeneratedBuilder = new StringBuilder();  
 compilerGeneratedBuilder.append("str");  
 compilerGeneratedBuilder.append("ingcon");  
 compilerGeneratedBuilder.append("catenation");  
 String finalString = compilerGeneratedBuilder.toString();

Full story I wrote here recently :

http://codeinventions.blogspot.com/2014/08/compiler-version-string-concatenation.html

When you wrote String r += 42;

Since you are trying to add an int value. Corresponding append(int i) method calls on StringBuilder and final string generates.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

Using this code to simulate your question above:

    String s = "asd";
    s+=42;
    System.out.println(s);

Will result in this byteCote:

 Code:
      0: ldc           #16                 // String asd
      2: astore_1
      3: new           #18                 // class java/lang/StringBuilder
      6: dup
      7: aload_1
      8: invokestatic  #20                 // Method java/lang/String.valueOf:(
java/lang/Object;)Ljava/lang/String;
     11: invokespecial #26                 // Method java/lang/StringBuilder."<
nit>":(Ljava/lang/String;)V
     14: bipush        42
     16: invokevirtual #29                 // Method java/lang/StringBuilder.ap
end:(I)Ljava/lang/StringBuilder;
     19: invokevirtual #33                 // Method java/lang/StringBuilder.to
tring:()Ljava/lang/String;
     22: astore_1
     23: getstatic     #37                 // Field java/lang/System.out:Ljava/
o/PrintStream;
     26: aload_1
     27: invokevirtual #43                 // Method java/io/PrintStream.printl
:(Ljava/lang/String;)V
     30: return

Look at number 16 and 19 you can clearly see that it call the StringBuilder class and call append method internally to the += operator which appended 42 and in line 19 it then converted it to String.

EDIT:

the above code is actually saying like this: s = s + 42, so each time you use plus operator to a Integer to the String it will call its wrapper class and call the toString method

JLS

Any type may be converted to type String by string conversion.

A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression (§15.9):

If T is boolean, then use new Boolean(x).

If T is char, then use new Character(x).

If T is byte, short, or int, then use new Integer(x).

If T is long, then use new Long(x).

If T is float, then use new Float(x).

If T is double, then use new Double(x).

This reference value is then converted to type String by string conversion.
Now only reference values need to be considered:

If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).

Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.
Rod_Algonquin
  • 26,074
  • 6
  • 52
  • 63
  • Wouldn't it be better to find the relevant section of the JLS and quote from that? Looking at the compiler output is crude ... and what if this was a compiler bug? – Stephen C Sep 03 '14 at 05:52
  • @nem if you are using windows go to command prompt and `cd to_folder_of_your_project/bin` and after use the `javap -c NAME_OF_CLASS` – Rod_Algonquin Sep 03 '14 at 05:53
1
String s1 = "abc";
String s1+=42;

This worked because 42 is an int.

The plus sign + is an overloaded operator in Java. It can either add numbers or append Strings.

  1. If you use + on both numbers, it will add it.

    System.out.println(1+1); //2

  2. If you use it on both Strings, it will append the Strings.

    System.out.println("abc"+"def"); //abcdef

  3. If you use it in a combination of numbers and Strings, it will just append it together.

    System.out.println(1+"1"); //11

For more information, check out this article on Oracle

lxcky
  • 1,668
  • 2
  • 13
  • 26