how to use chinese and japanese character as string in java?

sjain picture sjain · Nov 1, 2010 · Viewed 56.4k times · Source

Hi
I am using java language. In this I have to use some chinese, japanese character as the string and print using System.out.println().

How can I do that?

Thanks

Answer

Thilo picture Thilo · Nov 1, 2010

Java Strings support Unicode, so Chinese and Japanese is no problem. Other tools (such as text editors) and your OS shell probably need to be told about it, though.

When reading or printing Unicode data, you have to make sure that the console or stream also supports Unicode (otherwise it will likely be replaced with question marks).

Writer unicodeFileWriter = new OutputStreamWriter(
    new FileOutputStream("a.txt"), "UTF-8");
unicodeFileWriter.write("漢字");

You can embed Unicode literals directly in Java source code files, but you need to tell the compiler that the file is in UTF-8 (javac -encoding UTF-8)

String x = "漢字";

If you want to go wild, you can even use Chinese characters in method, variable, or class names. But that is against the naming conventions, and I would strongly discourage it at least for class names (because they need to be mapped to file names, and Unicode can cause problems there):

結果 漢字 = new 物().処理();