String processing in Java
Introduction
String is one of class that is mostly used in Java. This tutorial will show you some common ways to process String.
Concatenate string
There are some approaches to concatenate string in Java.
Using “+” operator
String a = "Hello" String b = " world" String c = a + b // c = "Hello world"
Actually, when concatenate String using
+
operator, Java compiler will convert those operations into something more efficient. Above statements may be converted into:String c = new StringBuilder(a).append(b).toString(); // c = "Hello world"
Using concat() method
String a = "Hello" String b = " world" String c = a.concat(b) // c = "Hello world"
Using StringBuilder
Even the Java compiler will convert string concatenation operator ( + ) into a StringBuilder chain, there are cases when we should use StringBuilder over string concatenation using (+) operator. That when we try to concatenate string in a loop.
String[] myStrArr = {"hello", "world", "how", "are", "you", "today"} StringBuilder sb = new StringBuilder(); for (String s : myStrList) { sb.append(s); } String c = sb.toString();
Convert a List<String> into String
Using String.join()
String message = String.join("-", "I", "am", "a", "newbie", "Java", "developer"); // message: I-am-a-newbie-Java-developer
Using Stream API
String combinedCountry = countries.stream().collect(Collectors.joining("-")); // combinedCountry = "Belarus-Colombia-Denmark-Egypt-Germany-Hong Kong"
Convert a String into array of String
String myString = "Some thing interesting";
String[] parts = string.split(" ");
String part1 = parts[0]; // Some
String part2 = parts[1]; // thing
String part3 = parts[2]; // interesting
Convert a string representaion of integer into integer
Use Integer.parseInt()
String myString = "1357"; int myInt = Integer.parseInt(myString);
Note that, this will throw NumberFormatException if input is not a valid number
int myInt = Integer.parseInt("not valid number"); // NumberFormatException will be thrown
Use Integer.valueOf()
String myString = "1357"; int myInt = Integer.valueOf(myString);
NoteThe difference betwwen Integer.valudOf() and Integer.parseInt():
- Integer.valueOf() return a new or cached instance of
java.lang.Integer
class- Integer.parseInt() returns primitive
int