How do I concatenate two strings in Java?

前端 未结 23 3024
长情又很酷
长情又很酷 2020-11-22 04:47

I am trying to concatenate strings in Java. Why isn\'t this working?

public class StackOverflowTest {  
    public static void main(String args[]) {
                


        
相关标签:
23条回答
  • 2020-11-22 05:03

    The java 8 way:

    StringJoiner sj1 = new StringJoiner(", ");
    String joined = sj1.add("one").add("two").toString();
    // one, two
    System.out.println(joined);
    
    
    StringJoiner sj2 = new StringJoiner(", ","{", "}");
    String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
    // {Jake, John, Carl}
    System.out.println(joined2);
    
    0 讨论(0)
  • 2020-11-22 05:05

    here is an example to read and concatenate 2 string without using 3rd variable:

    public class Demo {
        public static void main(String args[]) throws Exception  {
            InputStreamReader r=new InputStreamReader(System.in);     
            BufferedReader br = new BufferedReader(r);
            System.out.println("enter your first string");
            String str1 = br.readLine();
            System.out.println("enter your second string");
            String str2 = br.readLine();
            System.out.println("concatenated string is:" + str1 + str2);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:06

    There are two basic answers to this question:

    1. [simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
    2. [less simple]: Use StringBuilder (or StringBuffer).
    StringBuilder value;
    value.append("your number is");
    value.append(theNumber);
    value.append("!");
    
    value.toString();
    

    I recommend against stacking operations like this:

    new StringBuilder().append("I").append("like to write").append("confusing code");
    

    Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.

    Note: Spaceisavaluablecommodity,asthissentancedemonstrates.

    Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below

    Example 1

    String Blam = one + two;
    Blam += three + four;
    Blam += five + six;
    

    Example 2

    String Blam = one + two + three + four + five + six;
    
    0 讨论(0)
  • 2020-11-22 05:06

    You must be a PHP programmer.

    Use a + sign.

    System.out.println("Your number is " + theNumber + "!");
    
    0 讨论(0)
  • 2020-11-22 05:06

    You can concatenate Strings using the + operator:

    String a="hello ";
    String b="world.";
    System.out.println(a+b);
    

    Output:

    hello world.

    That's it

    0 讨论(0)
  • 2020-11-22 05:09

    For better performance use str1.concat(str2) where str1 and str2 are string variables.

    0 讨论(0)
提交回复
热议问题