Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the Java char primitive take up 2 bytes of memory?

Is there any reason why Java char primitive data type is 2 bytes unlike C which is 1 byte?

Thanks

like image 212
realnumber Avatar asked Oct 18 '10 05:10

realnumber


People also ask

Why does char take 2 bytes in Java?

And, every char is made up of 2 bytes because Java internally uses UTF-16. For instance, if a String contains a word in the English language, the leading 8 bits will all be 0 for every char, as an ASCII character can be represented using a single byte.

Why char uses 2 bytes in Java and what is u0000?

The 'char' data type in Java originally used for representing 16-bit Unicode. Therefore the size of the char data type in Java is 2 byte, and same for the C language is 1 byte. Hence Java uses Unicode standard. What are features of Java language?

Which of the following takes up 2 bytes of memory?

Java used as a internationalize so, its work in different languages and need to space more than one byte, that's why its take 2byte of space in char.


2 Answers

When Java was originally designed, it was anticipated that any Unicode character would fit in 2 bytes (16 bits), so char and Character were designed accordingly. In fact, a Unicode character can now require up to 4 bytes. Thus, UTF-16, the internal Java encoding, requires supplementary characters use 2 code units. Characters in the Basic Multilingual Plane (the most common ones) still use 1. A Java char is used for each code unit. This Sun article explains it well.

like image 166
Matthew Flaschen Avatar answered Sep 18 '22 12:09

Matthew Flaschen


char in Java is UTF-16 encoded, which requires a minimum of 16-bits of storage for each character.

like image 36
Vijay Mathew Avatar answered Sep 17 '22 12:09

Vijay Mathew