Can the char type be categorized as an integer?
Just now I read "char is the only unsigned integral primitive type in Java." Does this mean the char is one of the integral types in Java?
Same as in C, recently I have read that C types includes scalar types, function types, union types, aggregate types, and scalar types include pointer types and arithmetic types, then arithmetic types include integral types and floating-point types, the integral types include enumerated types and character types.
Can the char type really be categorized as a integer both in Java and C?
Yes, a char
is an integral type in all the popular languages in which it appears. "Integral" means that its spectrum is discrete and the smallest difference between any two distinct values is 1
. The required range of supported values is usually quite small compared to that of other integral types. Computer hardware traditionally treats integers as the fundamental data type; by contrast, arithmetic floating-point types are a more recent and more complicated addition.
Similar to @aioobe's answer
int n = 5;
char ch = (char) '0' + 5; // '5'
or the reverse
char ch = '9';
int i = ch - '0'; // 9
or the unusual
char ch = 'a';
ch += 1; // 'b';
or the odd
char ch = '0';
ch *= 1.1; // '4' as (char) (48 * 1.1) == '4'
ch %= 16; // `\u0004`
int i = ch; // 4
BTW: From String.hashCode()
// int h = 0;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
According to the Java Primitive Data Types tutorial:
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
So yes, it is a 16-bit unsigned integer. Whether you use the type to represent a number or a character is up to you...
Also keep in mind that while the
char
type is guaranteed to be 16 bits in Java, the only restriction C imposes is that the type must be at least 8 bits. According to the C spec reference from this answer:
maximum number of bits for smallest object that is not a bit-field (byte)
CHAR_BIT 8
So a char
in C does not necessarily represent the same range of integer values as a char
in Java.
I'm unsure of the formal definition of an integral type, but in short, yes, char
is an integral type in Java, since it can be seen as representing an integer.
You can for instance do
char c1 = 'a' + 'b';
char c2 = 5;
char c3 = c2 + 3;
int i = c3;
char c4 = (char) i;
and so on.
In memory, essentially everything is integral... but yes. char is an integer type in C, C++ and Java.