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:
1 | String 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:
1 | String str = "Hello, World!" ; |
2 | for ( int i = 0 ; i < str.length( ); i++ ) |
3 | System.out.print( str.charAt( i ) ); |
|
There are many string methods available, for example,
toUpperCase()
and
toLowerCase()
:
1 | String txt = "Hello World" ; |
2 | System.out.println( txt.toUpperCase( ) ); |
3 | System.out.println( txt.toLowerCase( ) ); |
|
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.
1 | String txt = "Please locate where 'locate' occurs!" ; |
2 | System.out.println( txt.indexOf( "locate" ) ); |
|
The + operator can be used between strings to add them together to make a new string.
This is called concatenation:
1 | String firstName = "John" ; |
2 | String lastName = "Doe" ; |
3 | System.out.println( firstName + " " + lastName ); |
|