A fellow moderator asked me to weigh in on this question at CodeRanch. The gist is whether this code creates one String or two:
String s = " " + 3;
How to find out the answer
The most definitive way to verify this is to check the bytecode. I had downloaded the bytecode plugin when working on our Java 8 OCA Study Guide because sometimes you just have to know what actually goes on behind the scenes to be accurate.
Using the plugin is easy. You go to Window -> Show View -> Other -> Java -> Bytecode. Then every time you save the Java file, the bytecode window is automatically updated. Great for lots of iterations.
The test
I wrote a simple Java class:
package jb;
public class PlayTest {
public static void main(String[] args) {
String s = "" + 3;
}
}
The generated bytecode is:
// class version 52.0 (52)
// access flags 0x21
public class jb/PlayTest {
// compiled from: PlayTest.java
// access flags 0x1
public <init>()V
L0
LINENUMBER 4 L0
ALOAD 0
INVOKESPECIAL java/lang/Object.<init> ()V
RETURN
L1
LOCALVARIABLE this Ljb/PlayTest; L0 L1 0
MAXSTACK = 1
MAXLOCALS = 1
// access flags 0x9
public static main([Ljava/lang/String;)V
L0
LINENUMBER 8 L0
LDC "3"
ASTORE 1
L1
LINENUMBER 14 L1
RETURN
L2
LOCALVARIABLE args [Ljava/lang/String; L0 L2 0
LOCALVARIABLE s Ljava/lang/String; L1 L2 1
MAXSTACK = 1
MAXLOCALS = 2
}