A lot of beginners (including me, have been learning Java for more than a year) Ken will be on the char and byte two data types have doubts, confusion, today specially looked at a lot of data, the byte and char two types are summarized and compared, first to share the results with you:
Byte is a byte data type, is a signed type, occupies 1 bytes, and has a size range of-128-127. Char is a character data type, is unsigned, occupies 2 bytes (Unicode code), the size range is 0-65535; char is a 16-bit binary Unicode character, and Java uses Char to represent a character.
Here are some examples to compare the differences:
1. Char is unsigned, can represent an integer, cannot represent a negative number, and byte is a signed type, which can represent 128-127;
[HTML]View Plaincopy
- char C = (char)-3;//char does not recognize negative numbers, must be cast otherwise error, even after casting, does not recognize
- System.out.println (c);
- byte d1 = 1;
- byte d2 =-1;
- byte d3 = 127;//If it is byte d3 = 128; error
- byte d4 =-128;//If it is byte d4 =-129; Error
- System.out.println (D1);
- System.out.println (D2);
- SYSTEM.OUT.PRINTLN (D3);
- System.out.println (D4);
The result is:
?
1
-1
127
-128
2, char can be a table Chinese characters, byte can not, such as:
[HTML]View Plaincopy
- Char e1 = ' Medium ', e2 = ' country ';
- byte f= (Byte) ' in ';//must be cast otherwise error
- SYSTEM.OUT.PRINTLN (E1);
- SYSTEM.OUT.PRINTLN (E2);
- System.out.println (f);
The result is:
In
Country
45
3, char, byte, int for English characters, can be converted to each other, such as:
[HTML]View Plaincopy
- byte g = ' B '; b corresponds to ASCII is 98
- Char h = (char) g;
- char i = 85; U corresponds to ASCII is
- int j = ' H '; H corresponds to ASCII is 104
- System.out.println (g);
- System.out.println (h);
- System.out.println (i);
- System.out.println (j);
The result is:
98
B
U
104
Welcome to the "Java Dream Team" learning Group: 226159645
The difference between char and byte