Literals: Writing Values Directly

Literals: Writing Values Directly in Java: A literal is a value written literally into your code. In , the is an integer literal.

Concept Explanation

A literal is a value written literally into your code. In int score = 100;, the 100 is an integer literal. Variables are labelled boxes; literals are the things you put in them.

Java has a literal form for each kind of data, and a few notation tricks worth knowing.


Literals by Type

// Integer literals
int decimal = 42;
int binary  = 0b101010;   // 0b prefix -> 42
int octal   = 052;        // leading 0  -> 42
int hex      = 0x2A;      // 0x prefix -> 42

// Long needs an L suffix when the value exceeds int range
long population = 8_100_000_000L;

// Floating point: double by default, F forces float
double pi = 3.14159;
float  ratio = 2.5F;
double scientific = 1.6e-19;   // 0.00000000000000000016

// Character literals use SINGLE quotes
char grade = 'A';
char newline = '\n';
char unicode = '\u0041';   // also 'A'

// String literals use DOUBLE quotes
String greeting = "Hello";

// Boolean and null
boolean active = true;
String missing = null;

Underscores for Readability

Since Java 7 you may place _ inside numeric literals. The compiler ignores them entirely:

int million   = 1_000_000;
long cardNum  = 1234_5678_9012_3456L;
int bitMask   = 0b1010_0101;

This is purely for human eyes — 1_000_000 and 1000000 are the same value.


Text Blocks (Java 15+)

For multi-line strings, triple quotes beat endless \n:

String json = """
    {
      "name": "Ada",
      "role": "engineer"
    }
    """;

Common Mistakes

  1. Missing the L: long big = 10000000000; fails — the literal is treated as an int before assignment and overflows.
  2. Missing the F: float f = 3.14; fails, because 3.14 is a double. Write 3.14F.
  3. Accidental octal: int code = 0755; is 493, not 755. A leading zero means octal.
  4. Quote confusion: 'Hello' is invalid — single quotes hold exactly one character.

Best Practices

  • Underscore long numbers: 50_000_000 is far easier to verify than 50000000.
  • Uppercase suffixes: Prefer 100L over 100l — lowercase L looks like the digit 1.
  • Name your magic numbers: final double TAX_RATE = 0.08; beats scattering 0.08 through your code.

Practice Exercises

  1. The Four Notations: Write the number 255 as a decimal, binary, octal, and hexadecimal literal, then print all four and confirm they match.
  2. The Overflow: Try long distance = 9999999999; without the L, read the error, then fix it.
  3. The Readable Constant: Declare the speed of light in metres per second as a long using underscores for grouping.