How is the append method used in Java?
In Java, the append() method is used to add a specified string, character, character array, or other appendable object to the end of a StringBuilder or StringBuffer object.
The append() method can accept a variety of parameters including strings, characters, booleans, integers, floats, etc. Depending on the type of parameter, the append() method will convert it to a string and append it to the end of a StringBuilder or StringBuffer object.
Here are some common usage examples of the append() method:
- Adding extra characters:
StringBuilder sb = new StringBuilder("Hello");
sb.append(" World");
System.out.println(sb.toString()); // 输出:Hello World
- Additional characters:
StringBuilder sb = new StringBuilder("Hello");
sb.append('!');
System.out.println(sb.toString()); // 输出:Hello!
- Addition of integers:
StringBuilder sb = new StringBuilder("The answer is: ");
sb.append(42);
System.out.println(sb.toString()); // 输出:The answer is: 42
- Additional floating-point numbers:
StringBuilder sb = new StringBuilder("The value is: ");
sb.append(3.14);
System.out.println(sb.toString()); // 输出:The value is: 3.14
The append() method can be called multiple times to continuously add content, allowing for the construction of longer strings and avoiding the frequent creation of new string objects.