- Forward


Literals
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back Forward
  • Value:
    • A representation of a datum (or "piece of" information)
  • Token:
    • The smallest element of a larger construct
Literals
Back Forward
  • Definition:
    • A literal is a notation for writing/typing a particular value
  • Observations:
    • A literal has a type
    • A literal is a single token
Some Literals in Java
Back Forward

Type Example
byte N/A
short N/A
int 83
long 83L
float 2.9f
double 2.9
char 'd'
boolean true

Numeric Literals
Back Forward
  • Grouping Character:
    • You can't use a comma (US-style) or dot (European-style) as a grouping character (e.g., 100,000 is not a valid int literal) but you can use an underscore (e.g., 100_100 is a valid int literal)
  • Integer vs. Floating Point:
    • A numeric literal without a dot is always an integer number
    • A numeric literal with a single dot is always a floating point number even if there are no digits to the right (e.g., 1. is a double literal)
Character Literals
Back Forward
  • Most Character Literals:
    • Consist of a single symbol enclosed in single quotes (e.g., 'a', '7', '[')
  • A Consequence:
    • The single quote literal must be represented in a special way, using what is called an escape sequence, which, in many languages, is a symbol preceded by a backslash (e.g., '\'')
  • A Cascading Consequence:
    • The backslash literal must also be escaped (i.e., '\\')
  • Other Escaped Character Literals:
    • '\t' is the tab literal
    • '\n' is the newline literal
    • '\r' is the carriage return literal
    • '\"' is the double quote literal (the need for which will become apparent later)
There's Always More to Learn
Back -