OCA Java SE 8 Core Java APIs - Java String Method








String class has many methods.

A string is a sequence of characters and Java counts from 0 when indexed.

The following code shows how each character in the string "animals" is indexed.

a      n      i      m      a      l      s 
0      1      2      3      4      5      6 

length()

The method length() returns the number of characters in the String.

The method signature is as follows:

int length() 

The following code shows how to use length():

public class Main{
   public static void main(String[] argv){
        String string = "animals"; 
        System.out.println(string.length());  // 7 
   }
}

It returns 7 since there are seven characters in string "animals".





charAt()

The method charAt() returns character is at a specific index.

The method signature is as follows:

char charAt(int index) 

The following code shows how to use charAt():

public class Main{
   public static void main(String[] argv){
        String string = "animals"; 
        System.out.println(string.charAt(0));  // a 
        System.out.println(string.charAt(6));  // s 
        System.out.println(string.charAt(7));  // throws exception 
   }
}

Since indexes start counting with 0, charAt(0) returns the "first" character in the sequence.

charAt(6) returns the "seventh" character in the sequence.

charAt(7) should return the "eighth" character in the sequence, but there are only seven characters present.

Java throws an exception.

java.lang.StringIndexOutOfBoundsException: String index out of range: 7





indexOf()

indexOf() finds the first index that matches the desired value.

indexOf can work with an individual character or a whole String as input.

It can start from a requested position.

The method signatures are as follows:

int indexOf(char ch) 
int indexOf(char ch, index fromIndex) 
int indexOf(String str) 
int indexOf(String str, index fromIndex) 

The following code shows how to use indexOf():

public class Main{
   public static void main(String[] argv){
//ww w.  j a v a  2 s.  co m
        String string = "java2s.com java2s.com"; 
        System.out.println(string.indexOf('a'));         
        System.out.println(string.indexOf("al"));        
        System.out.println(string.indexOf('a', 4));      
        System.out.println(string.indexOf("al", 5));     
   }
}

The code above generates the following result.

substring()

substring() looks for characters in a string.

It returns parts of the string.

The first parameter is the zero-based index to start with. The optional second parameter is the end index you want to stop at.

endIndex parameter is 1 past the end of the sequence if you want to stop at the end of the sequence.

The method signatures are as follows:

int substring(int beginIndex) 
int substring(int beginIndex, int endIndex) 

The following code shows how to use substring():

public class Main{
   public static void main(String[] argv){

        String string = "1234567890"; 
        System.out.println(string.substring(3));  
        System.out.println(string.substring(string.indexOf('0')));
        System.out.println(string.substring(3, 4)); 
        System.out.println(string.substring(3, 7)); 
   }
}

string.substring(3) says to take the characters starting with index 3 through the end.

string.substring(string.indexOf('0')) calls indexOf() to get the index rather than hard-coding it.

string.substring(3, 4) takes the characters starting with index 3 until, but not including, the character at index 4.

It returns a String with one character: the one at index 3.

string.substring(3, 7) take the characters starting with index 3 until we get to index 7.

public class Main{
   public static void main(String[] argv){
        String string = "1234567890"; 
        System.out.println(string.substring(3, 3)); // empty string 
        System.out.println(string.substring(3, 2));  // throws exception 
        System.out.println(string.substring(3, 18)); // throws exception 
   }
}

string.substring(3, 3) prints an empty string. Since we start and end with the same index, there are no characters in between.

string.substring(3, 2) throws an exception because the indexes can be backward.

string.substring(3, 18) says to continue until the eighteenth character. There is no eighth position, so Java throws an exception.

toLowerCase() and toUpperCase()

These methods make it easy to convert your data.

The method signatures are as follows:

String toLowerCase() 
String toUpperCase() 

The following code shows how to use these methods:

public class Main{
   public static void main(String[] argv){
        String string = "java2s.com"; 
        System.out.println(string.toUpperCase());  
        System.out.println("Abc123".toLowerCase());
   }
}

toUpperCase() converts any lowercase characters to uppercase in the returned string.

toLowerCase() converts any uppercase characters to lowercase in the returned string.

These methods leave alone any characters other than letters.

The strings are immutable, so the original string stays the same.

The code above generates the following result.

equals() and equalsIgnoreCase()

equals() method checks whether two String objects have the same characters with the same order.

The equalsIgnoreCase() method does the same thing without considering the case.

boolean equals(String str) 
boolean equalsIgnoreCase(String str) 

The following code shows how to use these methods:

public class Main{
   public static void main(String[] argv){

      System.out.println("abc".equals("ABC"));  // false 
      System.out.println("ABC".equals("ABC"));  // true 
      System.out.println("abc".equalsIgnoreCase("ABC"));  // true 
   }
}

The code above generates the following result.

startsWith() and endsWith()

startsWith() and endsWith() methods check whether the provided value matches part of the String.

The method signatures are as follows:

boolean startsWith(String prefix) 
boolean endsWith(String suffix) 

The following code shows how to use these methods:

public class Main{
   public static void main(String[] argv){
        System.out.println("abc".startsWith("a")); // true 
        System.out.println("abc".startsWith("A")); // false 
        System.out.println("abc".endsWith("c")); // true 
        System.out.println("abc".endsWith("a")); // false 
   }
}

The code above generates the following result.

contains()

contains() method looks for matches in the String. The match can be anywhere in the String.

The method signature is as follows:

boolean contains(String str) 

The following code shows how to use these methods:

public class Main{
   public static void main(String[] argv){

        System.out.println("abc".contains("b")); // true 
        System.out.println("abc".contains("B")); // false 
   }
}

We have a case-sensitive search in the String.

The contains() method is a convenience method so you don't have to write str.indexOf(otherString) != -1.

The code above generates the following result.

replace()

replace() method does a simple search and replace on the string.

The method signatures are as follows:

String replace(char oldChar, char newChar) 
String replace(CharSequence oldChar, CharSequence newChar) 

The following code shows how to use these methods:

public class Main{
   public static void main(String[] argv){
        System.out.println("abcabc".replace('a', 'A')); // AbcAbc 
        System.out.println("abcabc".replace("a", "A")); // AbcAbc 
   }
}

The first example uses the first method signature, passing in char parameters. the second example uses the second method signature, passing in String parameters.

The code above generates the following result.

trim()

trim() method removes whitespace from the beginning and end of a String.

whitespace consists of spaces along with the \t (tab), \r (carriage return) and \n (newline) characters.

The method signature is as follows:

public String trim()

The following code shows how to use this method:

public class Main{
   public static void main(String[] argv){
        System.out.println("abc".trim());           // abc 
        System.out.println("\t   a b c\n".trim());  // a b c 
   }
}

The first example prints the original string because there are no whitespace characters at the beginning or end.

The second example gets rid of the leading tab, subsequent spaces, and the trailing newline. It leaves the spaces that are in the middle of the string.

Method Chaining

It is common to call multiple methods on the same String, as shown here:

public class Main{
   public static void main(String[] argv){
//from  w w  w  .j  ava 2 s  .  c o  m
        String start = "AniMaL   "; 
        String trimmed = start.trim();                 
        String lowercase = trimmed.toLowerCase();      
        String result = lowercase.replace('a', 'A');   
        System.out.println(result); 

        result = "AniMaL   ".trim().toLowerCase().replace('a', 'A'); 
        System.out.println(result); 
   }
}

The code above generates the following result.

Example

Remember that String is immutable.

What is the result of this code?

public class Main{
   public static void main(String[] argv){
        String a = "abc"; 
        String b = a.toUpperCase(); // w w w  .  j av a2s . com
        b = b.replace("B", "2").replace('C', '3'); 
        System.out.println("a=" + a); 
        System.out.println("b=" + b); 
   
   }
}

The code above generates the following result.