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.
int million = 1_000_000; long id = 0xCAFE_BABEL; double rate = 1.5e-3; char tab = '\t';
Try it
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.
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_000is fine,_1000,1000_and0x_FFare errors. - Range checks. An
intliteral outside -2,147,483,648 to 2,147,483,647 is a compile error; addL. - Leading zero means octal.
010is 8, and09does not compile. - Hex and binary literals can be negative when the top bit is set:
0xFFFFFFFFis -1 as anint. - Floating literals default to
double.float f = 1.5;fails; write1.5for cast. - Uppercase suffix.
Lis clearer thanl. - String literals are interned. Identical literals are the same object, but compare strings with
equals()anyway. - Compile-time constants.
"a" + "b"and2 * 60are folded by the compiler; withfinalthey can be used inswitchlabels. - Text blocks (Java 15) strip common indentation; see text blocks.
Related
- int
- char
- Text blocks
- Escape sequences
- Tutorial: Variables