More Strings in Java

In this section we give several demonstrations of the Java String class. We show how to obtain a character at a given index (position) within the string and how to search for characters within a string. We then discuss the equals method for testing if two Strings contain the same data.

Accessing characters within a String

Our first program shows how to retrieve the characters using the CharAt method and find the index of a given character with in a string using the indexOf and lastIndexOf methods. The important points to note here are:
  • The number of characters in the string is provided by the length method.
  • The characters contained in the string are positioned starting from index 0. This means that the last character of the string is at index length-1, where length is the number of characters in the string.
  • All characters occupy the same space in the string. So that characters '\t' (the tab character) and 'a' are both one character.
  • If an attempt is made access a character using the charAt method beyond the range of a string the method return -1.
  • If a character is not found then then the search methods, indexOf, lastIndexOf return -1.
The fact that these method return -1 in these conditions is useful, it enables a program to take intelligent action using a flow control statement such as the if statement.
/**
This program demonstrates the Java String class.
It shows the character index methods and also the conversion from integers to strings.
*/
class  MoreStringsJava2
{

 
public static  void main(String[] args)
  {
   
   
int iFirstIndex;
   
int iNextIndex;
   
int iLastIndex;

   
//Index operations
   
   
System.out.println("Note the \\ character is only one char length long");
    String str1 =
"The \\index\\ methods provide the positions of characters.";
    System.out.println
(str1);
   
   
//Note how the return value from a method, in this case the length() method,
    //can be used directly without assignment to an integer variable.
   
System.out.println("The number of characters in the string str1 is :"+str1.length());
    System.out.println
("The first character is :"+str1.charAt(0));
    System.out.println
("The last character is  :"+str1.charAt(str1.length()-1));
   
 
    iFirstIndex=str1.indexOf
(' ');
    System.out.println
("The first space is at index :"+iFirstIndex);
    iNextIndex=str1.indexOf
(' ',iFirstIndex);
   
    System.out.println
("The next space is at index :"+iFirstIndex+1);
    iLastIndex=str1.lastIndexOf
('\\');
    System.out.println
("The last \\ character is at :"+iLastIndex);
    System.out.println
("The next last \\ character is at :"+str1.lastIndexOf('\\',iLastIndex-1));
    System.out.println
("Seaching beyond the range of the string returns  -1:"+str1.indexOf('\\',199));
    System.out.println
("As does search for non-existent characters :"+str1.indexOf('?'));

     
 
}
}

To compile and run from the command line:
$ java MoreStringsJava2
Note the \ character is only one char length long
The \index\ methods provide the positions of characters.
The number of characters in the string str1 is :56
The first character is :T
The last character is  :.
The first space is at index :3
The next space is at index :31
The last \ character is at :10
The next last \ character is at :4
The next last \ character is at :-1
$ javac MoreStringsJava2.java
$ java MoreStringsJava2
Note the \ character is only one char length long
The \index\ methods provide the positions of characters.
The number of characters in the string str1 is :56
The first character is :T
The last character is  :.
The first space is at index :3
The next space is at index :31
The last \ character is at :10
The next last \ character is at :4
Seaching beyond the range of the string returns  -1:-1
As does search for non-existent characters :-1
$ 

String equality

Two strings are equal if and only if they contain the exactly the same characters in the same order. To test if two strings are equal always use the "equals" method of the String class. This method performs a character by character comparison. The String class, as with other objects, makes available use of a second form of equality, reference equality. This form of equality uses the == operator. The operator tests if both its operand are the same underlying object. Confusing these two forms of equality can result in some very subtly bugs. Our next program demonstrates the difference between the two forms of equality, its output is at first sight surprising.
/**
This program demonstrates the Java String class.
It shows the difference between the equals method and the == operator.
*/
class  StringEqulityJava
{

 
public static  void main(String[] args)
  {
   
//First we declare 4 strings.
   
String str1 ="I am a string";
    String str2 =
"I am a string";
    String str3 =
"I am a string as well";
    String str4 =
new String ("I am a string");
   
   
//We show them.
   
System.out.println("str1 is:"+str1);
    System.out.println
("str2 is:"+str2);
    System.out.println
("str3 is:"+str3);
    System.out.println
("str4 is:"+str4);
   
   
//The equals method works by comparing each characters in the strings.
   
System.out.println("Is str1 equal to str1?:"+str1.equals(str1));   
    System.out.println
("Is str1 equal to str2?:"+str1.equals(str2));
    System.out.println
("Is str2 equal to str1?:"+str2.equals(str1));
    System.out.println
("Is str1 equal to str3?:"+str1.equals(str3));
    System.out.println
("Is str1 equal to \'I am a string\'?:"+str1.equals("I am a string"));
    System.out.println
("Is str1 equal to \'I am a string\'?:"+str1.equals("I am a"+" string"));
    System.out.println
("Is str1 equal to \'Iamastring\'?:"+str1.equals("Iamastring"));
    System.out.println
("Is str1 equal to str4?:"+str1.equals(str4));
   
   
//The object == operator tests whether the two objects are the same.
   
System.out.println("Is str1 the same object as str1:?"+(str1==str1));
    System.out.println
("Is str1 the same object as str2:?"+(str1==str2));
    System.out.println
("Is str1 the same object as str3:?"+(str1==str3));
    System.out.println
("Is str1 the same object as \'I am a string\':?"+(str1=="I am a string"));
    System.out.println
("Is str1 the same object as \'I am a string\':?"+(str1=="I am a"+" string"));
    System.out.println
("Is str1 the same object as str4:?"+(str1==str4));
     
 
}
}

To compile and run from the command line:
$ javac  StringEqulityJava.java 
$ java  StringEqulityJava
str1 is:I am a string
str2 is:I am a string
str3 is:I am a string as well
str4 is:I am a string
Is str1 equal to str1?:true
Is str1 equal to str2?:true
Is str2 equal to str1?:true
Is str1 equal to str3?:false
Is str1 equal to 'I am a string'?:true
Is str1 equal to 'I am a string'?:true
Is str1 equal to 'Iamastring'?:false
Is str1 equal to str4?:true
Is str1 the same object as str1:?true
Is str1 the same object as str2:?true
Is str1 the same object as str3:?false
Is str1 the same object as 'I am a string':?true
Is str1 the same object as 'I am a string':?true
Is str1 the same object as str4:?false
$ 

The important points to note here are:
  • The equals method acts as you would expect. equals returns true if the two strings contain exactly data. It makes no difference how the String objects were declared.
  • The == operator return true if the Strings refer to the same underlying object. The Java compiler is very good at collecting together things that have the same data and storing them as a single object. Doing this makes sense with immutable objects, because they can't change as the program runs.
  • In the program str1 and str2 actually refer to the same object. This is not obvious to the beginner Java programmer. Even when a string is declared on the fly as a literal, as in line 36 of the program the compiler is smart enough to merge the two objects.
    System.out.println("Is str1 the same object as \'I am a string\':?"+(str1=="I am a string"));
    
    and even smarter
    System.out.println("Is str1 the same object as \'I am a string\':?"+(str1=="I am a"+" string"));
    
    The compiler does this by evaluating every expressions that it has enough data to do so.

Summary

  • The number of characters in the string is provided by the length method.
  • The characters contained in the string are positioned starting from index 0. This means that the last character of the string is at index length-1, where length is the number of characters in the string.
  • All characters occupy the same space in the string.
  • If an attempt is made access a character using the charAt method beyond the range of a string the method return -1.
  • If a character is not found then then the search methods, indexOf, lastIndexOf return -1.
  • Use the equals method to test if two Stings contain the same data.
  • The Java compiler can merge literals and other immutable program elements into a single object.
  • The == operator should only be used to test if two references refer to the same objects.

    • Previous Using Strings in Java Next The Java if statement

Custom Search

Tutorial
Your First Java Program
Primitive data types in Java
Basic arithmetic operations in Java
Using Strings in Java
More Strings in Java
The Java if statement
Loops in Java
The entire content of this site is subject to copyright.