Each +
-operation forms a new string.
String numbers = ""; // creating a new string: ""
int i = 1;
// first creating the string "1" and then the string "1\\n"
numbers = numbers + i + "\\n";
i++;
// first creating the string "1\\n2" and then the string "1\\n2\\n"
numbers = numbers + i + "\\n"
i++;
// first creating the string "1\\n2\\n3" and then the string "1\\n2\\n3\\n"
numbers = numbers + i + "\\n"
i++;
// and so on
numbers = numbers + i + "\\n"
i++;
System.out.println(numbers); // outputting the string
In the previous example, a total of nine strings is created.
String creation - although unnoticeable at a small scale - is not a quick operation. Space is allocated in memory for each string where the string is then placed.
Java's ready-made StringBuilder
class provides a way to concatenate strings without the need to create them.
StringBuilder numbers = new StringBuilder();
for (int i = 1; i < 5; i++) {
numbers.append(i);
}
System.out.println(numbers.toString());
A regular expression defines a set of strings in a compact form.
Regular expressions are used, among other things, to verify the correctness of strings. We can assess whether or not a string is in the desired form by using a regular expression that defines the strings considered correct.
We can then use the matches
method of the String
class, which checks whether the string matches the regular expression given as a parameter.
System.out.print("Provide a student number: ");
String number = scanner.nextLine();
if (number.matches("01[0-9]{7}")) {
System.out.println("Correct format.");
} else {
System.out.println("Incorrect format.");
A vertical line indicates that parts of a regular expressions are optional.
For example, 00|111|0000
defines the strings 00
, 111
and 0000
. The matches
method returnstrue
if the string matches any one of the specified group of alternatives.
String string = "00";
if (string.matches("00|111|0000")) {
System.out.println("The string contained one of the three alternatives");
} else {
System.out.println("The string contained none of the alternatives");
}
The regular expression 00|111|0000
demands that the string is exactly it specifies it to be - there is no "contains" functionality.
You can use parentheses to determine which part of a regular expression is affected by the rules inside the parentheses.
Parentheses allow us to limit the option to a specific part of the string.