Literals in Java


Java Literals

Literal is also known as constant. A literal is a constant value which is compatible to a data type, a literal is used to assign a value to variable, to compare values or define constants. There are many types of constants (literals). They are:

  • Boolean literals
  • Integer literals
  • Floating literals
  • Character literals
  • String literals
  • Null literals

Each of them has a type associated with it. The type describes how the values behave and how they are stored

Boolean Literals:

The values true and false are treated as Boolean literals in Java programming. When we assign a value to a boolean variable, we can only use these two values. Example

boolean c = true;

Integer literals:

Integer data types consist of the following primitive data types: int,long, byte, and short. byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8) number systems as well. Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems for literals. Examples:

int decimal = 100;

int octal = 0144;

int hexa =  0x64;

Floating-point literals:

Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001. Java has two kinds of floating-point numbers: float and double. The default type when you write a floating-point literal is double, but you can designate it explicitly by appending the D (or d) suffix. example

Double=12.34;

Float 2.4;

Character literals:

char data type is a single 16-bit Unicode character. We can specify a character literal as a single printable character in a pair of single quote characters such as ‘a’, ‘#’, and ‘3’.example

char ch=’v’;

String Literals:

The set of characters in represented as String literals in Java. Always use “double quotes” for String literals. There are few methods provided in Java to combine strings, modify strings and to know whether to strings have the same values.Example

String s1=”veneeta”;

Null Literals:

The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the source code as ‘null’. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables.Example

For instance
s = null;

Comments are closed.