w3resource

Java String: codePointCount() Method

codePointCount() method - Number of Unicode code points within the specified text range

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 and above.

Syntax codePointCount() method

codePointCount(int beginIndex, int endIndex)

Parameters codePointCount() method

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

Return Value codePointCount() method

  • 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:

Previous:codePointBefore Method
Next:compareTo Method



Follow us on Facebook and Twitter for latest update.