Basics

In this section, we explore some of the basic string operations

Declaring and initializing

Here is how to declare a string variable:

String s1;

Just like any other variable that has been declared but not initialized, s1 currently has no value (and we will get a compilation error if we try to use s1 before initializing it).

We can give s1 an initial value like this:

s1 = "hello";

Or, we can declare and initialize a string at the same time like this:

String s1 = "hello";

Concatenation

String concatenation is pushing two strings together with the + sign – we’ve seen how to concatenate strings when printing things out. Here are some more examples:

int age = 7;
char initial = 'L';
String first = "Bob";
String last = "Jones";

String about = first + " " + initial + ". " + last + ", age " + age;

The string about will now hold the value “Bob L. Jones, age 7”.

Notice that we can concatenate types other than strings, like ints and chars. In fact, we can do this with any variable type. The only confusion is when we’re concatenating several ints – does the + mean concatenation or integer addition?

The answer, of course, is that it can mean both. The compiler interprets expressions by reading from left to right. If it sees a + and has only seen primitive types (like int a double) so far, it will assume you mean mathematical addition. If it has seen a string or object already on that line, it will assume you mean string concatenation. Here are some examples:

//evaluates to "11 hi"
String s1 = 4+7+" hi ";

//evaluates to "hi 47"
String s2 = "hi "+4+7; 

//evaluates to "11 hi 47"
String s3 = 4+7+" hi "+4+7; 

Length

You can get the number of characters in a string by accessing its length. Here’s how:

String s = "Hello";

//count will be set to 5
int count = s.length();