w3resource logo


Java Programming

Java String: codePointCount() Method

Secondary Nav

public int codePointCount(int beginIndex, int endIndex)

The codePointCount() method is used to count the number of Unicode code points in the specified text range of a given String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.

Java Platform: Java SE 8

Syntax :

codePointCount(int beginIndex, int endIndex)

Parameters:

Name Description Type
beginIndex the index after the last char of the text range. int
endIndex the index after the last char of the text range. int

Return Value :
The number of Unicode code points in the specified text range.

Return Value Type: int

Throws: IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String, or beginIndex is larger than endIndex.

Example : Java String codePointCount() Method

The following example shows the usage of java String() method.

public class Example {

public static void main(String[] args) {
System.out.println();
    String str = "w3rsource.com";
System.out.println("Original String : " +str);

    // codepoint from index 1 to index 10
int ctr = str.codePointCount(1, 10);

    // prints character from index 1 to index 10
System.out.println("Codepoint count = " +ctr);
System.out.println();
  }
}

Output:

Original String : w3rsource.com                        
Codepoint count = 9 

Example of Throws: codePointCount(int beginIndex, int endIndex) Method

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String, or beginIndex is larger than endIndex.

Let

int ctr = str.codePointCount(-1, 10);

in the above example.

Output:

Original String : w3rsource.com                        
Exception in thread "main" java.lang.IndexOutOfBoundsEx
ception                                                
        at java.lang.String.codePointCount(String.java:
745)                                                   
        at Exercise.main(Example.java:9)

Java Code Editor:



Join our Question Answer community to learn and share your programming knowledge.