Java String getChars() Method with Examples

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

The getChars() method in Java’s String class is a valuable tool for copying characters from a string into a character array (char[]). It is handy when extracting a specific segment of a string’s content.

In this article, we will explore how to use the getChars() method effectively. The getChars() method is part of the String class in Java and is designed to copy characters from a string into a character array. This method allows you to specify the starting and ending indices to determine the portion of the string to be copied. This functionality is beneficial when extracting a part of a string’s content into a character array for further processing or manipulation.

Moreover, the getChars() method offers an efficient approach to obtaining a substring from a string without creating a new string object.

Syntax and Parameters of Java getChars() method

The getChars() method has the following syntax:

public void getChars(int srcBeginIndex, int srcEndIndex, char[] destination, int dstBeginIndex)

It takes the following parameters:

  • srcBeginIndex – The starting index in the original string from where characters should be copied.
  • srcEndIndex – The ending index in the original string marking the end of the substring to copy.
  • destination – The character array into which the substring should be copied.
  • dstBeginIndex – The starting index in the destination array where the copied characters should be inserted.

Return Value

The getChars() method does not return any value. It copies the characters from the string into the destination character array.

Exception Handling

The getChars() method can throw a StringIndexOutOfBoundsException if:

  • srcBeginIndex is negative.
  • srcBeginIndex is greater than srcEndIndex.
  • srcEndIndex is greater than the length of the string.
  • dstBeginIndex is negative.
  • dstBeginIndex + (srcEndIndex – srcBeginIndex) is greater than the length of the destination array.

Proper validation of the index values is necessary to avoid exceptions.

Java String getChars() Method Examples

Example 1

public class StringGetCharsExample {
  public static void main(String[] args) {
    String str = "Hello World";
    char[] dest = new char[5];

    try {
      str.getChars(2, 7, dest, 0);
      System.out.println(dest); // Prints "llo W"
    } catch (StringIndexOutOfBoundsException ex) {
      System.out.println(ex);
    }
  }
}

Output:
llo W

This example creates a string “Hello World” and a character array of length 5. The getChars() method copies characters from index 2 to index 6 of the string into the destination array, starting at index 0.

Example 2

public class StringGetCharsExample {
  public static void main(String[] args) {
    String message = "Welcome to Java programming";
    char[] excerpt = new char[10];

    try {
      message.getChars(11, 21, excerpt, 0);
      System.out.println(excerpt); // Prints "programming"
    } catch (StringIndexOutOfBoundsException ex) {
      System.out.println("Index out of bounds!"); 
    }
  }
}

Output:
programming

Here, we extract a portion of the message string into the excerpt array using appropriate index values.

Example 3

public class StringGetCharsExample {
  public static void main(String[] args) {
    String empty = "";
    char[] arr = new char[10];

    empty.getChars(0, 0, arr, 0);
    System.out.println(arr); // Prints blank
  }
}

When srcBeginIndex and srcEndIndex are equal, getChars() copies no characters into the destination array.

Conclusion

In conclusion, the getChars() method in the Java String class simplifies substring extraction to a character array. Its efficient functionality eliminates the need for additional string object creation, making it ideal for memory conservation and performance improvement, especially with extensive text data. Precise control over start and end indices allows tailored text extraction. Proper exception handling ensures code reliability.

In summary, getChars() is a valuable tool for streamlined, memory-efficient string manipulation, enhancing Java application robustness.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

courses

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

Your email address will not be published. Required fields are marked *