Wednesday, July 24, 2013

Integer Literals

An integer variable stores an integer value, so before you get to use integer variables you need to understand how you write integer values of various types. As I said earlier, a value of any kind in Java is referred to as a literal. So 1, 10.5, and “This is text” are all examples of literals.

Any integer literal that you specify as a sequence of decimal digits is of type int by default. Thus 1, -9999, and 123456789 are all literals of type int. If you want to define an integer literal of type long, you need to append an L to the value. The values 1L, -9999L, and 123456789L are all of type long. You can also use a lowercase letter l, but don’t - it is too easily confused with the digit 1.

You are perhaps wondering how you specify literals of type byte or short. Because of the way integer arithmetic works in Java, they just aren’t necessary in the main. You’ll see a couple of instances where an integer literal may be interpreted by the compiler as type byte or short later in this chapter, but these situations are the exception.

You can also specify integer literals to base 16 - in other words, as hexadecimal numbers. Hexadecimal literals in Java have 0x or 0X in front of them and follow the usual convention of using the letters A to F (or a to f) to represent digits with values 10 to 15, respectively. In case you are a little rusty on hexadecimal values.

If you are not familiar with hexadecimal numbers, you can find an explanation of how these work in Appendix B. All the hexadecimal literals in the preceding table are of type int. If you want to specify a hexadecimal literal of type long, you must append L to the literal just as with decimal literals. For example,0x0FL is a hexadecimal literal that is equivalent to the decimal value 15.

There is a further possibility for integer literals - you can also define them as octal values, which is to base 8, and legal digits in an octal literal can be from 0 to 7. You write literals that are octal numbers with a leading zero, so 035 and 067 are examples of octal numbers. Each octal digit defines 3 bits, so this number base was used a lot more frequently in the days when machines used words of lengths that were a multiple of 3 bits to store a number. You will rarely find it necessary to use octal numbers these days, but you should take care not to use them by accident. If you put a leading zero at the start of an integer literal,the Java compiler will think you are specifying an octal value. Unless one of the digits is greater than 7, which results in the compiler flagging it as an error, you won’t know that you have done this.

No comments:

Post a Comment

Thanks for Commenting......