CORE JAVA

ProwessApps Learning Portal

Java Literals


  • A Java literal is a sequence of characters (digit, letters and other characters) that represent constant value to be stored in variable.

  • A literal is the source code representation of a fixed value.

Java Specifies 5 major types of literals :
  1. Integer Literals

  2. Floating-Point Literals

  3. Character Literals

  4. String Literals

  5. Boolean Literals


1. Integer Literals :
  • An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int.

  • Values of the integral types byte, short, int, and long can be created from int literals.

  • There are four ways to represent integer number in the Java language :

    1. Decimal ( base 10 )

      int x = 20;

    2. Octal ( base 8 )

      int x = 076; (starts with 0)

    3. Hexadecimal ( base 16 )

      int x = 0x13A; (starts with 0x)

    4. Binary (base 2 )

      int x = 0b101; (starts with 0b)


2. Float-Point Literals :
  • Floating-Point numbers are defined as a number, a decimal symbol, and one or more numbers representing the fraction.

    For Example:
         double d = 223.56;
  • Floating-points literals are defined as double (64 bits) by default, so if you want to assign a floating-point literal to a variable of type float ( 32 bits),you must attach the suffix F or f to the number;

    For Example:
         float f = 223.56F;

3. Character Literals :
  • A character literal is represented by a single character in single quotes.

    For Example:
         char a = 'a' ;
         char c = '@' ;

  • You can also type in the Unicode value of the character, using the Unicode notation of prefixing the value with \u.

    For Example:
        char ch = '\u0041' ; //letter 'A'

4. String Literals :
  • In Java, string literals are enclosed within double quotes.

    For Example:
         String s = "Java Prowess" ;

  • String literals are not only a sequence of character as in 'C', these are objects of type java.lang.String

    . For Example:
         String s = "Java Prowess" ;

5. Boolean Literals :
  • Boolean literals are the source code representation for boolean value. A boolean value can only be defined as true or false.

  • Although in 'C' (and some other languages) it is common to use number to represent true or false, this will not work in Java.

       boolean b = true ;//Legal
       boolean b = 1 ;//Compiler Error




advertisement