Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Java print a String?

Tags:

java

encoding

Java uses char array to store String and String uses UTF-16 to store characters.

For my ubuntu:

$ echo $LANG
en_US.UTF-8

If the encoding of my java source file is UTF-8, and the main content is:

System.out.println("你好");

The meaning of 你好 is hello. With UTF-8, and both need 3 bytes to store. With UTF-16, they need 2 bytes.

When 你好 is printed to screen, is the data that Java sends to Linux OS encoded with UTF-8 or UTF-16 ?

like image 797
letiantian Avatar asked Feb 04 '26 03:02

letiantian


1 Answers

The System.out is a PrintStream, which in turn uses StreamEncoder to encode the String (atleast in Java 6).

StreamEncoder is asked to use the encoding the OS expects. So in your case, it outputs in UTF-8.

like image 77
Nishan Avatar answered Feb 07 '26 00:02

Nishan