Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Types and Literals

Java literals

Reference for Java literals: integer, floating-point, hexadecimal, binary and octal numbers, underscores, suffixes, char escapes, strings and text blocks.

A literal is a value written directly in source code. Java has literals for integers, floating-point numbers, characters, strings, booleans and null. The form of a literal decides its type: 10 is an int, 10L a long, 10.0 a double, 10f a float, '1' a char and "10" a String.

Java also lets you write numbers in several bases and group digits with underscores, which makes constants and bit masks much easier to read.

Java
int million = 1_000_000;
long id = 0xCAFE_BABEL;
double rate = 1.5e-3;
char tab = '\t';

Try it

Java Numeric literal forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Character, string and text block literals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Kind Examples Type
Decimal integer 42, 1_000 int
Long integer 42L, 0xFFFF_FFFFL long
Hexadecimal 0x2A, 0XFF int / long
Octal 052 int / long
Binary 0b101010 int / long
Floating point 3.14, .5, 1e3, 2.5d double
Single precision 3.14f, 1e3F float
Character 'a', '\n', 'รฉ' char
String "text" String
Text block """ newline ... """ String
Boolean true, false boolean
Null null the null type

Escape sequences in chars and strings: \n \t \r \b \f \s \0..\377 \' \" \\ \uXXXX; text blocks add \<newline> (join lines).

Usage notes

  • Underscores may appear only between digits: 1_000 is fine, _1000, 1000_ and 0x_FF are errors.
  • Range checks. An int literal outside -2,147,483,648 to 2,147,483,647 is a compile error; add L.
  • Leading zero means octal. 010 is 8, and 09 does not compile.
  • Hex and binary literals can be negative when the top bit is set: 0xFFFFFFFF is -1 as an int.
  • Floating literals default to double. float f = 1.5; fails; write 1.5f or cast.
  • Uppercase suffix. L is clearer than l.
  • String literals are interned. Identical literals are the same object, but compare strings with equals() anyway.
  • Compile-time constants. "a" + "b" and 2 * 60 are folded by the compiler; with final they can be used in switch labels.
  • Text blocks (Java 15) strip common indentation; see text blocks.