Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Difficulty: Easy

Java String getChars() Method

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

A string is just a series of characters(char). In Java, the String is a Class and not a data type like 'int & char'. Thus, the String class represents String characters, and all string objects in Java are instances of this type. The string class is the most useful in Java programming and Selenium WebDriver. In this blog, we will learn about the String class' getChars() Method in Java with the help of a few examples.

getChars() Method

The java string getChars() function transfers characters from a string into a character array.

Syntax

public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)

Parameters

Here is a list of parameters:

  • srcBegin is the index of the first char to copy in the String.
  • srcEnd indexes after the final character to be copied in the String.
  • dst is the array's destination.
  • dstBegin is the offset at which the destination array begins.

Return

It returns no value but throws an IndexOutOfBoundsException.

Must Read: Java System Out Println

Exception Throws

When any of the following conditions is present, the method throws a StringIndexOutOfBoundsException:

  • If the value of srcBeginIndex is less than zero.
  • If srcBeginIndex exceeds srcEndIndex.
  • If srcEndIndex is higher than the length of the string that invokes the function, the method is called.
  • If the value of dstEndIndex is less than zero.
  • If the sum of dstEndIndex + (srcEndIndex - srcBeginIndex) exceeds the size of the destination array.

Internal Implementation

The syntax for getChars() is:

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

 

Must Read Array of Objects in Java

Example-1

import java.io.*;
public class Test {


   public static void main(String args[]) {
      String Str1 = new String("Welcome to CodingNinjas Portal");
      char[] Str2 = new char[7];
      try {
         Str1.getChars(2, 9, Str2, 0);
         System.out.print("Copied Value = " );
         System.out.println(Str2 );
      } catch ( Exception ex) {
         System.out.println("Raised exception...");
      }
   }
}

Output

Copied Value = lcome t

Example-2

// exception condition in working of getChars() method
 class Coding Ninjas Studio {
    public static void main(String args[])
    {
        String str = "Welcome! to Coding Ninjas Studio";
 
        char[] destArray = new char[20];
        try {
            // Starting index 0 and ending index 24
            str.getChars(12, 26, destArray, 0);
            System.out.println(destArray);
        }
        catch (Exception ex) {
            System.out.println(ex);
        }
    }
}

Output

java.lang.StringIndexOutOfBoundsException: begin 12, end 26, length 22


Must Read:  String Args in Java

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

Can we compare String using the == operator? What is the risk?

Yes, we can use the == operator to compare Strings. When we compare strings with the == operator, we are comparing their object references, which determines if these string variables correspond to the same string object or not.

Most of the time, developers wish to compare the content of strings, but they compare strings with the == operator rather than the equals() function, which results in an error.

 

What are mutable and immutable objects in Java?

The value of mutable objects can be altered. Mutable objects include the StringBuilder and StringBuffer.

Once created, the value of an immutable object cannot be modified. In Java, a string is an immutable class.

 

What Is the String Constant Pool?

The String constant pool, sometimes known as the String intern pool, is a specific memory location where the JVM saves String instances.

Conclusion

In this article, we have extensively discussed String getChars() Method in Java Programming. We have also discussed its syntax, parameters as well as return type with the help of an example. We hope this blog has helped you enhance your knowledge regarding string methods in Java Programming. Some official documentation on big data that can help you improve your understanding is String isEmpty().
 

Recommended problems -

If you would like to learn more, check out our articles on String contains(), and String format(). Practice makes a man perfect. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews. Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
getChars() Method
2.1.
Syntax
2.2.
Parameters
2.3.
Return
2.4.
Exception Throws
2.5.
Internal Implementation
2.6.
Example-1
2.6.1.
Output
2.7.
Example-2
2.7.1.
Output
3.
Frequently Asked Questions
3.1.
Can we compare String using the == operator? What is the risk?
3.2.
 
3.3.
What are mutable and immutable objects in Java?
3.4.
 
3.5.
What Is the String Constant Pool?
4.
Conclusion