8

I am trying to concatenate a String with an int and char including spaces, but not getting any concatenation. What is the reason?

private String messages;
Random r = new Random();
int random = r.nextInt(1000);

char ch='s';
messages.concat(String.valueOf(random));
messages.concat(" ");
messages.concat(String.valueOf(ch));
messages.concat(" ");
Pixel Elephant
  • 20,649
  • 9
  • 66
  • 83

5 Answers5

19

concat does not alter the invoking strings, but returns a new one.

You may assign each resulting String to your result like this.-

messages = messages.concat(String.valueOf(random));
messages = messages.concat(" ");
messages = messages.concat(String.valueOf(ch));
messages = messages.concat(" ");

Or just use the overloaded operator +

messages = String.valueOf(random) + " " + String.valueOf(ch) + " ";
ssantos
  • 16,001
  • 7
  • 50
  • 70
11

Strings are immutable. You can either append the result using String concatenation as shown in other answers or you can use StringBuilder

StringBuilder messages = new StringBuilder();
messages.append(String.valueOf(random));
messages.append(" ");
messages.append(String.valueOf(ch));
messages.append(" ");

Have a look at How do I concatenate two strings in Java?


Edit: (to insert at beginning of String)

messages.insert(0, "newstring");
Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • is there any way by which i can append any specified string at the beginning of the string? –  Sep 09 '13 at 20:41
  • yes, `StringBuilder` has an [insert](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html#insert-int-java.lang.CharSequence-) method with an offset position – Reimeus Aug 31 '17 at 17:06
6

A better way is :

Random r = new Random();
    int random = r.nextInt(1000);

StringBuilder str = new StringBuilder(String.valueOf(random));

str.append("s")
str.append(String.valueOf(random))
str.append(" ");
str.append(String.valueOf(ch));
Stathis Andronikos
  • 1,259
  • 2
  • 25
  • 44
  • thats better yes, since you wont need to create all those string Objects throw concat() method – Ahmed Adel Ismail Sep 09 '13 at 21:08
  • This should be the accepted answer. StringBuilder doesn't alloc a new string for every addition. Any time you're concat'ing more than 2 strings it's the way to go – jmaculate Jun 13 '14 at 13:56
2
messages += String.valueOf(random) + " " + String.valueOf(ch) + " ";
Cruncher
  • 7,641
  • 1
  • 31
  • 65
0
char ch='s';
messages =  messages.concat(String.valueOf(random));
messages = messages.concat(" ");
messages = messages.concat(String.valueOf(ch));
messages = messages.concat(" ");

String should be RE-Assigned, when you edit a String object, you create a new String Object in the String constant pool, but you didnt assign this new String value to any reference variable, so you will need to re-assign your modifications to the SAME REFERENCE VARIABLE that created them

Ahmed Adel Ismail
  • 2,168
  • 16
  • 23