String Class


Strings are used for storing text. A String variable contains a collection of characters surrounded by double quotes. For example, the following example creates a variable of type String and assign it a value:

1String greeting = "Hello";

A String in Java is actually an object, which contains methods that can perform certain operations on strings. For example, the length of a string can be found with the length() method:

1String str = "Hello, World!";
2for ( int i = 0; i < str.length( ); i++ )
3  System.out.print( str.charAt( i ) );      // Output: Hello, World!

There are many string methods available, for example, toUpperCase() and toLowerCase():

1String txt = "Hello World";
2System.out.println( txt.toUpperCase( ) );     // Output: HELLO WORLD
3System.out.println( txt.toLowerCase( ) );     // Output: hello world

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace). Java counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third, etc.

1String txt = "Please locate where 'locate' occurs!";
2System.out.println( txt.indexOf( "locate" ) );      // Output: 7

The + operator can be used between strings to add them together to make a new string. This is called concatenation:

1String firstName = "John";
2String lastName = "Doe";
3System.out.println( firstName + " " + lastName );      // Output: John Doe