How do I concatenate two strings in Java?

前端 未结 23 3022
长情又很酷
长情又很酷 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:09

    Using "+" symbol u can concatenate strings.

    String a="I"; 
    String b="Love."; 
    String c="Java.";
    System.out.println(a+b+c);
    
    0 讨论(0)
  • 2020-11-22 05:12

    String.join( delimiter , stringA , stringB , … )

    As of Java 8 and later, we can use String.join.

    Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.

    Integer theNumber = 42;
    String output = 
        String                                                   // `String` class in Java 8 and later gained the new `join` method.
        .join(                                                   // Static method on the `String` class. 
            "" ,                                                 // Delimiter.
            "Your number is " , theNumber.toString() , "!" ) ;   // A series of `String` or `CharSequence` objects that you want to join.
        )                                                        // Returns a `String` object of all the objects joined together separated by the delimiter.
    ;
    

    Dump to console.

    System.out.println( output ) ;
    

    See this code run live at IdeOne.com.

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

    The concatenation operator in java is +, not .

    Read this (including all subsections) before you start. Try to stop thinking the php way ;)

    To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:

    new StringBuilder().append("firstString").append("secondString").toString()
    
    0 讨论(0)
  • 2020-11-22 05:14

    In Java, the concatenation symbol is "+", not ".".

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

    You can concatenate Strings using the + operator:

    System.out.println("Your number is " + theNumber + "!");
    

    theNumber is implicitly converted to the String "42".

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

    "+" instead of "."

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