Character Extraction in Java

There are several ways by which characters can be extracted from String class object. String is treated as an object in Java so we can’t directly access the characters that comprise a string. For doing this String class provides various predefined methods.

 

Character Extraction in Java

charAt()

charAt() method is used to extract a single character at an index. It has following syntax.

Syntax

 

Example

 

Output
l

In above example ch will contain character l. We must take care that the index should not be negative and should not exceed string length.

 

getChars()

It is used to extract more than one character. getChars() has following syntax.

Syntax

 

Here stringStart and stringEnd is the starting and ending index of the substring. arr is the character array that will contain the substring. It will contain the characters starting from stringStart to stringEnd-1. arrStart is the index inside arr at which substring will be copied. The arr array should be large enough to store the substring.

Example

 

Output
ello

 

getBytes()

getBytes() extract characters from String object and then convert the characters in a byte array. It has following syntax.

Syntax

 

Example

 

toCharArray()

It is an alternative of getChars() method. toCharArray() convert all the characters in a String object into an array of characters. It is the best and easiest way to convert string to character array. It has following syntax.

Syntax

 

Example

 

Output
Hello World

 

If you found anything wrong or have any doubts regarding above tutorial then comment below.

Leave a Comment

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