StringBuffer might be a better bet as it's designed to be modifiable (that String code is creating copies all over the place. actually, it's probably using StringBuffer under the covers anyway)
StringBuffer has a method:
setCharAt(int index, char ch);
which sounds ideal
have been playing with javap -c and the following is TfGuy's code
Code:
static void BullDog1() {
String petName = "BULJDOG"; // Whoops. BULLDOG will not be happy!
int i = 3;
char a = 'L';
petName = petName.substring(0,i) + a + petName.substring(i + 1);
}
which generates:
Code:
static void BullDog1();
Code:
0: ldc #25; //String BULJDOG
2: astore_0
3: iconst_3
4: istore_1
5: bipush 76
7: istore_2
8: new #4; //class java/lang/StringBuilder
11: dup
12: invokespecial #5; //Method java/lang/StringBuilder."<init>":()V
15: aload_0
16: iconst_0
17: iload_1
18: invokevirtual #26; //Method java/lang/String.substring:(II)Ljava/lang/String;
21: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
24: iload_2
25: invokevirtual #27; //Method java/lang/StringBuilder.append:(C)Ljava/lang/StringBuilder;
28: aload_0
29: iload_1
30: iconst_1
31: iadd
32: invokevirtual #28; //Method java/lang/String.substring:(I)Ljava/lang/String;
35: invokevirtual #7; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
38: invokevirtual #9; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
41: astore_0
42: return
and the following uses StringBuffer and setCharAt
Code:
static void BullDog2() {
StringBuffer petName = new StringBuffer("BULJDOG"); // Whoops. BULLDOG will not be happy!
int i = 3;
char a = 'L';
petName.setCharAt(i, a);
}
which generates:
Code:
static void BullDog2();
Code:
0: new #29; //class java/lang/StringBuffer
3: dup
4: ldc #25; //String BULJDOG
6: invokespecial #30; //Method java/lang/StringBuffer."<init>":(Ljava/lang/String;)V
9: astore_0
10: iconst_3
11: istore_1
12: bipush 76
14: istore_2
15: aload_0
16: iload_1
17: iload_2
18: invokevirtual #31; //Method java/lang/StringBuffer.setCharAt:(IC)V
21: return
half as long... 8)