How do I concatenate two strings in Java?

前端 未结 23 3517
长情又很酷
长情又很酷 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条回答
  •  闹比i
    闹比i (楼主)
    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;
    

提交回复
热议问题