2.1 Strings

Strings are a sequence of characters. In the Java programming language, string is an object rather than a primitive data type. The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

 String greeting = "Hello world";

In this case, "Hello world" is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world.

Every character in a string has a specific position in the string. The position of the first character is 0, the position of the second character is 1, and so on. The length of a string is the number of characters in it.

String Hello World

Character in the string

H e l l o   W o r l d
Position of the character
in the string
0 1 2 3 4 5 6 7 8 9 10

 

String Arithmetic

The + operator can concatenate two or more strings. In previous sections, you have seen statement that look something like this:

String name = "David";
System.out.println("Your name is " + name);

These two lines result in the display of the following text:

Your name is David

The + operator combines strings, other objects, and variables to form a single string. In the preceding example, the literal "Your Name is " is concatenated to the value of the String object name.

If any part of a concatenation operation is a String or a string literal, all elements of the operation will be treated as if they were strings:

System.out.println("Your roll number is " + 19);

This produces the output Your roll number is 19, as if the integer literals 19 is string.