Sunday 13 March 2016

The Java Language: Integer literals

Integer literals can be specified in octal (base 8), decimal (base 10), or hexadecimal (base 16). A decimal integer is specified by a sequence of digits beginning with one of the characters 1–9:

 int i = 1230;  
Octal numbers are distinguished from decimal numbers by a leading zero:
 int i = 01230; // i = 664 decimal  
A hexadecimal number is denoted by the leading characters 0x or 0X (zero “x”), followed by a combination of digits and the characters a–f or A–F, which represent the decimal values 10–15:
 int i = 0xFFFF; // i = 65535 decimal  
Integer literals are of type int unless they are suffixed with an L, denoting that they are to be produced as a long value:
 long l = 13L;  
 long l = 13; // equivalent: 13 is converted from type int  
(The lowercase letter l is also acceptable but should be avoided because it often looks like the number 1.) When a numeric type is used in an assignment or an expression involving a “larger” type with a greater range, it can be promoted to the bigger type. In the second line of the previous example, the number 13 has the default type of int, but it’s promoted to type long for assignment to the long variable. Certain other numeric and comparison operations also cause this kind of arithmetic promotion, as do mathematical expressions involving more than one type. For example, when multiplying a byte value by an int value, the compiler promotes the byte to an int first:
 byte b = 42;  
 int i = 43;
int result = b * i; // b is promoted to int before multiplication  
A numeric value can never go the other way and be assigned to a type with a smaller range without an explicit cast, however:
 int i = 13;  
 byte b = i; // Compile-time error, explicit cast needed  
 byte b = (byte) i; // OK  
Conversions from floating-point to integer types always require an explicit cast because of the potential loss of precision. Finally, we should note that if you are using Java 7 or later, you can add a bit of formatting to your numeric literals by utilizing the “_” underscore character between digits. So if you have particularly large strings of digits, you can break them up as in the following examples:
 int RICHARD_NIXONS_SSN = 567_68_0515;  
 int for_no_reason = 1___2___3;  
 int JAVA_ID = 0xCAFE_BABE;  
Underscores may only appear between digits, not at the beginning or end of a number or next to the “L” long integer signifier.

0 comments:

Post a Comment