What Is a Literal in Programming? Explained with Examples

In programming, a literal is a fixed value written directly into the source code. It represents constant data that is not stored in a variable but used as-is in the program.

Types of Literals

  1. Integer Literal
    int x = 42;     // 42 is an integer literal
    
  2. Floating-point Literal
    pi = 3.14       // 3.14 is a floating-point literal
    
  3. Character Literal
    char grade = 'A';  // 'A' is a character literal
    
  4. String Literal
    let name = "John"; // "John" is a string literal
    
  5. Boolean Literal
    boolean isTrue = true;  // true is a boolean literal
    

Characteristics of Literals

  • Directly written in the source code.
  • Immutable (cannot be changed during program execution).
  • Commonly used to initialize variables or form expressions.

Full Example

x = 10           # 10 is an integer literal
y = 3.14         # 3.14 is a floating-point literal
z = "Hello"      # "Hello" is a string literal
flag = True      # True is a boolean literal

Literal vs Variable

Literal Variable
Fixed value A storage for data
Cannot be changed Value can be updated
Example: 42 Example: x = 42






0 Comments:

Post a Comment