Literals

From Wikibooks, open books for an open world
Jump to: navigation, search

Basic arithmetic Java Programming
Literals
Methods
Navigate Language Fundamentals topic: v  d  e )

Java Literals are syntactic representations of boolean, character, numeric, or string data. Literals provide a means of expressing specific values in your program. For example, in the following statement, an integer variable named count is declared and assigned an integer value. The literal 0 represents, natually enough, the value zero.

Example Code section 3.62: Numeric literal.
  1. int count = 0;
    

The following method call passes a String literal "int count = 0;" the boolean literal true and the special null value null to the method parse():

Example Code section 3.63: Literals.
  1. List items = parse("int count = 0;", true, null);
    

Boolean Literals[edit]

There are two Boolean literals

  • true represents a true boolean value
  • false represents a false boolean value

There are no other boolean literals, because there are no other boolean values!

Numeric Literals[edit]

There are three types of numeric literals in Java.

Character Literals[edit]

Character literals are constant valued character expressions embedded in a Java program. Java characters are sixteen bit Unicode characters, ranging from 0 to 65535. Character literals are expressed in Java as a single quote, the character, and a closing single quote ('a', '7', '$', 'π'). Character literals have the type char, an unsigned integer primitive type. Character literals may be safely promoted to larger integer types such as int and long. Character literals used where a short or byte is called for must be cast to short or byte since truncation may occur.

Integer Literals[edit]

In Java, you may enter integer numbers in several formats:

  1. As decimal numbers such as 1995, 51966. Negative decimal numbers such as -42 are actually expressions consisting of the integer literal with the unary negation operation -.
  2. As octal numbers, using a leading 0 (zero) digit and one or more additional octal digits (digits between 0 and 7), such as 077. Octal numbers may evaluate to negative numbers; for example 037777777770 is actually the decimal value -8.
  3. As hexadecimal numbers, using the form 0x (or 0X) followed by one or more hexadecimal digits (digits from 0 to 9, a to f or A to F). For example, 0xCAFEBABEL is the long integer 3405691582. Like octal numbers, hexadecimal literals may represent negative numbers.
  4. Starting in J2SE 7.0, as binary numbers, using the form 0b (or 0B) followed by one or more binary digits (0 or 1). For example, 0b101010 is the integer 42. Like octal and hex numbers, binary literals may represent negative numbers.

In addition, if an integer literal has a letter el suffix (either the character l or the character L), it denotes a long integer rather than a standard integer. For example, 3405691582L is a long integer literal. Long integers are 8 bytes in length as opposed to the standard 4 bytes for int. It is best practice to use the suffix L instead of l to avoid confusion with the digit 1 (one) which looks like l in many fonts: 200l2001.

Starting in J2SE 7.0, you may insert underscores between digits in a numeric literal. They are ignored but may help readability by allowing the programmer to group digits.

Floating Point Literals[edit]

Floating point numbers are expressed as decimal fractions or as exponential notation:

Example Code section 3.64: Floating point literals.
  1. double decimalNumber = 5.0;
    
  2. decimalNumber = 5d;
    
  3. decimalNumber = 0.5;
    
  4. decimalNumber = 10f;
    
  5. decimalNumber = 3.14159e0;
    
  6. decimalNumber = 2.718281828459045D;
    
  7. decimalNumber = 1.0e-6D;
    

Floating point numbers consist of:

  1. an optional leading + or - sign (indicating a positive or negative value, the default being positive if no sign exists)
  2. one of the following number formats
    • integer digits (must be followed by either an exponent or a suffix or both, to distinguish it from an integer literal)
    • integer digits .
    • integer digits . integer digits
    • . integer digits
  3. an optional exponent of the form
    • the exponent indicator e or E
    • an optional exponent sign + or - (the default being a positive exponent)
    • integer digits representing the integer exponent value
  4. an optional floating point suffix:
    • either f or F indicating a single precision (4 bytes) floating point number, or
    • d or D indicating the number is a double precision floating point number (by default, thus the double precision (8 bytes) is default).

Here, integer digits represents one or more of the digits 0 through 9.

Starting in J2SE 7.0, you may insert underscores between digits in a numeric literal. They are ignored but may help readability by allowing the programmer to group digits.

String Literals[edit]

String literals consist of the double quote character (") (ASCII 34, hex 0x22), zero or more characters (including Unicode characters), followed by a terminating double quote character ("), such as: "Ceci est une string."

So a string literal follows the following grammar:

<STRING :
        "\""
        (    (~["\"","\\","\n","\r"])
        |("\\"
            ( ["n","t","b","r","f","\\","'","\""]
            |["0"-"7"](["0"-"7"])?
            |["0"-"3"]["0"-"7"]["0"-"7"]
            )
        )
        )*
        "\"">

Within string and character literals, the backslash character can be used to escape special characters, such as unicode escape sequences, or the following special characters:

Name Character ASCII hex
Backspace \b 8 0x08
TAB \t 9 0x09
NUL character \0 0 0x00
newline \n 10 0x0a
carriage control \r 13 0xd
double quote \" 34 0x22
single quote \' 39 0x27
backslash \\ 92 0x5c

String literals may not contain unescaped newline or linefeed characters. However, the Java compiler will evaluate compile time expressions, so the following String expression results in a string with three lines of text:

Example Code section 3.65: Multi-line string.
  1. String text = "This is a String literal\n"
    
  2.             + "which spans not one and not two\n"
    
  3.             + "but three lines of text.\n";
    

null[edit]

null is a special Java literal which represents a null value: a value which does not refer to any object. It is an error to attempt to dereference the null value — Java will throw a NullPointerException. null is often used to represent uninitialized state.

Mixed Mode Operations[edit]

In concatenation operations, the values in brackets are concatenated first. Then the values are concatenated from the left to the right. Be careful when mixing character literals and integers in String concatenation operations:

Example Code section 3.66: Concatenation operations.
  1. int one = '1';
    
  2. int zero = '0';
    
  3.  
    
  4. System.out.println("120? " + one + '2' + zero);
    
Computer code Console for Code section 3.66
120? 49248

The unexpected results arise because '1' and '0' are converted twice. The expression is concatenated as such:

"120? " + one + '2' + zero
"120? " + 49 + '2' + 48
"120? 49" + '2' + 48
"120? 492" + 48
"120? 49248"
  1. one and zero are integers. So they store integer values. The integer value of '1' is 49 and the integer value of '0' is 48.
  2. So the first concatenation concatenates "120? " and 49. 49 is first converted into String, yielding "49" and the concatenation returns the string "120? 49".
  3. The second concatenation concatenates "120? 49" and '2'. '2' is converted into the String "2" and the concatenation returns the string "120? 492".
  4. The concatenation between "120? 492" and '0' returns the string "120? 49248".

The code section 67 yields the desired result:

Example Code section 3.67: Correct primitive type.
  1. char one = '1';
    
  2. char zero = '0';
    
  3.  
    
  4. System.out.println("120? " + one + '2' + zero);
    
Computer code Console for Code section 3.67
120? 120
Test your knowledge

Question 3.9: Consider the following code:

Example Question 3.9: New concatenation operations.
  1. int one = '1';
    
  2. int zero = '0';
    
  3.  
    
  4. System.out.println("  3? " + (one + '2' + zero));
    
  5. System.out.println("102? " + 100 + '2' + 0);
    
  6. System.out.println("102? " + (100 + '2' + 0));
    
Computer code Console for Question 3.9
  3? 147
102? 10020
102? 150

Explain the results seen.

Answer

For the first line:

" 3? " + (one + '2' + zero)
" 3? " + (49 + '2' + 48)
" 3? " + (89 + 48)
" 3? " + 147
" 3? 147"

For the second line:

"102? " + 100 + '2' + 0
"102? 100" + '2' + 0
"102? 1002" + 0
"102? 10020"

For the last line:

"102? " + (100 + '2' + 0)
"102? " + (150 + 0)
"102? " + 150
"102? 150"


Basic arithmetic Java Programming
Literals
Methods