Search

Friday, December 14, 2018

Java Literals, Hexadecimal and Octal Constants

In Java, literals refer to fixed values that are represented in their human-readable form.
For example, the number 100 is a literal. Literals are also commonly called constants. For the most part, literals, and their usage, are so intuitive that they have been used in one form or another by all the preceding sample programs. Now the time has come to explain them formally. Java literals can be of any of the primitive data types. The way each literal is represented depends upon its type. As explained earlier, character constants are enclosed in single quotes. For example, 'a' and ' %' are both character constants. Integer constants are specified as numbers without fractional components. For example, 10 and –100 are integer constants. Floating-point constants require the use of the decimal point followed by the number’s fractional component. For example, is a floating-point constant. Java also allows you to use scientific notation for floating-point numbers. By default, integer literals are of type int. If you want to specify along literal, append an l or an L. For example is an int, but 12 L is along. By default, floating-point literals are of type double. To specify a float literal, append an F or f to the constant.
Although integer literals create an int value by default, they can still be assigned to variables of type char,byte, or short as long as the value being assigned can be represented by the target type. An integer literal can always be assigned to a long variable.

As you probably know, in programming it is sometimes easier to use a number system based on 8 or 16 instead of 10. The number system based on 8 is called octal,and it uses the digits 0 through 7. In octal the number 10 is the same as 8 in decimal. The base 16 number system is called hexadecimal and uses the digits 0 through 9 plus the letters A through F,which stand for 10,11,12,13,14, and 15. For example, the hexadecimal number 10 is 16 in decimal.
Because of the frequency with which the set won umber systems are used, Java allows you to specify integer constants in hexadecimal or octal in stead of decimal. A hexadecimal constant must begin with 0 x (a zero followed by an x). An octal constant begins with a zero. Here are some examples:

hex            =            0xFF; // 255  in decimal 
oct             =            011;  // 9 in decima

0 comments:

Post a Comment