In this post, we will see how to get unicode value of character in java.
Get Unicode Value of Character in Java
You can simply use below code to get unicode value of character in java.
1 2 3 4 5 |
private static String getUnicodeCharacterOfChar(char ch) { return String.format("\\u%04x", (int) ch); } |
Here is complete example to print unicode value of character in java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package org.arpit.java2blog; public class GetUnicodeCharacterOfCharMain { public static void main(String[] args) { String str="java2blog"; String char1 = getUnicodeCharacterOfChar(str.charAt(3)); System.out.println("Unicode value of character d: "+char1); String char2 = getUnicodeCharacterOfChar('क'); System.out.println("Unicode value of character क: "+char2); } private static String getUnicodeCharacterOfChar(char ch) { return String.format("\\u%04x", (int) ch); } } |
Output
Unicode value of character क: \u0915
If source is not character but string, you must chatAt(index)
to get unicode value of the character.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; public class GetUnicodeValueOfCharMain { public static void main(String[] args) { String str="java2blog"; String char1 = getUnicodeCharacterOfChar(str.charAt(3)); System.out.println("Unicode value of character d: "+char1); } private static String getUnicodeCharacterOfChar(char ch) { return String.format("\\u%04x", (int) ch); } } |
Output:
Get Unicode Character Code in Java
In java, char is a "16 bit integer", you can simply cast char to int and get code of unicode character.
1 2 3 4 |
char char1 = 'ज'; int code = (int) char1; |
Here is definition of char from Oracle:
The char data type is a single 16-bit Unicode character. It has a minimum value of ‘\u0000’ (or 0) and a maximum value of ‘\uffff’ (or 65,535 inclusive).
Here is complete example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
package org.arpit.java2blog; public class GetUnicodeCodeOfCharMain { public static void main(String[] args) { char char1 = '®'; System.out.println(String.format("Unicode character code: %d", (int) char1)); System.out.println(String.format("Unicode character code in hexa format: %x", (int) char1)); } } |
Unicode character code in hexa format: ae
That’s all about how to get unicode value of character in java.