Skip to content
Code To Live By » Java Tutorial » Strings in Java

Strings in Java

  • by

We have touched on Strings in some of our previous entries in this tutorial, however there are enough things that can be done with Strings that I felt they warranted their own post. Being able to manipulate Strings and understand the concepts surrounding them will be valuable regardless of where you decide to apply your development skills.

Before we begin I will say that this post will differ from some of the other posts in this series. This will mostly be highlighting methods that are available through the String class within Java rather than introducing new concepts. For a more complete list you may wish to visit Oracle’s documentation on the String class. In any case, I would recommend visiting some of Oracle’s documentation at some point while you read through this post as being able to read technical documentation will prove to be an extremely valuable skill in your growth as a developer.

Recap

Let’s quickly refresh on what we know so far about Strings.

Strings variables can be created by using the String data type.

String helloWorld = "Hello World!"

We can add String variables together, a process known as “Concatenation.”

String helloWorld = "Hello" + " " + "World!";

People may tell you that you should concatenate Strings using something such as a StringBuilder. I personally tend to err on the side of readability, as the performance gains tend to be minimal unless you are dealing with a high volume of Strings. If you would like to read further on the topic I found this writeup on Redfin to be very informative.

Analyzing Strings

Lets say we receive a String but we aren’t sure what is in it. Perhaps we received it from reading in a txt file and we don’t actually know what it contains? We can use some of the following methods to help us figure out what we are looking at:

MethodDescription
length()Return the length of the String
equals(Object)Return whether the String has the same content as a particular Object
contains(CharSequence)Returns whether the String contains a particular sequence of characters
startsWith(String)Return whether the String starts with a particular String
endsWith(String)Return whether the String ends with a particular String
charAt(int)Return the character at the given index
indexOf(String)Search for a particular String and return the index if we find it. Return -1 if we don’t find it.
lastIndexOf(String)Search for a particular String and return the index if we find it, starting from the end of the String. Return -1 if we don’t find it.

Let’s go through a small example to try to tie some of this together. Let’s say we wanted to search for an exclamation point (or whatever other character) in a given String. We could use something like this:

String example = "This an example String!";
if (example.contains("!")) {
	int exclamationIndex = example.indexOf("!");
	System.out.println("We found an exclamation mark at index " + exclamationIndex);
}

Or, since indexOf will return a -1 if it didn’t find what we were looking for, we could do something like this:

String example = "This an example String!";			
int exclamationIndex = example.indexOf("!");
if (exclamationIndex >= 0) {
	System.out.println("We found an exclamation mark at index " + exclamationIndex);
}

In either case we should see the following output:

We found an exclamation mark at index 22
== vs .equals()

You may have noticed the presence of an equals() method and said something along the lines of: “Wait a minute, I already knew about that from Code To Live By’s page on Operators.” There is actually a very important different between these two when it comes to Strings as they have two different definitions of “equal.”

When it comes to Strings, “==” will test whether two Strings are equal by reference. Essentially that means are they stored in same place? equals() will test whether two Strings are equal by value. Do these two strings contain the same sequence of characters? When you are comparing Strings, you will very likely be trying to compare the values of the String rather than caring about their references, but this is a very important distinction that can trip you up if you are not aware of the differences.

String string1 = new String("I am String");
String string2 = new String("I am String");
		
// True, it is the same variable
System.out.println(string1 == string1);
// False, they are different references
System.out.println(string1 == string2);
// True, they have the same content
System.out.println(string1.equals(string2));

Manipulating Strings

The following methods give us options to manipulate Strings:

MethodDescription
substring(int, int)Get the characters between the two indices
split(String)Split a String based on a “Regular Expression”
strip()Remove leading or trailing whitespace
replace(char, char)Replace all instance of one character with another

It’s important to note that for methods where you are modifying Strings, the result will be returned to you as a new String. Strings in Java are “immutable” meaning they cannot be modified after they have been initialized.

.Again, here’s a small example to quickly demonstrate the usage:

String example = "This an example String!";
String[] splitExample = example.split(" ");
for (String splitString : splitExample) {
	if (splitString.length() > 5) {
		splitString = splitString.substring(0, 5);
	}
	System.out.println(splitString);
}

This would give us the following output:

This
an
examp
Strin

Interpolation

Interpolation essentially means to use placeholders within a String and then replace them with your value. We can accomplish String interpolation in Java by using the format(String, Object) method in the String class. To demonstrate this we can return to the example we used earlier regarding finding an exclamation mark.

String example = "This an example String!";
if (example.contains("!")) {
	int exclamationIndex = example.indexOf("!");
	System.out.println("We found an exclamation mark at index " + exclamationIndex);
}

If we were so included we could use Interpolation rather than Concatenation

String example = "This an example String!";
if (example.contains("!")) {
	int exclamationIndex = example.indexOf("!");
	System.out.println(String.format("We found an exclamation mark at index %s", exclamationIndex));
}

We are using %s as a placeholder value which String.format will replace with our exclamationIndex

Now you know how to manipulate Strings in Java!

Leave a Reply

Your email address will not be published. Required fields are marked *