Home >Java >Javagetting Started >How many bytes does the char type occupy?

How many bytes does the char type occupy?

青灯夜游
青灯夜游Original
2021-01-18 13:51:3076868browse

In Java, the char type occupies 2 bytes; reason: The Java compiler uses Unicode encoding by default, so 2 bytes (16 bits) can represent all characters. In Java, short and char occupy 2 bytes; byte and boolean occupy 1 byte, and int and float occupy 4 bytes.

How many bytes does the char type occupy?

The operating environment of this tutorial: windows7 system, java10 version, DELL G3 computer.

Number of bytes occupied by Java basic types:

  • 1 Bytes: byte, boolean

  • 2 bytes: short, char

  • 4 bytes: int, float

  • 8 bytes: long, double

Note: 1 byte (byte) = 8 bits (bits)

Appendix:

1. Encoding and Chinese:

  • Unicode/GBK: Chinese 2 bytes

  • UTF-8: Chinese is usually 3 bytes, and the one after the extended B area is 4 characters Section

To sum up, the number of bytes occupied by Chinese characters in encoding is generally 2-4 bytes.

Test code:

/*
System.out.println("中".getBytes("UTF-8").length); ----> 6
System.out.println("中中".getBytes("UTF-8").length); ----> 9
System.out.println("中".getBytes("GBK").length); ----> 3
System.out.println("中中".getBytes("GBK").length); ----> 6

不好意思,我也不能解释,为什么打印的结果是这样的。大牛飘过还请指摘。
*/

2. Number of bytes of char in Java:

Char occupies 2 bytes in Java.

The Java compiler uses Unicode encoding by default, so 2 bytes can represent all characters.

Test code:

char a= (char) Integer.MAX_VALUE;
System.out.println((int)a);

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of How many bytes does the char type occupy?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn