Java Literals – Concept Every Java Programmer Must Know

In this Java article, we will learn one of the most fundamentals of Java that every Java learner must know. The topic is Literals in Java that gives us a way to specify values in our Java programs. There are many types of literals in java that we will cover in this article with the implementation examples. So firstly let’s start with an introduction to literal in Java and then we will move towards the types of Java literals.

Types of Java Literals

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Literals in Java

Literals are the data items that have fixed or constant values. Therefore we also call literals as constants in Java. Literals can represent various types of values such as numeric, character, boolean, or String values. We can assign literals to any of the 8 primitive data types in Java. For example, let’s consider an example that you frequently use in your programs.                                  

int number = 20;

Here the number is an integer variable and we have assigned a value 20 to it. Here 20 is literal.

java literals

Note: We can’t change the value inside the literal during the program execution.

Types of Java Literals

Java allows 6 kinds of literals which are:

1. Integer literals
2. Floating literals
3. Boolean literals
4. Character literals
5. String literals
6. Null literal

Let’s take a deep dive into each of them:

1. Java Integer Literals

Integer literals are the whole numbers that don’t contain any fractional or exponential part. They can be either negative or positive or may contain no sign.

The rule to write an integer literals is that there must be at least one digit and there must not be any decimal point. There can be positive(+) or negative(-) signs in a literal. If the literal has no sign, then it is considered as a positive number. There should not be any commas in an integer literal.

Integer Literals are further divided into three categories:

1. Decimal Integer Literals
2. Octal Integer Literals
3. HexaDecimal Integer Literals

1. Decimal Integer Literals(Base 10)

A decimal integer literal is an integer literal containing digits between 0 to 9. We can consider a sequence of digits to be a decimal integer literal unless it begins with 0 digits.
For example:

1256, 67, +98, -54 are some valid decimal integer literals. But the number 0987 is not a valid decimal integer literal.

Example:

int x1 = 100; //A valid decimal literal
int x2 = -467; //A negative decimal constant
int x3 = 089; //Not a decimal literal

2. Octal Integer Literals(Base 8)

An Octal integer literal is a literal containing combination of digits between 0 to 7. The sequence of such literals always starts with 0 digits. For example, a decimal integer 8 can be written as 010 in the octal number form. And 49 in decimal can be written as 061 as an octal integer literal. Make sure while writing octal literals they should always begin with 0 and should not contain any 8 or 9 in them, as 8 and 9 are both invalid octal digits.

Example:

int x1 = 0765; //Octal constant
int x2 = 0987; //Invalid as it contains 8 and 9

3. Hexadecimal Integer Literals(Base 16)

A sequence of digits starting with either 0x or 0X falls under the category of hexadecimal integer literals. In such literals there can be a combination of digits from 0 to 9 and also there can be alphabet characters from A to F. We can use both uppercase and lowercase letters. All other letters other than A to F are illegal. For example, the decimal integer 12 can be written as 0XC in hexadecimal form.

Example:

int x1 = 0x54; //Hexadecimal integer
int x2 = -0X6BF8; //Valid negative hexadecimal literal

Note: We can also use the suffix l or L and u or U to represent Long and unsigned values respectively.

package com.techvidvan.literals;
public class IntegerLiterals {
  public static void main(String[] args) {
    int decimalLiteral = 561; // decimal literal
    int octalLiteral = 01204; // octal literal
    int hexaDecimalLiteral = 0x1BfA; // Hexa-decimal literal

    System.out.println("The value of Decimal literal is: " + decimalLiteral);
    System.out.println("The value of Octal literal is: " + octalLiteral);
    System.out.println("The value of Hexa-decimal literal is: " + hexaDecimalLiteral);
  }
}

Output:
The value of Decimal literal is: 561
The value of Octal literal is: 644
The value of Hexa-decimal literal is: 7162

2. Floating literals in Java

Floating literals are the literals that have fractional parts and decimal points in them. They are also known as the real literals. We can write to them in two forms-either in fractional form or in exponential form. We can’t specify them in octal or hexadecimal values; they can only be in decimal form. There is a decimal point(.) between the digits.

The rule to write a floating literal is that:
It should be in the fractional form containing at least one digit before a decimal point and at least one digit after the decimal point. There can also be a positive (+) or negative (-) sign before a floating literal. A real or floating literal without any sign is considered to be positive.

Some valid floating literals are:

2.0, 16.7, -13.0, -0.00987

Some invalid floating literals are:

7                    (No decimal point)
7.                   (No digit after decimal place)
+14/6           (/- illegal symbol used)
17.257.87     (Two decimal points)
34,789.50    (No commas allowed)

This was the representation of floating literals in fractional form. Now we will discuss the exponent form of floating literals.

A floating literal in the exponential form consists of 2 parts: mantissa and exponent. For example, 6.8 can be written as 0.68 x 101 = 0.68E01, where the mantissa part is 0.68(part appearing before E) and the exponent part is 1(the part appearing after E). E01 represents 101.

Some valid real literals in the exponent form are:

152E05
1.52E07
0.152E08
1520E04
152E+8
-0.172E-3

Some invalid real literals in the exponent form are:

172.E5         (At least a digit must follow the decimal point)
1.7E              (No digit specified for exponent)
0.17E2.3      (Exponent cannot have fractional part)
17,445E02   (No comma allowed)

Note: Every floating type is a double type and this is the reason why we cannot assign it directly to the float variable, to escape this situation we use f or F as a suffix, and for double we use d or D.

package com.techvidvan.literals;
public class FloatingPointLiteral {
  public static void main(String args[]) {
    double floatingLiteral1 = 987.678; // fractional floating literal
    double floatingLiteral2 = 089.0987 // It also acts as fractional floating litera
    double floatingLiteral3 = 1.234e20; // Exponential form

    System.out.println("The floating literal in fractional form is: " + floatingLiteral1;
    System.out.println("The floating literal in fractional form is: " + floatingLiteral2);
    System.out.println("The floating literal in exponential form is: " + floatingLiteral3);
  }
}

Output
The floating literal in fractional form is: 987.678
The floating literal in fractional form is: 89.0987
The floating literal in exponential form is: 1.234E20

3. Boolean Literals in Java

The Boolean literals have only two values- true and false. They contain only Boolean values. These are used for assigning flag variables or when there is a need for checking any condition. The Boolean literal can’t take any value other than true and false. We have to use the boolean data type.

Example:

boolean b1 = true; //valid boolean value
boolean b2 = false; //valid boolean value
boolean b3 = 5; //invalid boolean value

package com.techvidvan.literals;
public class BooleanLiterals {
  public static void main(String args[]) {
    boolean b1 = false;
    // boolean b2 = 7; This will generate an error, so comment this line
    int x = 20;
    if (x % 2 == 0) {
      b1 = true;
      System.out.println("The result for the if condition is: " + b1);
      System.out.println("The number is even");
    }
    else {
      b1 = false;
      System.out.println("The result for the if condition is: " + b1);
      System.out.println("The number is even");
    }
  }
}

Output
The result for the if the condition is: true
The number is even

4. Java Character literals

A character literal represents a single character that is enclosed in a single quote ‘’, as in ‘Z’. The rule for writing a character literal is that it must contain a single character enclosed within a single quote. We have to use the char data type to represent a character literal.

For example,

char ch = ‘A’;

Java allows us to have certain non-graphic characters as character literals. Nongraphic characters are the characters that we can’t directly from the keyboard; example backspaces, tabs, etc. These nongraphic characters can be represented as escape sequences.

There are many escape sequences in Java and they are listed in the following table:

Escape Sequences in Java

Some valid character literals are:
char c = ‘a’;
char c = ‘%’;
char c = ‘\t’;
char c = ‘\\’;
char c = ‘4’;
char c = ‘S’;

We can also use the character literals to represent an integer literal that shows the Unicode value of the character. It can specify the integer in decimal, octal or hexadecimal form but within the range of 0-65535.

Example, ch = ‘063’; is valid.

We can also specify the character literals in the UNICODE representation ‘\uxxxx’. Here xxxx represents 4 hexadecimal numbers.

For example, ch = ‘\u03a9’ //Here u03a9 is a hexadecimal number.

package com.techvidvan.literals;
public class CharacterLiteral {
  public static void main(String[] args) {
    char character = 'd';
    char unicodeCharacter = '\u0064';
    System.out.println("Character literal value is: " + character);
    System.out.println("Value of unicode character is: " + unicodeCharacter);
    System.out.println("\" is a symbol");
  }
}

Output
Character literal value is: d
Value of Unicode character is: d
” is a symbol

5. Java String Literals

The String literals represent multiple characters. A sequence of zero or more characters written within double quotes ” ” is known as a string. Each character in a string literal can also represent an escape sequence. All String-Literals belong to class String.

For example, Some valid string literals are:

String s = “Abc”
String s = “TechVidvan”
String s = “I love my country”
String s = “Rita\’s book” // \’ is an escape sequence
String s = “\ab” //\a is escape sequence

Some invalid string literals are:

String s = HelloWorld; //No Double quotes
String s = ‘TechVidvan’; //Single quote not allowed

package com.techvidvan.literals;
public class StringLiteral {
  public static void main(String[] args) {
    String myString = "Welcome to TechVidvan Tutorials of Java";

    // If we assign without "" then it treats as a variable and causes compiler error //String myString1 = Hello; 

    System.out.println(“The String is: “ + myString);
  }
}

Output
The String is: Welcome to TechVidvan Tutorials of Java

6. Null Literals

Finally, the Null literals are the values that represent null values. The null literals have only a single value (null). It shows the null reference. A null literal is of the null type.

Conclusion

In conclusion, Literals in Java are useful to provide values to the variables. We can assign the values to the variables according to their data types. There are 6 types of literals in Java but the null literal is not much used but can be considered as a literal. We commonly use the 5 types of literals in our Java programs. We should follow the rules of each literal while using them so as to maintain the correct syntax of the Java language. In this article, we discussed each type of literals in Java with examples.

Do not forget to share your TechVidvan Google Rating if you liked the article.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.