☕ Java

Literals

A literal is a fixed value written directly in your source code — 42, 3.14, 'A', true, "Hello". Every literal has a type, and understanding how Java interprets each one prevents subtle bugs around type mismatches, overflow, and precision loss.

What Is a Literal?

A literal is a value you write directly in source code — a fixed, hardcoded value that doesn't come from a variable, method call, or computation. Every literal has a specific type that Java infers from how it's written. Understanding literals matters because Java uses the form of the literal — not where it's assigned — to determine its type. Writing 100 gives you an int. Writing 100L gives you a long. Writing 100.0 gives you a double. Writing 100.0f gives you a float. Getting this wrong causes compile errors, silent overflow, and precision loss.

Integer Literals

Integer literals default to type int. Add an L suffix to make them long. They can be written in four bases: decimal, hexadecimal, octal, and binary.
Java
// Decimal (base 10) — default:
int age = 25;
int negative = -100;
int million = 1000000;

// Underscore separators (Java 7+) — purely visual, ignored by compiler:
int million2 = 1_000_000;
int creditCard = 1234_5678_9012_3456;
int binary = 0b1111_0000_1111_0000;

// Long literals — L suffix (uppercase L preferred, lowercase l looks like 1):
long population = 8_000_000_000L;   // exceeds int range — L required
long fileSize = 10_737_418_240L;    // 10 GB in bytes
long small = 100L;                  // L suffix valid even for small values

// Hexadecimal (base 16) — 0x prefix:
int hex = 0xFF;        // 255
int color = 0xFF5733;  // RGB color value
long macAddr = 0x001A_2B_3C_4D_5EL;

// Binary (base 2, Java 7+) — 0b prefix:
int flags = 0b1010_1010;   // 170
int mask = 0b1111_1111;    // 255

// Octal (base 8) — 0 prefix (rarely used, easy to confuse with decimal):
int octal = 0777;    // 511 — leading zero means octal!
int trap = 010;      // 8, NOT 10 — leading zero is octal prefix

// Type matters — integer literal is int by default:
long wrong = 3_000_000_000;   // COMPILE ERROR — 3 billion exceeds int range
long right = 3_000_000_000L;  // correct — L suffix makes it a long literal

Floating-Point Literals

Floating-point literals default to type double. Add an f suffix for float. They support decimal and scientific notation.
Java
// Double literals — default (no suffix needed):
double pi = 3.141592653589793;
double price = 19.99;
double gravity = 9.81;
double small = 0.001;

// d suffix is optional for double — rarely used:
double x = 3.14d;    // same as 3.14

// Float literals — f suffix required:
float piFloat = 3.14159f;
float temp = -3.5f;

// Without f, decimal literals are double — assigning to float fails:
float bad = 3.14;    // COMPILE ERROR — possible lossy conversion from double to float
float good = 3.14f;  // correct

// Scientific notation:
double avogadro = 6.022e23;    // 6.022 × 10^23
double electron = 9.109e-31;   // 9.109 × 10^-31
float lightSpeed = 3.0e8f;     // 3 × 10^8 (f suffix for float)

// Hexadecimal floating-point literals (rare, used in low-level/scientific code):
double hexFloat = 0x1.8p1;     // 3.0 — (1 + 8/16) × 2^1

// Special double values:
double inf = Double.POSITIVE_INFINITY;    // 1.0 / 0.0
double negInf = Double.NEGATIVE_INFINITY; // -1.0 / 0.0
double nan = Double.NaN;                  // 0.0 / 0.0

// Underscores work in floating-point literals too:
double precise = 3.141_592_653_589_793;

Character Literals

Character literals are single characters enclosed in single quotes. They represent a single Unicode character stored as a 16-bit unsigned integer.
Java
// Basic character literals — single quotes:
char letter = 'A';
char digit = '7';
char space = ' ';

// Escape sequences — special characters with backslash:
char newline = '\n';     // line feed (U+000A)
char tab = '\t';         // horizontal tab (U+0009)
char carriageReturn = '\r'; // carriage return (U+000D)
char backslash = '\\';     // backslash itself
char singleQuote = '\'';    // single quote
char doubleQuote = '"';   // double quote (no escape needed in char literal)
char nullChar = '\0';    // null character (U+0000)

// Unicode escape sequences — \uXXXX:
char omega = '\u03A9';   // Ω — Greek capital Omega
char rupee = '\u20B9';   // ₹ — Indian Rupee sign
char copyright = '\u00A9'; // ©

// char is a 16-bit integer — numeric literals work:
char a = 65;              // 'A' — decimal code point
char b = 0x42;            // 'B' — hex code point

// Common mistake — double quotes vs single quotes:
char wrong = "A";   // COMPILE ERROR — "A" is a String, not a char
char right = 'A';   // correct

// char arithmetic:
char c = 'A';
System.out.println(c + 1);         // 66int arithmetic
System.out.println((char)(c + 1)); // 'B' — cast back to char

Boolean Literals

Boolean literals are the simplest — exactly two possible values: true and false. They are lowercase keywords and cannot be used as identifiers.
Java
// The only two boolean literals:
boolean yes = true;
boolean no = false;

// Boolean fields default to false:
class Example {
    boolean flag;   // false by default
}

// Booleans are NOT integers in Java (unlike C/C++):
boolean b = 1;      // COMPILE ERROR — int cannot be converted to boolean
boolean b2 = 0;     // COMPILE ERROR
if (1) { }          // COMPILE ERROR — condition must be boolean, not int

// Boolean expressions produce boolean values:
boolean isAdult = age >= 18;
boolean isValid = email != null && email.contains("@");
boolean isEmpty = list.size() == 0;

// Correct boolean comparison:
if (isActive == true) { }    // works but redundant
if (isActive) { }            // preferred — cleaner
if (isActive == false) { }   // works but redundant
if (!isActive) { }           // preferred

// true and false are reserved — cannot be used as identifiers:
int true = 1;     // COMPILE ERROR
String false = ""; // COMPILE ERROR

String Literals

String literals are sequences of characters enclosed in double quotes. Unlike the other literals, String is not a primitive type — it's a class. But Java gives String literals special treatment through the String pool.
Java
// String literals — double quotes:
String name = "Alice";
String empty = "";
String space = " ";
String sentence = "The quick brown fox";

// Escape sequences inside String literals:
String newline = "Line 1\nLine 2";      // embedded newline
String tab = "Col1\tCol2";             // embedded tab
String quote = "She said \"Hello\"";   // embedded double quotes
String path = "C:\\Users\\Alice";   // Windows path — double backslashes
String unicode = "\u20B9 1,000";       // ₹ 1,000

// String concatenation with + operator:
String first = "Hello";
String second = "World";
String combined = first + ", " + second + "!";  // "Hello, World!"

// Any type concatenated with String becomes String:
int count = 42;
String message = "Count: " + count;    // "Count: 42"
boolean flag = true;
String status = "Active: " + flag;     // "Active: true"

// Text blocks (Java 15+) — multiline strings with """ delimiters:
String json = """
        {
            "name": "Alice",
            "age": 25,
            "active": true
        }
        """;

String html = """
        <html>
            <body>
                <p>Hello, World!</p>
            </body>
        </html>
        """;

// Text blocks preserve indentation relative to the closing """
// Leading whitespace common to all lines is stripped automatically

// String pool — literals are interned:
String a = "Hello";
String b = "Hello";
System.out.println(a == b);       // true — same pool object
String c = new String("Hello");
System.out.println(a == c);       // falsenew forces heap allocation
System.out.println(a.equals(c));  // true  — same content

The null Literal

null is a special literal that represents the absence of a reference. It can be assigned to any reference type variable and is the default value for all reference type fields.
Java
// null can be assigned to any reference type:
String name = null;
int[] arr = null;
BankAccount account = null;

// null cannot be assigned to primitives:
int x = null;        // COMPILE ERROR
boolean b = null;    // COMPILE ERROR

// null is typeless — it's compatible with any reference type:
String s = null;
Integer i = null;
Object o = null;

// Checking for null:
if (name != null) {
    System.out.println(name.length());   // safe
}

// Dereferencing null throws NullPointerException:
String s2 = null;
s2.length();    // throws NullPointerException at runtime

// null in string concatenation — becomes the string "null":
String result = "Value: " + null;
System.out.println(result);   // "Value: null"

// null comparisons:
System.out.println(null == null);   // true
System.out.println(null instanceof String);  // falseinstanceof on null is always false

Literal Type Summary

Quick reference for how Java determines the type of each literal from its syntax:
Java
// Integer literals:
42          // int
42L         // long
0xFF        // int (hex)
0b1010      // int (binary)
0777        // int (octal)

// Floating-point literals:
3.14        // double (default)
3.14d       // double (explicit)
3.14f       // float
6.022e23    // double (scientific notation)

// Character literals:
'A'         // char
'\n'        // char (escape sequence)
'\u03A9'   // char (Unicode escape)

// Boolean literals:
true        // boolean
false       // boolean

// String literals:
"Hello"     // String
""          // String (empty)
"""..."""   // String (text block, Java 15+)

// Null literal:
null        // null type (compatible with any reference type)