BCA / B.Tech 9 min read

Literals in Java

What are Literals in Java?

A literal is a source code representation of a fixed value. In other words, literals are the constant values that you assign directly to variables in your code.

Types of Literals in Java:
  • Integer Literals: Represent whole numbers.
    • Decimal (base 10): int num = 101;
    • Octal (base 8, starts with 0): int num = 0146;
    • Hexadecimal (base 16, starts with 0x): int num = 0x65;
    • Binary (base 2, starts with 0b): int num = 0b1100101;
    • To specify a long literal, append an `L` or `l`: long bigNum = 3000000000L;
  • Floating-Point Literals: Represent numbers with decimal points.
    • Default to double: double pi = 3.14159;
    • To specify a float, append an `f` or `F`: float price = 29.95f;
  • Character Literals: Represent a single character, enclosed in single quotes.
    • char letter = 'A';
    • Can also use escape sequences for special characters: char newline = ' ';
  • String Literals: Represent a sequence of characters, enclosed in double quotes.
    • String greeting = "Hello, World!";
  • Boolean Literals: Represent the logical values of `true` and `false`.
    • boolean isLoggedIn = true;
  • Null Literal: Represents a `null` reference, meaning a variable that does not point to any object.
    • String name = null;