Print unicode character in java

Viewed 41151

Displaying unicode character in java shows "?" sign. For example, i tried to print "अ". Its unicode Number is U+0905 and html representation is "अ". The below codes prints "?" instead of unicode character.

char aa = '\u0905';
String myString = aa + " result" ;
System.out.println(myString); // displays "? result"

Is there a way to display unicode character directly from unicode itself without using unicode numbers? i.e "अ" is saved in file now display the file in jsp.

5 Answers

Java defines two types of streams, byte and character.

The main reason why System.out.println() can't show Unicode characters is that System.out.println() is a byte stream that deal with only the low-order eight bits of character which is 16-bits.

In order to deal with Unicode characters(16-bit Unicode character), you have to use character based stream i.e. PrintWriter.

PrintWriter supports the print( ) and println( ) methods. Thus, you can use these methods in the same way as you used them with System.out.

PrintWriter printWriter = new PrintWriter(System.out,true);
char aa = '\u0905';
printWriter.println("aa = " + aa);

Unicode is a unique code which is used to print any character or symbol.

You can use unicode from --> https://unicode-table.com/en/

Below is an example for printing a symbol in Java.

        package Basics;
        
        /**
         *
         * @author shelc
         */
        public class StringUnicode {
        
            public static void main(String[] args) {
        
                String var1 = "Cyntia";
                String var2 = new String(" is my daughter!");
        
                System.out.println(var1 + " \u263A" + var2);
    
                //printing heart using unicode
                System.out.println("Hello World \u2665");
        
            }
        
        }
        
    ******************************************************************
    OUTPUT-->
    
    Cyntia ☺ is my daughter!
    Hello World ♥
          
Related