There are 2 ways you can achieve your desired output/result:
1. Using String:
You can simply append the new values at the end of String as following...
String text = "";
text = "Apple";
text = text + ", "+ "Banana";
text = text + ", "+ "Orange";
System.out.println(text); //output will be: Apple, Banana, Orange
2. Using StringBuilder: [recommended]
You can initialize StringBuilder, and use append() function to append new values at the end of the String and at last, you can get String
from StringBuilder
using toString()
method of StringBuilder
.
StringBuilder builder = new StringBuilder("");
builder.append("Apple").append(", ").append("Banana").append(", ").append("Orange");
String text = builder.toString();
System.output.println(text); //output will be Apple, Banana, Orange
2nd approach is recommended because when you append a String in StringBuilder
, it does not create new object of String in String pool every time, it updates the existing object of StringBuilder
.
Whereas String
class in Java is immutable, so when you append a String in String literal, then it does update the existing object, it does create new object of String
in String pool and points the reference to newly created String pool object.