Why does Java's concat() method not do anything?
a String is immutable, meaning you cannot change a String in Java. concat() returns a new, concatenated, string.
String s = "TEST";
String s2 = s.trim();
String s3 = s.concat("ING");
System.out.println("S = "+s);
System.out.println("S2 = "+s2);
System.out.println("S3 = "+s3);
Why does 'concat' not change String?
s1.concat(" Y");
doesn't alter s1
(it can't, since Strings are immutable).
It returns a new String :
String s2 = s1.concat(" Y");
System.out.println("s2 refers to "+s2);
Why doesn't the String method concat work in a for loop?
The concat
method doesn't mutate the current String, but in fact returns a new String
containing the result.
Use it like this:
output = output.concat(str);
String.concat
documentation.
String.concat() doesn't do concatenation
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) + " ";
Why doesn't my Java string concatenation work?
String
is immutable and concat() will return a new String
(check the linked doc), which you're not collecting.
You should make use of a StringBuilder to build a string efficiently, and then call toString()
on that once you're complete to get he resultant String.
e.g.
StringBuilder sb = new StringBuilder();
while (....) {
sb.append("more string data");
}
String str = sb.toString();
You can append Strings
e.g.
str = str + "more string data";
but it's not very efficient, due to the implementation of String
. A StringBuilder
is built in order to perform concatenation efficiently. You can tune a StringBuilder
via its initial capacity if you have an idea of the size of String
you're building.
You may see some sources refer to a StringBuffer
. That's very similar, except it's older and synchronises its methods by default. In a non-threaded environment that's wasteful and the general advice is to prefer StringBuilder
.
Clarification on String concatenation in java
Because you're not assigning the concatenated String to another value (as concat()
returns the resulting String), so it is lost.
If you want to get the result, you need to do:
test = test.concat("test");
The second println()
works, because the resulting concatenated string is returned, captured and used immediately by System.out.println()
, but is then lost outside of the println()
as it is not assigned (so if you check test
after, it still just contains "test"
).
Here's the doc: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#concat%28java.lang.String%29
String concatenation not working, or is it a bug
Ok, we see this question at least couple of times a day.
Strings
are immutable
, so all operations on String results in new String
.
conc= conc.concat("hello ");
you need to reassign result to string again
When to use String#concat() method in Java?
String#concat
and +
exist to provide a minimalistic set of operations on the type String.
They are not efficient if used multiple times.
But they have their own right as type operations "xxx" + "yyy"
you do not want to specify using a StringBuilder. (Furthermore there it is a compile time concatenation.)
StringBuffer
is a mistake IMHO. It is slower that the newer StringBuilder
as it is synchronized, but one would rarely add something rom two threads (unordered).
String::concat
may be a method reference useful for stream reduction or such.
Related Topics
JPA Query Selecting Only Specific Columns Without Using Criteria Query
Jtable How to Change Background Color
How to Set Up Java Logging Using a Properties File? (Java.Util.Logging)
Calling Superclass from a Subclass Constructor in Java
Gson Custom Seralizer for One Variable (Of Many) in an Object Using Typeadapter
Java - Removing Duplicates in an Arraylist
Can't Cast to to Unspecific Nested Type with Generics
How to Use Mockito When We Cannot Pass a Mock Object to an Instance of a Class
How to Check If a String Contains Only Ascii
How to Handle Precision Error with Float in Java
How Could I Add a Simple Delay in a Java Swing Application
Java - Generate Random Range of Specific Numbers Without Duplication of Those Numbers - How To
No Color Highlight in Eclipse in Some Files
How to Convert a 1D Array to 2D Array
Composing Swing Components: How to Add the Ability to Add Actionlisteners