In this article, we’ll look at a collection of Java String programming tips. The Java String class is one of the most commonly-used classes, so it’s well worth knowing how to perform some of the most common operations.
Testing String equality
The first important thing to know about working with Java strings is how to compare two strings to each other. Unlike comparing primitives in Java, you cannot compare two Java strings like this:
You can do that, but it would be wrong. The correct way to compare two Java strings is to use the String equals method, like this:
Finding one string in another string
A second common String operation is to search one string to see if it contains some other string. For instance, assume you had a string named toppings, and you wanted to see if that string contained the string “pepperoni”. A simple way to do that is to use the indexOf () method, like this:
As a precaution, if you don’t know the case of the string you’re comparing to, you’re always better off converting that string to upper- or lower-case, like this:
One final way to do this, which is very powerful, is to use the matches () method of the Java String class, like this:
Note that with this method you need to pass in a regular expression, that’s why the string in between the parentheses looks like this:
instead of this, which would not work:
Extracting a substring
Another very common Java String class operation is to extract a substring from a String. Java includes a substring () method for just this purpose. Let’s look at a few examples.
If we start with this String declaration:
we can extract everything after the fifth position in the string with this substring statement:
If we print out the new String named sub, the output will look like this:
With the substring () method, we can also limit the length of the substring we extract, so this statement:
can be read as, “Starting after the fifth position in the String, extract the next 20 characters.” If we now print the output of the variable sub, it will look like this:
There are more operations you can perform on strings, including working on Java String arrays, but these are some of the most common String methods you’ll need daily.
Java String array examples
It’s also very common to store strings in Java arrays. There are two main ways to declare a Java String array. In the first approach, you define the array, and give it an initial size, like this:
After that, you populate the array later in your code.
In the second approach, you define and populate your Java String array in one statement, like this:
Either approach will work; It’s just a matter of which array syntax you need for the current situation.