๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Literals in Java  


Introduction

  • Literals are constants used in Java programs to represent fixed values.
  • They represent fixed values such as numeric values, characters, strings etc which are directly assigned to the variables.
  • For example :
    int rollno = 101;
    Variables in Java in Java

Types of Literals

There are many types of literals in Java which are as below :-
   1. Integer Literal
   2. Floating-Point Literal
   3. Character Literal
   4. String Literal
   5. Boolean Literal
   6. Null Literal

1. Integer Literals
  • Integer Literals represents the whole numbers and can be written in different number systems.
  • Difference types of Integer Literals are :-
    1. Decimal (Base 10): These are regular whole numbers (e.g., int num = 42;).
    2. Binary (Base 2): These starts with 0b or 0B (e.g., int bin = 0b1010;).
    3. Octal (Base 8): These starts with 0 (e.g., int oct = 010;).
    4. Hexadecimal (Base 16): These starts with 0x or 0X (e.g., int hex = 0x1F;).
  • Rules for Integer Literals are:
    • By default, integer literals are of type int.
    • Use L or l to specify a long literal (e.g., long bigNum = 123456789L;).
  • Program for Integer Literal :
    public class IntegerLiteralsExample
    {
        public static void main(String[] args)
        {
            // Decimal Literal (Base 10): Regular whole numbers
            int decimal = 42;
            System.out.println("Decimal Literal: " + decimal); // Output: 42
    
            // Binary Literal (Base 2): Starts with 0b or 0B
            int binary = 0b1010; // Binary for decimal 10
            System.out.println("Binary Literal: " + binary); // Output: 10
    
            // Octal Literal (Base 8): Starts with 0
            int octal = 010; // Octal for decimal 8
            System.out.println("Octal Literal: " + octal); // Output: 8
    
            // Hexadecimal Literal (Base 16): Starts with 0x or 0X
            int hexadecimal = 0x1F; // Hexadecimal for decimal 31
            System.out.println("Hexadecimal Literal: " + hexadecimal); // Output: 31
    
            // Long Literal: Specified with L or l at the end
            long bigNum = 123456789L;
            System.out.println("Long Literal: " + bigNum); // Output: 123456789
    
            // Example of usage of all types together in calculations
            int sum = decimal + binary + octal + hexadecimal;
            System.out.println("Sum of all literals: " + sum); // Output: 91
        }
    }
    Output:
    Decimal Literal: 42
    Binary Literal: 10
    Octal Literal: 8
    Hexadecimal Literal: 31
    Long Literal: 123456789
    Sum of all literals: 91
2. Floating-Point Literals
  • Floating-Point Literals represents the numbers with decimal points.
  • Difference types of Floating-Point Literals are :-
    1. Float: These ends with F or f suffix (e.g., float pi = 3.14F;).
    2. Double: These are the default type for decimal literals (e.g., double e = 2.718;).
  • Rules for Floating-Point Literals are:
    • Use scientific notation for very large or small numbers (e.g., double largeNum = 1.23e4;).
  • Program for Floating-Point Literal :
    public class FloatingPointLiteralsExample
    {
        public static void main(String[] args)
        {
            // Float Literal: Ends with F or f
            float pi = 3.14F; // The 'F' indicates it's a float literal
            System.out.println("Float Literal (pi): " + pi); // Output: 3.14
    
            // Double Literal: Default type for decimal numbers
            double e = 2.718; // By default, this is considered a double
            System.out.println("Double Literal (e): " + e); // Output: 2.718
    
            // Scientific Notation: Large number in scientific format
            double largeNum = 1.23e4; // Equivalent to 1.23 * 10^4 = 12300
            System.out.println("Scientific Notation (largeNum): " + largeNum); // Output: 12300.0
    
            // Another example of scientific notation: Very small number
            double smallNum = 4.56e-3; // Equivalent to 4.56 * 10^-3 = 0.00456
            System.out.println("Scientific Notation (smallNum): " + smallNum); // Output: 0.00456
    
            // Demonstrating precision with double
            double preciseNum = 3.14159265359; // Double can hold many decimal places
            System.out.println("Double with precision (preciseNum): " + preciseNum); // Output: 3.14159265359
        }
    }
    Output:
    Float Literal (pi): 3.14
    Double Literal (e): 2.718
    Scientific Notation (largeNum): 12300.0
    Scientific Notation (smallNum): 0.00456
    Double with precision (preciseNum): 3.14159265359
3. Character Literals
  • Character Literals represent a single character enclosed in single quotes (').
  • Examples of Character Literals are :-
    1. char letter = 'A';
    2. char digit = '7';
    3. char specialChar = '@';
  • Rules for Character Literals are:
    • Character Literals must represent a single Unicode character.
    • Escape sequences can be used for special characters:
      • \n (Newline), \t (Tab), \' (Single quote), \\ (Backslash), etc.
  • Program for Character Literal :
    public class CharacterLiteralsExample
    {
        public static void main(String[] args)
        {
            // Character Literal: A single character enclosed in single quotes
            char letter = 'A'; // Represents the character 'A'
            System.out.println("Character Literal (letter): " + letter); // Output: A
    
            // Character Literal: A digit as a character
            char digit = '7'; // Represents the character '7'
            System.out.println("Character Literal (digit): " + digit); // Output: 7
    
            // Character Literal: A special character
            char specialChar = '@'; // Represents the character '@'
            System.out.println("Character Literal (specialChar): " + specialChar); // Output: @
    
            // Using Escape Sequences for special characters
            char newlineChar = '\n'; // Represents a newline
            char tabChar = '\t'; // Represents a tab
            char singleQuoteChar = '\''; // Represents a single quote
            char backslashChar = '\\'; // Represents a backslash
    
            // Output using escape sequences
            System.out.println("Escape Sequence (newline):" + newlineChar + "This is after newline.");
            System.out.println("Escape Sequence (tab):" + tabChar + "This is after tab.");
            System.out.println("Escape Sequence (single quote): " + singleQuoteChar + "This is single quote.");
            System.out.println("Escape Sequence (backslash): " + backslashChar + "This is backslash.");
        }
    }
    Output:
    Character Literal (letter): A
    Character Literal (digit): 7
    Character Literal (specialChar): @
    Escape Sequence (newline):
    This is after newline.
    Escape Sequence (tab):	This is after tab.
    Escape Sequence (single quote): 'This is single quote.
    Escape Sequence (backslash): \This is backslash.
4. String Literals
  • String Literals represent a sequence of characters enclosed in double quotes (").
  • Examples of String Literals are :-
    1. String greeting = "Hello, World!";
    2. String empty = ""; (An empty string).
  • Rules for String Literals are:
    • Strings are immutable in Java. (explained in String chapter)
    • Can include escape sequences (e.g., "Line1\nLine2").
  • Program for String Literal :
    public class StringLiteralsExample
    {
        public static void main(String[] args)
        {
            // String Literal: A sequence of characters enclosed in double quotes
            String greeting = "Hello, World!"; // A simple string literal
            System.out.println("String Literal (greeting): " + greeting); // Output: Hello, World!
    
            // String Literal: An empty string
            String empty = ""; // An empty string
            System.out.println("String Literal (empty): '" + empty + "'"); // Output: ''
    
            // String with Escape Sequences
            String multiLineString = "Line1\nLine2"; // Using escape sequence \n for newline
            System.out.println("String with Escape Sequences (multiLineString): " + multiLineString);
            // Output:
            // Line1
            // Line2
    
            String quotedString = "He said, \"Hello!\""; // Using escape sequence \" for double quote
            System.out.println("String with Escape Sequences (quotedString): " + quotedString);
            // Output: He said, "Hello!"
    
            String tabbedString = "Item1\tItem2"; // Using escape sequence \t for tab
            System.out.println("String with Escape Sequences (tabbedString): " + tabbedString);
            // Output: Item1    Item2
        }
    }
    Output:
    String Literal (greeting): Hello, World!
    String Literal (empty): ''
    String with Escape Sequences (multiLineString): Line1
    Line2
    String with Escape Sequences (quotedString): He said, "Hello!"
    String with Escape Sequences (tabbedString): Item1	Item2
5. Boolean Literals
  • Boolean Literals represent one of two values: true or false.
  • Examples of Boolean Literals are :-
    1. boolean isJavaFun = true;
    2. boolean isHot = false;
  • Rules for Boolean Literals are:
    • Boolean Literals are used for conditional expressions and control flow.
  • Program for Boolean Literal :
    public class BooleanLiteralsExample
    {
        public static void main(String[] args)
        {
            // Boolean Literals: Represent either true or false
            boolean isJavaFun = true; // The value of isJavaFun is true
            boolean isHot = false;    // The value of isHot is false
    
            // Printing the Boolean literals
            System.out.println("Is Java Fun? " + isJavaFun); // Output: true
            System.out.println("Is it Hot? " + isHot);       // Output: false
    
            // Using Boolean literals in a conditional expression (if-else)
            if (isJavaFun) {
                System.out.println("Java is fun!");  // This will print as isJavaFun is true
            } else {
                System.out.println("Java is not fun!");
            }
    
            // Using Boolean literals for control flow (example with boolean flags)
            if (!isHot) {
                System.out.println("It is not hot today!");  // This will print as isHot is false
            } else {
                System.out.println("It is hot today!");
            }
        }
    }
    Output:
    Is Java Fun? true
    Is it Hot? false
    Java is fun!
    It is not hot today!
6. Null Literal
  • Null Literal represents the absence of a value for an object reference.
  • Examples of Null Literal is :-
    1. String str = null;
  • Rules for Null Literals are:
    • null can only be assigned to reference types, not primitive data types.
  • Program for Null Literal :
    public class NullLiteralExample
    {
        public static void main(String[] args)
        {
            // Null Literal: Represents the absence of a value for an object reference
            String str = null; // Null literal assigned to a reference type
    
            // Checking if the object reference is null
            if (str == null)
            {
                System.out.println("The string is null, no value assigned.");
            }
            else
            {
                System.out.println("The string has a value: " + str);
            }
        }
    }
    Output:
    The string is null, no value assigned.

Underscores in Numeric Literals (Java 7+)

  • We can use underscores in numeric literals to improve readability.
  • For example :-
    1. int million = 1_000_000;
    2. double pi = 3.141_592_653;
  • Rules to use Underscores in Numeric Literals :
    • Underscores cannot be used at the start or end of the literal, or next to a decimal point.
  • Program for Underscores in Numeric Literals :
    public class NumericLiteralsWithUnderscore
    {
        public static void main(String[] args)
        {
            // Using underscores to improve readability in numeric literals
            int million = 1_000_000;    // Underscores to separate thousands
            double pi = 3.141_592_653;  // Underscores in a floating-point number
    
            // Printing the values
            System.out.println("Million: " + million);  // Output: 1000000
            System.out.println("Pi value: " + pi);      // Output: 3.141592653
        }
    }
    Output:
    Million: 1000000
    Pi value: 3.141592653