LITERAL VALUES FOR ALL PRIMITIVES

INTEGER LITERAL:
There are three ways to represent integer numbers in the Java language: decimal
(base 10), octal (base 8), and hexadecimal (base 16).
Decimal Literals -Decimal integers need no explanation; you've been using
them since grade one or earlier.e.g.int x=10;
Octal Literals -Octal integers use only the digits 0 to 7. In Java, you represent
an integer in octal form by placing a zero in front of the number,
e.g.int six = 06; // Equal to decimal 6
int eight = 010; // Equal to decimal 8
Hexadecimal Literals -Hexadecimal (hex for short) numbers are constructed
using 16 distinct symbols. Because we never invented single digit symbols for the
numbers 10 through 15, we use alphabetic characters to represent these digits.
Counting from 0 through 15 in hex looks like this:
0 1 2 3 4 5 6 7 8 9 a b c d e f
e.g.int x = 0X0001;
int y = 0x7fffffff;
int z = 0xDeadCafe;
FLOATING POINT LITERAL:
Floating-point literals are defined as double (64 bits) by default, so if you want to
assign a floating-point literal to a variable of type float (32 bits), you must attach the suffix F or f to the number. If you don't, the compiler will complain about a possible loss of precision, because you're trying to fit a number into a (potentially) less precise "container."
float f = 23.467890; // Compiler error, possible loss of precision
float g = 49837849.029847F; // OK; has the suffix "F"
You may also optionally attach a D or d to double literals, but it is not necessary
because this is the default behavior.
double d = 110599.995011D; // Optional, not required
double g = 987.897; // No 'D' suffix, but OK because the
// literal is a double by default
BOOLEAN LITERALS:
Boolean literals are the source code representation for boolean values. A boolean
value can only be defined as true or false.
CHARACTER LITERAL:
A char literal is represented by a single character in single quotes.
char a = 'a';
char b = '@';
You can also type in the Unicode value of the character, using the Unicode
notation of prefixing the value with \u as follows:
char letterN = '\u004E'; // The letter 'N'
Remember, characters are just 16-bit unsigned integers under the hood. That
means you can assign a number literal, assuming it will fit into the unsigned 16-bit
range (65535 or less). For example, the following are all legal:
char a = 0x892; // hexadecimal literal
char b = 982; // int literal
char c = (char)70000; // The cast is required; 70000 is
// out of char range
Literal Values for All Primitive Types (Exam Objectives 1.3 and 7.6) 189
char d = (char) -98; // Ridiculous, but legal
STRING LITERAL:
A string literal is a source code representation of a value of a String object. For
example, the following is an example of two ways to represent a string literal:
String s = "Bill Joy";
System.out.println("Bill" + " Joy");
Although strings are not primitives,they can be represented as literals—in other words, typed directly into code.

No comments:

Post a Comment