Java multiline string

前端 未结 30 2876
醉梦人生
醉梦人生 2020-11-22 15:55

Coming from Perl, I sure am missing the \"here-document\" means of creating a multi-line string in source code:

$string = <<\"EOF\"  # create a three-l         


        
30条回答
  •  自闭症患者
    2020-11-22 16:27

    Pluses are converted to StringBuilder.append, except when both strings are constants so the compiler can combine them at compile time. At least, that's how it is in Sun's compiler, and I would suspect most if not all other compilers would do the same.

    So:

    String a="Hello";
    String b="Goodbye";
    String c=a+b;
    

    normally generates exactly the same code as:

    String a="Hello";
    String b="Goodbye":
    StringBuilder temp=new StringBuilder();
    temp.append(a).append(b);
    String c=temp.toString();
    

    On the other hand:

    String c="Hello"+"Goodbye";
    

    is the same as:

    String c="HelloGoodbye";
    

    That is, there's no penalty in breaking your string literals across multiple lines with plus signs for readability.

提交回复
热议问题