Java Literals - Advanced Explanation
This document provides an advanced explanation of Java Literals. It covers compiler behavior,
memory ranges, escape sequences, String Constant Pool, null literal behavior, and tricky interview
cases.
1. Default Type Rules
By default, integer literals are of type int, and floating literals are of type double.
int x = 10; // int by default
long y = 10; // int can be stored in long
long z = 10L; // L suffix for long
float f = 3.14F; // F suffix for float
double d = 3.14; // default double
2. Range & Memory Sizes
Each primitive literal type has a fixed memory size and range:
3. Character Literal Escape Sequences
Java supports special escape sequences for characters:
4. String vs Char Literals
Difference between single character and String object.
char c = 'A'; // Unicode 65
String s = "A"; // Object in String Pool
System.out.println('A' + 1); // 66
System.out.println("A" + 1); // A1
5. String Literal Interning
String literals are stored in the String Constant Pool (SCP).
String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2); // true
String s3 = new String("Java");
System.out.println(s1 == s3); // false
6. Null Literal
null can be assigned only to reference types, never to primitives.
String s = null; // valid
Object o = null; // valid
int x = null; // ERROR
System.out.println(null instanceof Object); // false
7. Tricky Interview Cases
Examples that often confuse beginners and appear in interviews:
System.out.println('A' + 'B'); // 131
System.out.println("A" + "B"); // AB
System.out.println(10/0.0); // Infinity
System.out.println(0.0/0.0); // NaN
Primitive Data Types - Range & Memory
Type Size Range
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2^31 to 2^31-1
long 8 bytes -2^63 to 2^63-1
float 4 bytes ~6–7 decimal digits
double 8 bytes ~15–16 decimal digits
char 2 bytes 0 to 65,535 (Unicode)
boolean 1 bit (JVM dependent) true/false
Character Escape Sequences
Literal Meaning
'\n' Newline
'\t' Tab
'\b' Backspace
'\r' Carriage return
'\f' Form feed
'\'' Single quote
'\"' Double quote
'\\' Backslash
'\u0041' Unicode for A