Which of these method of class string is used to extract a single character from a string object O Chatat O charAt O Chatat ?

In this tutorial, we will learn how to get a character or multiple characters from a string object in Java.

Java String class provides the following methods by which we can extract or retrieve a single character from a string object, and more than one character from a string object at a time. They are as follows:

  • charAt()
  • getChars()

Let’s understand each method one by one with example programs.

Java String charAt() Method


To extract or retrieve a single character from a String object, we can refer directly to a single character using the charAt( ) method.

This charAt() method of string class returns the character located at the specified index within a string. It accepts an integer value that represents an index number. The index number starts at 0 and goes to (n-1) where n is the length of the string.

If the specified index number is greater than or equal to this string length or a negative number, it will return an exception named StringIndexOutOfBoundsException.

The general syntax of this method is as follows.

Syntax:
public char charAt(int index)

Here, index is a parameter that specifies the position of a specific character within a string.

Internal implementation:

public char charAt(int index) 
{
   if ((index < 0) || (index >= value.length)) 
  {
         throw new StringIndexOutOfBoundsException(index);
   }
   return value[index];
}

String charAt() Method Example Program


Let’s take a simple example program in which we will retrieve a specific character from a string object. Look at the following source code.

Program code 1:

package stringProgram;
public class GetCharacter {
public static void main(String[] args) 
{
// Create a string object.	
     String str = new String("Java Technology"); 
     System.out.println("Original string: " +str);

// Retrieve 0th, 4th, 8th, and 9th characters from a string using charAt() method.
     char ch0 = str.charAt(0);
     char ch4 = str.charAt(4);
     char ch8 = str.charAt(8);
     char ch9 = str.charAt(9);
   
     System.out.println("Character at position 0: " +ch0);
     System.out.println("Character at position 4: " +ch4);
     System.out.println("Character at position 8: " +ch8);
     System.out.println("Character at position 9: " +ch9);
  } 
}
Output:
      Original string: Java Technology
      Character at position 0: J
      Character at position 4:  
      Character at position 8: h
      Character at position 9: n

Explanation:

Internally, a string object is represented using an array as shown in the below figure. Java String class provides two public methods such as charAt() and getChars() to retrieve characters from the array.

This is a good example of encapsulation where the detailed data structure is hidden from the user via private modifier. Thus, an user cannot directly manipulate the internal data structure.

If an array is not declared as private, the user would be able to change the string content by modifying the array. Thus, it will violate the statement “String class is immutable in Java”.

Which of these method of class string is used to extract a single character from a string object  O Chatat  O charAt  O Chatat ?

Since an array index starts from 0, str.charAt(0) returns the first character J from the string. Similarly, str.charAt(4) returns the fifth character space in the sequence. str.charAt(8) returns the ninth character h in the sequence and so on.


Let’s take another example program based on charAt() method where we will pass a greater index value than length of an array. In such a case, it throws an exception named StringIndexOutOfBoundsException at run time.

Program code 2:

package stringProgram;
public class GetCharacter {
public static void main(String[] args) 
{
// Create a string object.	
    String str = new String("Scientech Easy"); 
    System.out.println("Original string: " +str);

// Retrieve 3th, 5th, 9th, and 15th characters from a string using charAt() method.
     char ch3 = str.charAt(3);
     char ch5 = str.charAt(5);
     char ch9 = str.charAt(9);
     char ch25 = str.charAt(15);
   
     System.out.println("Character at position 0: " +ch3);
     System.out.println("Character at position 4: " +ch5);
     System.out.println("Character at position 8: " +ch9);
     System.out.println("Character at position 9: " +ch25);
  } 
}
Output:
        Original string: Scientech Easy
        Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 15

As you can observe in the output of the program, when we exceed the index value out of range, JVM throws java.lang.StringIndexOutOfBoundsException.

Java String getChars() Method


The getChars() method is used to extract or retrieve more than one character from a string at a time. In other words, it copies characters from a string into a character array.

The general syntax to declare getChars() method is as follows:

Syntax:
void getChars(int srcStart, int srcEnd, char target[ ], int tarStart)

Here, srcStar specifies the index of starting of the substring and srcEnd specifies an index that is one less the end of desired substring. Thus, substring contains characters between srcStart and srcEnd – 1.

The characters starting from position srcStart to srcEnd – 1 in the string are copied into the array “target” to a location starting from tarStart. Counting of characters in the string will begin from 0th position.

tarEnd specifies the location of the destination array from where the characters from the string will be pushed.


This method does not return any value and throws an exception named StringIndexOutOfBoundsException when any one or more than one of the following conditions holds true.

  • If srcStart is less than zero.
  • If srcStart is greater than srcEndIndex.
  • If srcEnd is greater than the size of the string that calls the method
  • If tarEnd is less than zero.
  • If tarEnd + (srcEnd – srcStart) is greater than the size of the target array.

Internal implementation

The syntax or signature of string getChars() method of String class is as below:

void getChars(char tar[ ], int tarStart)
{
  // copies value from 0 to tar - 1.
      System.arraycopy(value, 0, tar, tarStart, value.length);
}

String getChars() Method Example Program


Let’s take an example program based on getChars() method where we will retrieve more than one character from a string.

In other words, we will take a string and copy some of characters of the string into a character array “target” using getChars() method.

Program code 3:

package stringProgram;
public class GetCharacter {
public static void main(String[] args) 
{
// Create a string object.	
   String str = new String("Welcome to Scientech Easy"); 
   System.out.println("Original string: " +str);
   
   int srcStart = 5;
   int srcEnd = 20;
   char[] target = new char[srcEnd - srcStart];
   str.getChars(srcStart, srcEnd, target, 0);
   System.out.println(target);
  } 
}
Output:
      Original string: Welcome to Scientech Easy
       me to Scientech

Let’s take another example program based on getChars() method where we will keep the index value out of array range and the method will throw an exception.

Program code 4:

package stringProgram;
public class GetCharacter {
public static void main(String[] args) 
{
// Create a string object.	
   String str = new String("How are you?"); 
   System.out.println("Original string: " +str);
   
   int srcStart = 5;
   int srcEnd = 13;
   char[] target = new char[12];
   str.getChars(srcStart, srcEnd, target, 0);
   System.out.println(target);
  } 
}
Output:
      Original string: How are you?
      Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 13
	at java.lang.String.getChars(Unknown Source)
	at stringProgram.GetCharacter.main(GetCharacter.java:12)

Let’s create a program in which we will keep the same value of srcStart and srcEnd. In this case, the getChars() method will not copy anything into the char array.

This is because the getChars() method copies from the srcStart index to srcEnd – 1 index. As srcStart is equal to srcEnd, therefore, srcEnd – 1 is less than srcStart. Therefore, the getChars() method copies nothing.

Program code 5:

package stringProgram;
public class GetCharacter {
public static void main(String[] args) 
{
// Create a string object.	
     String str = new String("I love Java Programming"); 
     System.out.println("Original string: " +str);
   
     int srcStart = 10;
     int srcEnd = 10;
     char[ ] target = new char[12];
   
     str.getChars(srcStart, srcEnd, target, 0);
     System.out.println(target);
     System.out.println("The getChars() method copies nothing.");
  } 
}
Output:
     Original string: I love Java Programming

     The getChars() method copies nothing.

Retrieving First and Last Character by using charAt() Method


Let’s take a simple example program where we will retrieve the first and last characters from the given string.

Program code 6:

package stringProgram;
public class GetChar {
public static void main(String[] args) 
{
// Create a string object.	
     String str = new String("I love Java Programming"); 
     System.out.println("Original string: " +str);
     int strLength = str.length();
     System.out.println("Length of given string: " +strLength);

// Retrieving the first character from the string.
     char firstChar = str.charAt(0);
     System.out.println("First character of a string: " +firstChar);
// Getting last character from thr string.
     char lastChar = str.charAt(strLength - 1);
     System.out.println("Last character of given string: " +lastChar);
  } 
}
Output:
      Original string: I love Java Programming
      Length of given string: 23
      First character of a string: I
      Last character of given string: g

Printing Characters from String at Odd Positions by using charAt() Method


Let’s create a program in which we will extract all the characters at odd position of a given string.

Program code 7:

package stringProgram;
public class GettingOddChar {
public static void main(String[] args) 
{
   String str = "I love my country"; 
   System.out.println("Original string: " +str);
   int strLength = str.length();
   System.out.println("Length of given string: " +strLength);

   for(int i = 0; i <strLength; i++) {
	 if(i % 2!= 0) {
	  System.out.println("Char at " +i+ " place " +str.charAt(i));	 
	 }
   }
  } 
}
Output:
      Original string: I love my country
      Length of given string: 17
      Char at 1 place  
      Char at 3 place o
      Char at 5 place e
      Char at 7 place m
      Char at 9 place  
      Char at 11 place o
      Char at 13 place n
      Char at 15 place r

Counting Frequency of a character in Given String Using charAt() Method


Let’s create a program in which we will count the frequency of a character in the given string using charAt() method of string class.

Program code 8:

package stringProgram;
public class CountingChar {
public static void main(String[] args) 
{
   String str = "I love my country"; 
   int count = 0;
   for(int i = 0; i <= str.length() - 1; i++){
	 if(str.charAt(i) == 'o') 
	 {
	  count++;	 
	 }
   }
   System.out.println("Frequency of character o: " +count );
  } 
}
Output:
      Frequency of character o: 2

Counting the Number of Vowels in a Given String Using chatAt() Method


Let’s take an example program where we will count the number of vowels in a given string by using charAt() method of String class.

Program code 9:

package stringProgram;
import java.util.ArrayList;
public class CountingVowels 
{
     ArrayList al;  
// Declare a constructor for creating and assigning values to the ArrayList al.  
    CountingVowels()  
    {  
	  al = new ArrayList();  // Creating ArrayList object.
  // Adding elements in ArrayList.
	 al.add('A'); al.add('E');  
	 al.add('a'); al.add('e');  
	 al.add('I'); al.add('O');  
	 al.add('i'); al.add('o');  
	 al.add('U'); al.add('u');  
    }
// Declare a method that will check whether the character c is a vowel or not.     
    private boolean isVowel(char c)  
    {  
      for(int i = 0; i < al.size(); i++)  
      {  
        if(c == al.get(i))  
        {  
           return true;  
         }  
       }  
      return false;  
    }  
// Declare a method that will calculate vowels in the given String str.  
    public int countVowels(String str)  
    {  
      int countVowel = 0; // storing total number of vowels.  
      int size = str.length(); // size or length of string.  
      for(int j = 0; j < size; j++)  
      {  
        char c = str.charAt(j);  
        if(isVowel(c))  
        {  
     // If a vowel is found!, increase the count by 1.  
          countVowel = countVowel + 1;  
         }  
       }  
      return countVowel;  
    }    
public static void main(String[] args) 
{
// Create an object of class CountingVowels.  
     CountingVowels cv = new CountingVowels();  
     String s = "Scientech Easy is a great site to learn Java programming.";    
     int noOfVowel = cv.countVowels(s);  
	  
     System.out.println("Given string: " + s);  
     System.out.println("Total number of vowels in the given string: "+ noOfVowel + "\n");    
   
     s = "Every person loves his country";
     System.out.println("Given string: " +s);
     noOfVowel = cv.countVowels(s);
     System.out.println("Total number of vowels in the given string: " +noOfVowel);
  } 
}
Output:
       Given string: Scientech Easy is a great site to learn Java programming.
       Total number of vowels in the given string: 19

       Given string: Every person loves his country
       Total number of vowels in the given string: 9

Hope that this tutorial has covered almost all the important points concerning with how to get character from a string in Java with several example programs. I hope that you will have understood the basic concepts and practiced all programs.
Thanks for reading!!!
Next ⇒ How to Reverse String in Java⇐ PrevNext ⇒

Which method is used to extract a part of a string?

The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters.

What is use of charAt () method?

The charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.

How do I extract a character from a string in Java?

Using String..
Get the string and the index..
Convert the String into Character array using String. toCharArray() method..
Get the specific character at the specific index of the character array..
Return the specific character..

How do you extract the first character of a string?

To get the first and last characters of a string, use the charAt() method, e.g. str. charAt(0) returns the first character, whereas str. charAt(str. length - 1) returns the last character of the string.