Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Char size 8 bit or 16 bit?

Tags:

java

char

byte

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html, char size is 16 bit i.e 2 byte. somehow i recalled its 8 bit i.e 1 byte. To clear my doubt, i created a text file with single character "a" and saved it. Then i inspected the size of file , its 1 byte i.e 8 bit. I am confused whats the size of character ? If its 2 byte , why file size is 1 byte and if it is 1 byte why link says 2 bytes?

like image 615
user3198603 Avatar asked Jun 07 '14 08:06

user3198603


People also ask

Is a char 8-bit?

The char type takes 1 byte of memory (8 bits) and allows expressing in the binary notation 2^8=256 values. The char type can contain both positive and negative values. The range of values is from -128 to 127.

What is the size of char datatype 8-bit 12 bit 16-bit 20 bit?

Clarification: Size of 'Char' datatype is 16 bit.

Can char be more than 8 bits?

that a char is represented by a byte, that a byte can always be counted upon to have 8 bits, that sizeof (char) is always 1 , and that the maximum theoretical amount of memory I can allocate (counted in char s) is the number of bytes of RAM (+ swap space).


2 Answers

A char in Java is a UTF-16 code unit. It's not necessarily a complete Unicode character, but it's effectively an unsigned 16-bit integer.

When you write text to a file (or in some other way convert it into a sequence of bytes), then the data will depend on which encoding you use. For example, if you use ASCII or ISO-8859-1 then you're very limited as to which characters you can write, but each character will only be a byte. If you use UTF-16, then each Java char will be converted into exactly two bytes - but some Unicode characters may take four bytes (those represented by two Java char values).

If you use UTF-8, then the length of even a single Java char in the encoded form will depend on the value.

like image 120
Jon Skeet Avatar answered Oct 08 '22 00:10

Jon Skeet


There is a contemporary way to learn its size. Just print with BYTES.

System.out.println(Character.BYTES);

It results in 2

like image 45
snr Avatar answered Oct 07 '22 22:10

snr