Java Strings
In Java programming language, strings are like the building blocks of a language. They allow us to work with text, whether it's a simple "Hello, World!" or a complex document. Strings are everywhere in our code, and understanding how to use them effectively is fundamental for any Java developer.
The String type
String
is a reference type consisting of characters. It is one of the most widely used types in Java. For example, the string "Hello, Java" is a sequence of characters that includes 11 total characters, including one space.
This data type has some unique features:
- String is immutable type: it's impossible to change a character in a string;
- it has methods for getting individual characters and extracting substrings;
- individual characters can be accessed by indexes, the first character has the index 0, the last one has the index length of the string – 1;
- non-primitive type.
A string literal is surrounded by a pair of double quotes, for instance:
String simpleString = "It is a simple string"; // a simple string
System.out.println(simpleString); // it prints "It is a simple string"
String anotherString = "This is\na multiline\nstring"; // a string with escape sequences
System.out.println(anotherString); // it prints the result in several lines
A string can represent a long character sequence (text) or represent only one or zero characters.
String strangeText = "aaaaaaaaaaaassssssssssss gggggggggggggggggggg ddddddddddd qqqqqq ffff";
String emptyString = ""; // An empty string
String s = "s"; // a string consisting of one character
A string can be null
. It means no value was assigned.
String nullString = null; // it is null
Another way to create a String
variable is by using the new
keyword.
String str = new String("my-string"); // it creates a string object and assigns it to the variable
Any string has two useful methods:
length()
returns the number of characters in the string;charAt(int index)
returns a character by its index;
Here is an example:
String s = "Hi, all";
int len = s.length(); // the string length is 7
char theFirstChar = s.charAt(0); // 'H' has the index 0
char theFifthChar = s.charAt(4); // 'a' has the index 4
char theLastChar = s.charAt(s.length() - 1); // 'l' has the index 6
You can easily get a character within a string by the index, but you can't change characters because strings are immutable in Java.
Useful methods of strings
The standard library of Java provides a lot of useful methods for processing strings:
isEmpty()
returnstrue
if the string is empty, otherwise,false
;toUpperCase()
returns a new string in uppercase;toLowerCase()
returns a new string in lowercase;startsWith(prefix)
returnstrue
if the string starts with the given stringprefix
, otherwise,false
;endsWith(suffix)
returnstrue
if the string ends with the given stringsuffix
, otherwise,false
.contains(...)
returnstrue
if the string contains the given string or character;substring(beginIndex, endIndex)
returns a substring of the string in the range:beginIndex
,endIndex - 1
;replace(old, new)
returns a new string obtained by replacing all occurrences ofold
withnew
, where old can be a character or string.replaceAll(old, new)
returns a new string obtained by replacing all occurrences ofold
withnew
, whereold
is not a string or character but a regular expression.trim()
returns a copy of the string obtained by omitting the leading and trailing whitespace. Note that whitespace includes not only the space character, but mostly everything that looks empty: tab, carriage return, newline character, etc.
Take a look at the following example to better understand these methods:
String text = "The simple text string";
boolean empty = text.isEmpty(); // false
String textInUpperCase = text.toUpperCase(); // "THE SIMPLE TEXT STRING"
boolean startsWith = textInUpperCase.startsWith("THE"); // true
/* Replace all space characters with empty strings */
String noSpaces = textInUpperCase.replace(" ", ""); // "THESIMPLETEXTSTRING"
// Replace all space characters with "_" in original text
String phoneNumber = text.replaceAll(" ", "_"); // "The_simple_text_string"
String textWithWhitespaces = "\t text with whitespaces !\n \t";
String trimmedTex = textWithWhitespaces.trim(); // "text with whitespaces !"
To learn more about different methods and arguments you can check out the official documentation.
Exceptions when processing strings
When working with strings, there can be several exceptions:
1. NullPointerException
— If a string is null
and you call a method of the string, it throws a NullPointerException
.
String s = null;
int length = s.length(); // it throws NullPointerException
2. StringIndexOutOfBoundsException
— If you try to access a non-existing character by an index then this exception occurs.
String s = "ab";
char c = s.charAt(2); // it throws StringIndexOutOfBoundsException because indexing starts with 0
We will consider how to handle different types of exceptions later.
Concatenating strings and appending values to a string
Two strings can be concatenated using the +
operator or the concat
method. Both approaches lead to the same results.
String firstName = "John";
String lastName = "Smith";
// concatenation using the "+" operator
String fullName1 = firstName + " " + lastName; // "John Smith"
// concatenation using the concat method
String fullName2 = firstName.concat(" ").concat(lastName); // "John Smith"
When we concatenate two strings a new string is created (because strings are immutable). A common question that arises is whether the order of concatenation matters. In the general case str1 + str2
is not the same as str2 + str1
because concatenation is not a commutative operation.
It's possible to add values of different types to a string. The value will be automatically converted to a string. See an example below.
String str = "str" + 10 + false; // the result is "str10false"
In the example above, the order of execution is:
- "str" + 10 => "str10"
- "str10" + false => "str10false"
Let's look at a more complex example:
String shortString = "str";
int number = 100;
String result1 = shortString + number + 50; // the result is "str10050"
String result2 = number + 50 + shortString; // what is the result2?
The value of result2
will be 150str
, because, first, we calculate the sum of number
and 50
and then concatenate it with str
. The order of operations is important.
How to compare strings correctly?
Since String
is a reference type you shouldn't compare strings using the ==
or !=
operators. In this case, only addresses will be compared, but not actual values.
String
has two convenient methods for comparing the equivalence of the actual content of one string with the content of another string: equals(other)
and equalsIgnoreCase(other)
.
Take a look at the example below:
String first = "first";
String second = "second";
String anotherFirst = "first";
String secondInUpperCase = "SECOND";
System.out.println(first.equals(second)); // false, the strings have different values
System.out.println(first.equals(anotherFirst)); // true, the strings have the same value
System.out.println(second.equals(secondInUpperCase)); // false, the strings have different cases
System.out.println(second.equalsIgnoreCase(secondInUpperCase)); // true, it ignores cases
Strings and arrays
It's possible to convert between strings and character arrays using special methods like valueOf()
and toCharArray()
.
char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F' };
String stringFromChars = String.valueOf(chars); // "ABCDEF"
char[] charsFromString = stringFromChars.toCharArray();
// { 'A', 'B', 'C', 'D', 'E', 'F' }
String theSameString = new String(charsFromString); // "ABCDEF"
There is another way to turn a string into a array of characters. Take a look:
String text = "Hello";
String[] parts = text.split(""); // {"H", "e", "l", "l", "o"}
Here we used a much more concise method that splits a string into parts. Let's explore it in more detail!
Splitting the string
A string can be divided into an array of strings based on a delimiter. To perform this, we call the split
method, which divides the string into substrings using a separator. In the previous example, we used the ""
delimiter, which automatically splits a string into smaller elements (substrings), where each element consists of a single character.
If the delimiter is specified, the method returns an array of all the substrings. Note that the delimiter itself is not included in any of the substrings:
String sentence = "a long text";
String[] words = sentence.split(" "); // {"a", "long", "text"}
Let's try to split an American phone number into the country code, the area code, the central office code, and other remaining digits:
String number = "+1-213-345-6789";
String[] parts = number.split("-"); // {"+1", "213", "345", "6789"}
Keep in mind that all these parts are still strings no matter what they look like!
Choose your delimiter wisely, otherwise you might get some sentences that start with a space:
String text = "That's one small step for a man, one giant leap for mankind.";
String[] parts = text.split(",");
// {"That's one small step for a man", " one giant leap for mankind."}
You can choose any delimiter you prefer, including a combination of spaces and words:
String text = "I'm gonna be a programmer";
String[] parts = text.split(" gonna be "); // {"I'm", "a programmer"}
As you can see here, the split
method is also a good tool to get rid of something you don't need or don't want to use.
Iterating over a string
It's possible to iterate over the characters of a string using a loop (while, do-while, for-loop).
See the following example:
String scientistName = "Isaac Newton";
for (int i = 0; i < scientistName.length(); i++) {
System.out.print(scientistName.charAt(i) + " ");
}
In strings, just like in arrays, indexing begins from 0
. In our example, the for-loop iterates over the string "Isaac Newton"
. With each iteration, the charAt
method returns the current character at the i
index, and that character is then printed to the console, followed by a blank space.
Here is what the code snippet displays as a result:
I s a a c N e w t o n
Conclusion
A String
is a sequence of characters, encapsulated by double quotes. It represents text-based information and can include letters, digits, whitespaces, and other characters altogether.
String
in Java is an immutable data type, meaning its content cannot be changed after creation. Any manipulation of a String
results in the creation of a new String
. Strings can be created using the new keyword. Java's standard library offers numerous methods for string manipulation. When comparing strings, avoid using the ==
or !=
operators, as they compare references, not values. Instead, use the equals
and equalsIgnoreCase
methods to compare the content of strings.
You can convert between a string and an array using the valueOf()
and toCharArray()
methods or divide a string into substrings with the help of the split()
method. You can also iterate over the characters of a string using a loop. This process of manipulating strings with various methods will help you solve different tasks and improve your programming experience.