0

How can I Concatenate or Merge a string after another string in java? for example I have this first string:

String1="12345"

and this is second string:

String2="00000"

How to concatenate the second string after first string? Output is:

String3="1234500000"
Mohammad Farahi
  • 1,006
  • 4
  • 14
  • 38

2 Answers2

1

You can use the + operator to concatenate them. Give your variables small first letters: string1

Plus operator for printing:

System.out.println(string1 + string2);

Or store in a third String (string3)

string3 = string1 + string2;

There is the string1.concat(string2) function, but if there is a Null value it will NPE. Furthermore, the concat() method only accepts String values while the + operator will silently convert the argument to a String (using the toString() method for objects) See here for more on Concat and +

Community
  • 1
  • 1
RossC
  • 1,200
  • 2
  • 11
  • 24
  • Is this operation stores string2 directly after string3? – Mohammad Farahi Sep 01 '14 at 14:51
  • What do you mean? `string3` will be `string1` followed by `string2` or as in your example "1234500000" – RossC Sep 01 '14 at 14:52
  • ???? That was downvoted already, I didn't touch the question at all! I went to the trouble of answering your question! – RossC Sep 01 '14 at 14:58
  • @MohammadFarahi No problem, my pleasure! I wouldn't downvote a question I've answered, and if I do downvote I add a comment saying why! Thanks for accepting. – RossC Sep 01 '14 at 15:00
1

You can also do the following:

String string1 = "12345";
String string2 = "00000";

string1 += string2;

System.out.println(string1);

By doing it this way, you can eliminate the string3 variable.

Toby Blanchard
  • 216
  • 1
  • 5