Literals

Integer, floating-point, character, string, boolean literals

6 min read

What are Literals?

A literal is a fixed value written directly in your code. It's the actual data you're assigning to variables.

Types of Literals

Integer Literals

  • Decimal: 10, -25, 0
  • Hexadecimal: 0x1A (prefix with 0x)
  • Octal: 012 (prefix with 0)
  • Binary: 0b1010 (prefix with 0b)
  • Long: 123L (suffix L)

Floating-Point Literals

  • Float: 3.14f (suffix f)
  • Double: 3.14 or 3.14d (default, optional suffix d)
  • Scientific notation: 1.5e2 (equals 150.0)

Character & String Literals

  • Character: 'A' (single character in single quotes)
  • String: "Hello" (text in double quotes)
  • Escape sequences: \n, \t, \\"

Boolean Literals

  • true or false only

💡 Tip: Use underscores in large numbers for readability: 1_000_000 instead of 1000000

Code Examples

Different ways to write integer literals

java
1// Integer literals
2int decimal = 255;       // Decimal
3int hex = 0xFF;          // Hexadecimal (255)
4int octal = 0377;        // Octal (255)
5int binary = 0b11111111; // Binary (255)
6long large = 1000000L;   // Long literal
7int readable = 1_000_000; // With underscores

Floating-point number literals with different precisions

java
1// Floating-point literals
2float pi = 3.14f;        // Float (note the f suffix)
3double e = 2.718281828; // Double (default)
4double scientific = 1.5e2;  // 150.0
5double small = 1.23e-4;     // 0.000123

Character and String literals with escape sequences

java
1// Character and String literals
2char letter = 'A';
3char digit = '5';
4char space = ' ';
5
6String message = "Hello, World!";
7String escaped = "He said \"Hello\"";  // With quotes
8String newline = "Line1\nLine2";          // With newline
9String tab = "Col1\tCol2";                // With tab

Boolean literals in conditional statements

java
1// Boolean literals
2boolean active = true;
3boolean inactive = false;
4
5if (active) {
6    System.out.println("System is running");
7}

Use Cases

  • Writing constant values directly in code
  • Initializing variables with fixed data
  • Creating different number formats (hex, octal, binary)
  • Working with character and string data
  • Setting boolean conditions

Common Mistakes to Avoid

  • Forgetting f suffix for float literals (becomes double)
  • Using double quotes for characters instead of single quotes
  • Incorrect escape sequences in strings
  • Using = instead of == in boolean expressions
  • Mixing up number formats (0x, 0, 0b)