How to concatenate string in java

感情迁移 提交于 2021-02-04 16:46:58

问题


Here is my code for string concatenation.
StringSecret.java

public class StringSecret {
    public static void main(String[] args) {
        String s = new String("abc");
        s.concat("def");
        System.out.println(s);
    }
}

I expected that the output will be "abcdef" but I am getting only "abc" printed. What's the problem !.


回答1:


In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string object is created its data or state can't be changed but a new string object is created.

so to get the output as "abcdef" write "s.concat("def");"

Example

public class StringSecret {

public static void main(String[] args) {
    String s = new String("abc");

    s = s.concat("def");
    System.out.println(s);

  }
}

I hope it will help you.




回答2:


In java strings are immutable. It cannot be changed. concat(...) function doesn't change the value of s but it just return the concated value passed as argument with s.
You will have to store it in another variable or print it directly or use s = s.concat("def")

String c = s.concat("def");
System.out.println(c);

For the note, you can just use c = s + "def"; in java or s += "def"




回答3:


String s = new String("abc");
s.concat("def");

 String s = new String("abc");
 s = s.concat("def");

Note:- Don't initialize string like this String a = new String("abc"); just use this String a = "abc";




回答4:


Try this one..

public class Test {

   public static void main(String args[])
   {
      String s = "Strings are immutable";
      s = s.concat(" all the time");
      System.out.println(s);
   }
}



回答5:


Strings dont mutate so the result of the concatenation must be assigned to something otherwise will be lost example:

String s = new String("abc");
s = s.concat("def");



回答6:


s = s.concat("def");
 System.out.println(s);

You are concatenating correctly, but you are not saving the result of concatenation anywhere.



来源:https://stackoverflow.com/questions/35932331/how-to-concatenate-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!