+ 7

Someone can explain how to use append() ?

27th Aug 2017, 1:46 AM
Davide Mazzeo
Davide Mazzeo - avatar
4 Antworten
+ 8
thanks!
27th Aug 2017, 3:00 AM
Davide Mazzeo
Davide Mazzeo - avatar
+ 7
yes i used that but i have seen also StringBuffer. where are the differences?
27th Aug 2017, 2:09 AM
Davide Mazzeo
Davide Mazzeo - avatar
+ 2
You're gonna need to be more descriptive. There are several append() methods in Java. I'm going to guess that you mean the append method for a StringBuilder, since it's one of the most common. import java.lang.StringBuilder; import java.util.Scanner; public class Program { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("Hello,"); sb.append(" World!"); System.out.println(sb.toString()); sb.delete(0,sb.length()); Scanner sc = new Scanner(System.in); System.out.println("What's your name? "); String name = sc.nextLine(); // Chaning append method calls together instead of // using String concatenation // "Hello, " + name + ". How are you?" sb.append("Hello, ").append(name).append(". How are you?"); System.out.println(sb.toString()); } }
27th Aug 2017, 2:02 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
StringBuffer and StringBuilder work similarly to each other and have the same methods. append() is used the same way in StringBuffer as it is in StringBuilder. The main difference between the 2 is that StringBuffer is synchronized (thread safe). So, if you are working with mutable Strings on multiple threads then use StringBuffer. Otherwise, if you need to mutable Strings use StringBuilder as it will be faster in most cases. If you only need to make a few or set amount of changes to your Strings then go ahead and just use String. Basically, if you're changing a string across threads use StringBuffer. If you need to make an unknown amount of changes to a string on the same thread, like in a loop, then you may want to use StringBuilder. If you're not making any changes to a string or if you will only making a few changes to that string then use String.
27th Aug 2017, 2:25 AM
ChaoticDawg
ChaoticDawg - avatar