Java Literals

Category: Java   Tags: Java, Java Basic

A Java literal is nothing but a constant value e.g 100, "hello", 20.30 are some valid Java literals.

Integer Literals

Here is some Java integer literals example:

                          int i = 100;
                          int binary = 0b1010;
                          int dash = 123_456_789;

Beginning with JDK 7, we can have integer literals using binary. To do so, prefix the value with 0b or 0B:

                          int x = 0b1010;

It specifies the decimal value 10 using a binary literal.

Integer literal can have one or more underscores and it makes easier to read large integer literals. For example:

                            int x = 100_109_200;

When compiled all underscore will ignored and the actual value of x will be 100109200.

Boolean Literals

A Java boolean value can have true or false only, nothing else. For example:

                            boolean isValid = true;
                            boolean isRedColor = false;

Character Literals

Character literals are enclosed in single quotation marks for example 'a', 'A', '9', '+', '_', and '~'.

                            char c = 'A';

String Literals

String literals are enclosed between a pair of double quotes:

                            String str = "Hello Java!";

Floating-Point Literals

It is a whole number component followed by a decimal point followed by a fractional component. For example 98.21, 10.0.

A floating-point number plus a suffix that specifies a power of 10 by which the number is to be multiplied, for example 6.02E21, 27159E–05 are also a valid floating point number. The exponent is indicated by an E or e followed by a decimal number.