Most languages provide a way to work with Strings, and Java is no exception.
Java sometimes provides several ways to create, as well as work, with strings. We’ll look at the most common ways to work with Strings that you will experience.
Creating a String
Where you get a string will vary based upon your applications. Strings often come from reading a file, console inputs, and other methods. Likewise you can create them, either by specifying and a String object, or assigning it a literal string.
// create by defining a new object
String s1 = new String("Hello");
// create by assigning a literal value
String s2 = "World";
In both cases, a String object is created, and you can access method of the object. If you simply put the object it is treated as the string of characters, however, place a . and you can access any of it’s methods, as you see below.
System.out.println(s1 + " has " + Integer.toString(s1.length()) + " characters in it.");
System.out.println(s2 + " has " + Integer.toString(s2.length()) + " characters in it.");
Notice that we are using Integer.toString( <int value> )
to convert the numeric value to a string so we can put it all into the print line method.
Concatenating Strings
Concatenating strings, is simply the joining of strings together. Java provides two different ways to concatenate strings.
First is the +
operator. We see that in the example above where we “add” strings together to get the value we are looking for.
There is also a concat()
method. Using this method means that you need to pass in a new string to concatenate with the existing string. It will return the combination of those two strings, it does not store the concatenated value in the existing string, as can bee seen here.
Using the values previously established:
System.out.println(s1.concat(s2));
System.out.println(s1);
Instead you would need to do something like the following:
s1 = s1.concat(" " + s2);
Notice how there is a combination of the concatenation methods, and now s1
holds the new value because it was assigned to it.
What is interesting, is when you concatenate a string, it returns a string, which means that you can concatenate a new string with that, as you can see from the following example:
System.out.println(s2.concat(" has ").concat(Integer.toString(s2.length())).concat(" characters in it."));
Trimming White Space
Often Strings get white space due to it being entered by a user, or improperly parsed/loaded into the source material.
As such, it is important to be able to remove those white space characters at the beginning and ending of a string, while leaving the ones in the middle.
String trim = " This is an example. ";
trim = trim.trim();
System.out.println(trim);
Notice how just as with concat()
, you have to set the new value. It is not automatically made to the string itself.
There are three other methods that do something similar. The strip()
method removes all leading and trailing white space just like trim()
.
The stripLeading()
method only removes leading white space characters, and stripTrailing()
removes trailing white space characters.
Substrings
Often we need to look at parts of a string, rather than the whole string. Java has the overloaded substring()
method which does that for us.
If you pass one integer to substring()
it starts at that index, and returns the rest of the string.
System.out.println("This is the way.".substring(8));
// prints out "the way."
If you pass two arguments, then you get the value between the beginning and ending index.
System.out.println("This is the way.".substring(5,7));
// prints "is"
Note: Since this is using a beginning and ending index, you can assume that it wouldn’t work, and you would be correct. An exception would be generated. If your beginning and ending indexes are the same, an empty string is returned.
Contains
The contains()
method checks to see if a string is contained within the parent string. It will return a boolean value.
Checking for Equality
You can check for equality for two strings by using the equals()
method. Alternatively, if you don’t care about case, you can use the equalsIgnoreCase()
method. With both methods you will need to pass in a string to compare it with.
String s3 = "testing";
String s4 = "testing";
String s5 = "TESTING";
System.out.println(s3.equals(s4)); // true
System.out.println(s3.equals(s5)); // false
System.out.println(s3.equalsIgnoreCase(s5)); // true
You can use the ==
, or equality operator, although it is not recommended.
Joining and Splitting Strings
You might wonder why Java has to similarly named methods, concat and join. However, they do different things.
For example concat takes and joins two (and only two) strings.
However, join allows you to pass in multiple items to join together. The first element is a delimiter, which means, what will separate the elements you are joining. So if you want to produce a list of items, you can pass in a ", "
and then the items in the list.
String groceries = "Grocery List: " + String.join(", ", "eggs", "milk", "grapefruit");
System.out.println(groceries);
// prints: Grocery List: eggs, milk, grapefruit
The split()
method does the exact opposite of a join. It splits data along a delimiter. It takes a Regular Expression as a parameter to determine how to split the string. This is especially useful when reading in data from an outside source, such as a CSV (comma separated value) file.
String list = "Wimberly, Walter, Assistant Professor";
String arr[] = list.split(",");
for(String x : arr) {
System.out.println(x.trim());
}
Getting an Element at an Index
The charAt()
method returns the character of a string as a specific index.
System.out.println(s4.charAt(4));
You will need to remember that Java is a zero (0) based index language, so the index of 4 is actually the fifth character in the string.
If you pick an index that is larger than the length of the string, it will cause an exception to be thrown.
Other Methods
Of course there are other functions and methods that will allow you to do a variety of things such as reduce to all lower case, or increase to all upper case, get the length of a string and more.
Working with Strings in Java was originally found on Access 2 Learn