Several ways of connecting strings in Java and their advantages and disadvantages

Time:2021-10-7

Several ways of connecting strings in Java and their advantages and disadvantages

String concatenation is very common in Java programs. This article will summarize four ways of string concatenation

  • +connect

  • String.concat()

  • StringBuilder

  • StringBuffer

use+Number connection

class Helloworld {

result: Hello World!

advantage:

  • Simple operation

Disadvantages:

  • Because each use will generate a new string object to load a new string, the efficiency is very low

Applicable scenario

  • Simple string link

String.concat

public class SringC {

public static void main(String[] args) {

String test = "Hello ";

String test1 = test.concat("World!");

System.out.println(test1);

}

}

result: Hello World!

advantage:

  • Simple operation

Disadvantages:

  • Not found yet

Applicable scenario

  • Simple string link

StringBuilder

public class StringB {

public static void main(String[] args) {

StringBuilder builder = new StringBuilder();

builder.append("Hello ");

builder.append("World!");

System.out.println(builder.toString());

}

}

result: Hello World!

advantage:

  • There is no need to generate string objects every time, which is efficient

Disadvantages:

  • Not found yet

Applicable scenario

  • Large string construction, such as reading from text

StringBuffer

public class SringF {

public static void main(String[] args) {

StringBuffer buffer = new StringBuffer();

buffer.append("Hello ");

buffer.append("World!");

System.out.println(buffer.toString());

}

}

result: Hello World!

advantage:

  • There is no need to generate string objects every time, and the efficiency is high (lower than)StringBuilder(mode)

Disadvantages:

  • Not found yet

Applicable scenario

  • Large string construction, such as reading from text

  • Support multi-threaded creation

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Reprint prohibited

Recommended Today

Summary of DOM event flow in JS

1、 Event capture 1. Concept Event capture: from the document to the node that triggered the event,Top downTo trigger the event. 2. Illustration Event capture 2、 Event bubbling 1. Concept Event bubbling: from the node that triggered the event to the document, yesBottom upTo trigger the event. 2. Illustration Event Bubbling 3、 DOM event flow […]