Java Data Type Tutorial - Java String Characters








Character at an Index

You can use the charAt() method to get a character at a particular index from a String object. The index starts at zero.

The following code prints the index value and the character at each index in a string of "JAVA2S.COM":

public class Main {
  public static void main(String[] args) {
    String str = "JAVA2S.COM";
//from w  w  w.  j a  v a2s  .  com
    // Get the length of string
    int len = str.length();

    // Loop through all characters and print their indexes
    for (int i = 0; i < len; i++) {
      System.out.println(str.charAt(i) + "  has  index   " + i);
    }

  }
}

The code above generates the following result.





Testing a String to be Empty

To test whether a String object is empty. The length of an empty string is zero.

There are three ways to check for an empty string:

  • isEmpty() method.
  • equals() method.
  • Get the length of the String and check if it is zero.

The following code shows how to use the three methods:

public class Main {
  public static void main(String[] args) {
    String str1 = "Hello";
    String str2 = "";
/*ww  w  .  j ava 2s.  com*/
    // Using the isEmpty() method
    boolean empty1 = str1.isEmpty(); // Assigns false to empty1
    boolean empty2 = str2.isEmpty(); // Assigns true to empty1

    // Using the equals() method
    boolean empty3 = "".equals(str1); // Assigns false to empty3
    boolean empty4 = "".equals(str2); // Assigns true to empty4

    // Comparing length of the string with 0
    boolean empty5 = str1.length() == 0; // Assigns false to empty5
    boolean empty6 = str2.length() == 0; // Assigns true to empty6

  }
}




Changing the Case

To convert the content of a string to lower and upper case, use the toLowerCase() and the toUpperCase() methods, respectively.

String str1 = new String("Hello"); // str1  contains "Hello" 
String str2 = str1.toUpperCase();   // str2 contains "HELLO" 
String str3 = str1.toLowerCase();   // str3 contains "hello"