Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Strings

A string is a sequence of characters: a name, a message, an address. In Java strings have the type String. It is not a primitive type but an object — a value with its own methods for working with text.

Creating a string

A string is written in double quotes. Empty quotes "" give an empty string:

void main() {
    String greeting = "Hello, Java!";
    IO.println(greeting);
}

Output:

Hello, Java!

Joining strings

The + operator joins strings. If one operand is a string, the other is turned into text too:

void main() {
    String name = "Oleg";
    int age = 30;
    IO.println("My name is " + name + ", I am " + age);
}

Output:

My name is Oleg, I am 30

Be careful with numbers: "Sum: " + 2 + 3 gives Sum: 23, because joining goes left to right. Put the arithmetic in parentheses: "Sum: " + (2 + 3).

Length and characters

A method is an action an object can perform. It is called with a dot. The length() method returns the number of characters, and charAt() returns the character at an index — its position counted from zero:

void main() {
    String word = "Java";
    IO.println(word.length());
    IO.println(word.charAt(0));
    IO.println(word.charAt(3));
}

Output:

4
J
a

The last character has index length() - 1. Other string methods are covered in the lesson on string methods.

Special characters

Some characters cannot just be typed into a string. They are written with a backslash, which is called escaping: \n is a line break, \t a tab, \" a quote, \\ the backslash itself:

void main() {
    IO.println("First line\nSecond line");
    IO.println("He said: \"Hello\"");
}

Output:

First line
Second line
He said: "Hello"

Strings do not change

A string cannot be changed after it is created. Methods such as toUpperCase() leave the original string alone and return a new one:

void main() {
    String city = "rome";
    String upper = city.toUpperCase();
    IO.println(city);
    IO.println(upper);
}

Output:

rome
ROME

Common mistake

Do not compare strings with ==: it checks whether both are the same object in memory, not whether they contain the same text. Use the equals() method to compare text:

void main() {
    String a = "Anna";
    String b = new String("Anna");
    IO.println(a == b);
    IO.println(a.equals(b));
}

Output:

false
true

Sometimes == happens to return true — Java reuses identical strings written in code. But strings typed by a user or built from pieces are different objects, so always use equals().

Thanks for reading!

Donate to the site — we work hard for you.