Literals in Java

Literals are a value which you can assign to the variable or a constant.

There are five types of literals and are listed below:



  • It can be assigned to one of the integer data types; there are three types of integer literals.

  • Decimal integer literals: Base 10 [0-9]

  • Octal integer literals (starts with 0) [0-7]

  • Hexadecimal integer literals (0-9, A-F)

    Examples (imp. Interview questions)
  • int a=123;

  • int a=0123; (starting with zero)

  • int a=0x123A; (starting with zero & x)

  • It can be assigned to floating point variables declared with float or double datatypes.
    There are two types of representation:

    • Decimal pointer presentation

    • Exponential representation

  • Examples
  • double d16 = 99.99;

  • double d12 = 99.99e-5; // 99.99e-4

  • double d15 = 9.9E3; // (9.9*10*10*10)

  • It is a single character which is enclosed between single quotes ‘ ’

    • Example :

        ‘a’ ‘+’ ‘ ’
        ‘ ’ // invalid (because of space)

  • A character literal can be assigned to a character type variable.
    • Example :

        char ch1='a';

  • Each character which is enclosed in single quotation marks will have integer equivalent’s value as per ASCII character set as shown in the example below:

    • ‘a’ = 97, ‘b’ = 98, ------------- , ’y’ = 121, ’z’ =122

    • ‘A’ = 65, ‘B’ = 66, ------------- , ‘Y’ = 89, ‘Z’ = 90

    • ‘0’ = 48, ‘1’ = 49, ------------- , ‘8’ = 56, ‘9’ = 57

  • Java uses the character set UNICODE (Universal Code)

  • UNICODE character set takes two bytes of memory for each character and supports multi languages.

  • ASCII character set takes only one byte character and supports only English language.

  • There are two boolean literals:

    • True

    • False

  • Boolean literals can be assigned to the variables which are declared with boolean data type.

    • Example :
        boolean b=true;
  • It is a collection of one or more characters enclosed between double quotation marks.

  • String literals can be assigned to reference variable of type String.

Example:

Lab2.Java



Back to Java Language Chapter