Wednesday, May 30, 2018

Integer Literals using JAVA

Integers are probably the most commonly used type in the typical program. Any whole
number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal
values, meaning they are describing a base 10 number. There are two other bases which
can be used in integer literals, octal (base eight) and hexadecimal (base 16). Octal values
are denoted in Java by a leading zero. Normal decimal numbers cannot have a leading
zero. Thus, the seemingly valid value 09 will produce an error from the compiler,
since 9 is outside of octal’s 0 to 7 range. A more common base for numbers used by
programmers is hexadecimal, which matches cleanly with modulo 8 word sizes, such
as 8, 16, 32, and 64 bits. You signify a hexadecimal constant with a leading zero-x, (0x
or 0X). The range of a hexadecimal digit is 0 to 15, so A through F (or a through f ) are
substituted for 10 through 15.
Integer literals create an int value, which in Java is a 32-bit integer value. Since
Java is strongly typed, you might be wondering how it is possible to assign an integer
literal to one of Java’s other integer types, such as byte or long, without causing a type
mismatch error. Fortunately, such situations are easily handled. When a literal value is
assigned to a byte or short variable, no error is generated if the literal value is within the
range of the target type. Also, an integer literal can always be assigned to a long variable.
However, to specify a long literal, you will need to explicitly tell the compiler that the
literal value is of type long. You do this by appending an upper- or lowercase L to
the literal. For example, 0x7ffffffffffffffL or 9223372036854775807L is the largest long.
banner
Previous Post
Next Post

0 comments: