Why the method of concat() doesn't work?

B

Bruce Sam

Below is my simple java program:
/* **************************************** */
public class MyString {
public static void main(String[] args) {
String str1 = "BCDE";
System.out.println(str1);
String str2 = "A";
System.out.println(str2);
str2.concat(str1);
System.out.println(str2);
}
}
/* **************************************** */
I think the run result should be as:
BCDE
A
ABCDE
But in fact,it is:
BCDE
A
A
Why the method of concat() doesn't work?What I hope to do is only to
concatenate the str1 to the end of str2;
 
L

Lothar Kimmeringer

Why the method of concat() doesn't work?What I hope to do is only to
concatenate the str1 to the end of str2;

A String is immutable, so all methods that should do something
with the content of a String can only return a new String
containing the result. You just throw away that result in your
source-code. You need to assign that result to a variable.


Regards, Lothar
--
Lothar Kimmeringer E-Mail: (e-mail address removed)
PGP-encrypted mails preferred (Key-ID: 0x8BC3CD81)

Always remember: The answer is forty-two, there can only be wrong
questions!
 
A

Andrew Thompson

Below is my simple java program:

Good (simple) example, but please use indentation in future
to make it easier to read. 2-3 spaces for each tab character
(don't post tab characters) should be sufficient.

In any case, you seem to have a misunderstanding about the
method 'concat' actually changing a string, hopefully this
will explain that it does not.

<sscce>
public class MyString {
public static void main(String[] args) {
String str1 = "BCDE";
System.out.println(str1);
String str2 = "A";
System.out.println(str2);
str2.concat(str1);
System.out.println(str2);

// 'concat' returns a string, it does not change the string
System.out.println(str2.concat(str1));

// however you can assign the string returned to an attribute
str2 = str2.concat(str1);
System.out.println(str2);
}
}
</sscce>

BTW - in future, please post these sorts of (basic)
question to a more appropriate group, described here.
<http://www.physci.org/codes/javafaq.jsp#cljh>

HTH
 
B

Bryce

Below is my simple java program:
/* **************************************** */
public class MyString {
public static void main(String[] args) {
String str1 = "BCDE";
System.out.println(str1);
String str2 = "A";
System.out.println(str2);

instead of this:
str2.concat(str1);
^^^^^^^^^^^^^

do this:

str2 = str2.concat(str1);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top