How do I concatenate two strings in Java?

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

    There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.

    Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.

    String first = "I eat";  String second = "all the rats."; 
    System.out.println(first+second);
    

提交回复
热议问题