java.lang.Character charCount(int codePoint)

Description

The Character.charCount(int codePoint) java method determines the number of char values needed to represent the specified character (Unicode code point). If the specified character is equal to or greater than 0x10000, then the method returns 2. Otherwise, the method returns 1.

This method doesn’t validate the specified character to be a valid Unicode code point. The caller must validate the character value using isValidCodePoint if necessary.

Make a note that the charCount method of Character class is static thus it should be accessed statically which means the we would be calling this method in this format:

Character.charCount(method args)

Non static method is usually called by just declaring method_name(argument) however in this case since the method is static, it should be called by appending the class name as suffix. We will be encountering a compilation problem if we call the java charCount method non statically.

Method Syntax

public static int charCount(int codePoint)

Method Argument

Data Type Parameter Description
int codePoint the character (Unicode code point) to be tested.

Method Returns

The charCount(int codePoint) method of Character class returns 2 if the character is a valid supplementary character; 1 otherwise.

Compatibility

Requires Java 1.5 and up

Discussion

 The method charCount(int codePoint) just count how many characters are in the specified codepoint(method argument). Basically expects the returned value either 2 or 1. The returned value is 2 if the specified character is equal to or greater than 0x10000, otherwise 1. Expect that most of the time the you would be getting a value of 1 because by right a character length is 1.

Java Character charCount(int codePoint) Example

Below is a simple java example on the usage of charCount(int codePoint) method of Character class.

package com.javatutorialhq.java.examples;

/*
 * This example source code demonstrates the use of 
 * charCount(int codePoint) method of Character class.
 */

public class CharacterCharCountExample {

	public static void main(String[] args) {

		// initialize codepoints
		int codepoint1 = 12;
		int codepoint2 = 1231212;

		// check the number of char values needed to represent the specified
		// character
		int result1 = Character.charCount(codepoint1);
		int result2 = Character.charCount(codepoint2);

		// print the result
		System.out.println("Codepoint " + codepoint1 + " can be respresented by "
				+ result1 + " char values");
		System.out.println("Codepoint " + codepoint2 + " can be respresented by " 
				+ result2 + " char values");
	}

}

Sample Output

Below is the sample output when you run the above example.

java Character charCount() example output