Java codePointCount Method

The Java codePointCount method is one of the String Methods, which is to count the number of Unicode points within the specified text range. In this article, we will show how to use codePointCount in Java Programming language with an example. The basic syntax of the codePointCount is as shown below.

public int codePointCount(int Starting_Index, int End_Index) 

//In order to use in program
String_Object.codePointCount(int Starting_Index, int End_Index)
  • String_Object: Please specify the valid String Object.
  • Starting_Index: Please specify the index position of the first character.
  • End_Index: Please specify the index position of the last but one character.

The Java codePointCount Function will count no of Unicode points from Starting_Index to End_Index – 1. Mathematically we say the return value as (End_Index – Starting_Index).

For example, codePointCount(12, 20) will return 8 as an output because 20 – 12 = 8. If we provide the Index position out of range or negative value, then the codePointCount Function will throw an error.

Java codePointCount Example

In this program, we are going to use the string codePointCount method to count the Unicode points between the specified range.

package StringFunctions;

public class CodePointCount {
	public static void main(String[] args) {
		String str = "Learn Free Java Tutorial";
		
		int a = str.codePointCount(0, 3);
		int b = str.codePointCount(4, 11);
		int c = str.codePointCount(12, str.length()- 1);
		int d = str.codePointCount(0, str.length()- 1);
		
		System.out.println( "Total Unicode Points from 0 to Index position 3 = " + a);
		System.out.println( "Total Unicode Points from 4 to Index position 11 = " + b);
		System.out.println( "Total Unicode Points from 12 to Last Index position = " + c);
		System.out.println( "Total Unicode Points from 0 to Last Index position = " + d);
	}
}
Java codePointCount Method 1

Within the following codePointCount statements, the first statement will find the Count the Unicode points between 0 and 3, and the other will find Unicode points between 4 and 11.

int a = str.codePointCount(0, 3);
int b = str.codePointCount(4, 11);

If you observe the above screenshot, str.codePointCount(0, 3) is returning 3. It is because there are three Unicode points between 0 and 3 or (3 – 0 = 3). You should count the space as One Character.

Within the next two lines, we are using the Java codePointCount method along with the length function to calculate the string length.

int c = str.codePointCount(12, str.length()- 1);
int d = str.codePointCount(0, str.length()- 1);

From the above String Method code snippet, we are subtracting one from string length. Because the length of a string will count from 1 to n, where the index position will start from 0 and ends at n – 1. The following four Java System.out.println statements will print the output

Comments are closed.