Java concatenation strings and static strings

I'm trying to better understand the strings. I basically make a program that requires a lot of lines. However, many lines are very similar and simply require a different word at the end of the line.

eg.

String one = "I went to the store and bought milk"
String two = "I went to the store and bought eggs"
String three = "I went to the store and bought cheese"

So my question is: which approach works best when working with strings? The combination of two lines together can have any advantages only if there are static lines, for example, in performance or memory management?

eg.

String one = "I went to the store and bought "
String two = "milk" 
String three = "cheese"
String four = one + two
String five = one + three

I'm just trying to find the best way to handle all of these lines. (If this helps to put the few lines that I use, I currently have 50, but the number can exceed a huge amount)

+4
source share
7

, - . , . , Strings, String , . .

+2

,

String openingSentence = "I went to the store and bought";

, , :

String[] thingsToBeBought = { "milk", "water", "cheese" .... };

foreach .

0

, . -

final static String s = "static string";

, , , . , , , , , :

// not as good performance wise since they are generated at runtime
String four = one + two
String five = one + three
0

Java, (, "+" ), String, . , - StringBuilder StringBuffer.

, URL-, , , StringBuilder/StringBuffer, URL-, .

0

URL-, StringJoiner ( , JAVA 8). , StringBuilder ( ) "/" .

StringJoiner myJoiner = new StringJoiner("/")
0

, , , . , , .

:

String action = "I went to the store and bought ";
String [] items = {"milk", "eggs", "cheese"};

for (int x = 0; x< items.length; x++){
     System.out.println(action + items[x]);
}
0

, , , - , . , - Java , , .

2 +, String, GC'd. , a = "1" b = "2", do String s = "s" + a + b;, Java String "s1", , "s12". , - StringBuilder. ( , .)

If you don't like string formatting , not just concatenation , use MessageFormator String.format(). It is prettier and avoids intermediate lines created using the operator +. So, something like String urlBase = "http://host/res?a=%s&b=%s"; String url = String.format(urlBase, a, b);where aand bare the parameters of the query string.

0
source

Source: https://habr.com/ru/post/1623307/


All Articles