Strings


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:

 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:

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

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

 String txt = "Hello World";
 System.out.println( txt.toUpperCase( ) );     // Output: HELLO WORLD
 System.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.

 String txt = "Please locate where 'locate' occurs!";
 System.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:

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




      Why do cows wear bells?    
      Because their horns don’t work.