Java Character charCount() with Examples

JavaObject Oriented ProgrammingProgramming

The Character.charCount() 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.

Example

Let us now see an example −

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      // create and assign values to int codepoint cp
      int cp = 0x12345;
      // create an int res
      int res;
      // assign the result of charCount on cp to res
      res = Character.charCount(cp);
      String str1 = "It is not a valid supplementary character";
      String str2 = "It is a valid supplementary character";
      // print res value
      if ( res == 1 ) {
         System.out.println( str1 );
      } else if ( res == 2 ) {
         System.out.println( str2 );
      }
   }
}

Output

It is a valid supplementary character

Example

Let us see another example −

 Live Demo

import java.lang.*;
public class Demo {
   public static void main(String[] args) {
      int c = 0x11987;
      int res = Character.charCount(c);
      System.out.println(res);
   }
}

Output

2
raja
Published on 26-Sep-2019 12:47:56
Advertisements