Strings are a sequence of characters and are used often in Java. They are treated as objects and we can do lots of different things to manipulate them! Let’s dive in a bit further. Open up Eclipse and create a new class called Strings.java. In this lesson, I’ll show you how to create a String and what cool things we can do with them.

Creating a String

To create a String, we simply write this:

Seems fairly straight forward right? Let’s see what else we can do with Strings.

Concatenating Strings

We can also join Strings together or concatenate them together to make new Strings. Here’s an example:

Here, we take our two variables “Will” and “Velida” from earlier and make a new variable called fullName that has the value of “Will Velida”.

Getting the length of a String

Because Strings are objects in Java, we can use methods to gain information about those objects. These are also known as accessor methods. We will go through methods late on in this course, but for now let’s explore one of them. We can get the length of a String by using .length(). This method will return the number of characters contained in a String. So for example, let’s call .length() on our fullName variable like this:

Printing a String

Remember the first lesson where we printed out a String to the console. We essentially printed out the value of a String object to the console. We can do this for any String. So for our program, we can do this:

These lines of code will produce the following output:

Formatting our variables in a String

The above examples are great for when we know the exact values of our variables, but this won’t always be the case. What if we want to produce a String when we don’t know the exact values of our variables?

What we can do is use a formatted String that we can reuse in our programs. Here’s an example:

So if the values of our float, int and String change, our formattedString changes with those values. Our output will be:

There is so much we can do with Strings and I’d suggest that you look here for what methods we can use with Strings. But for now, let’s move onto our next topic Java with Maths.