Topic 19 of 119 2. Fundamentals of Java Programming Interactive Tutorial

Java Literals: Numeric, Character, String, Boolean, and Other Forms

16 mins read Last updated: 22 Aug 2026 18,287 views

Direct Answer & Core Concept

A literal is the fixed value you write directly in your source code, such as 100, 3.14, 'A', "Java", true or null. Java supports decimal, octal, hexadecimal and binary integer literals, floating-point literals with scientific notation, character literals with escape sequences, String literals, boolean literals and the null literal. Because a literal is not a variable, nothing can change it. Two details surprise beginners: a whole number with no suffix is always an int, even a very large one, and a decimal literal without a suffix is always a double.

Detailed Explanation & Mechanics

1. What Is a Literal in Java?

A literal is the fixed value you write directly in your source code. When you type 100 or 3.14 or "Java", you are not referring to a variable, you are writing the value itself.

Main.java
Run Online
int age = 25;
// 25 is an integer literal
double rate = 7.5;
// 7.5 is a floating-point literal
String city = "Pune";
// "Pune" is a String literal

A literal is the opposite of a variable in one important way: it can never change. There is no valid Java code that reassigns 25, because 25 is not a name, it is the value itself.

Architecture Diagram
VARIABLE VERSUS LITERAL

   int  age    = 25;
   |   |    |    |
   |   |    |    +--> LITERAL     a fixed value, cannot change
   |   |    +-------> assignment  copies it into the box
   |   +------------> VARIABLE    a name you can change later
   +----------------> TYPE        always int here

   age = 26;          works, you changed the variable
   25 = 26;           ERROR, you cannot change a literal

Literals matter more than they look, because the compiler uses them to decide the type of everything around them. A literal is the starting point of Java's whole type system.

2. The Six Forms of a Java Literal

Java recognises six broad forms of literal, and every value you write in code belongs to one of them.

FormExampleNotes
Integer100, 0144, 0x64, 0b1100100Decimal, octal, hexadecimal, binary
Floating point3.14, 3.14f, 1.5e10double by default, f forces float
Character'A', '\n', '©'One character, single quotes
String"Java", "C:\\path"Any length, double quotes
Booleantrue, falseLower case only, nothing else allowed
NullnullReference types only, never a primitive

There is also a seventh form that beginners rarely meet, the class literal such as String.class, which we cover towards the end.

3. Integer Literals: Decimal, Octal, Hexadecimal and Binary

An integer literal is any whole number written in code. Java can read it in four different bases, and the base decides how the digits are interpreted.

Main.java
Run Online
THE NUMBER 100 WRITTEN IN FOUR BASES DECIMAL OCTAL HEXADECIMAL BINARY(no prefix)(0 prefix)(0x prefix)(0b prefix) 100 0144 0x64 0b0110 0100 | | | | +---------------+---------------+----------------+ all four store the same value
Main.java
Run Online
public class IntegerLiterals {
    public static void main(String[] args) {
        int decimal = 100;
        int octal = 0144;
        // leading zero means octal
        int hex = 0x64;
        // 0x means hexadecimal
        int binary = 0b01100100;
        // 0b means binary, Java 7 and later
        System.out.println(decimal);
        // 100
        System.out.println(octal);
        // 100
        System.out.println(hex);
        // 100
        System.out.println(binary);
        // 100
    }
}
  • Hexadecimal letters are written in either case, so 0xCAFE and 0xcafe mean the same thing.
  • An octal literal that contains an 8 or a 9 is an error, so 0789 will not compile.
  • Java 7 added the binary prefix, and Java 7 also added underscores, which we look at next.
  • There is one delightful quirk here. Because 0x80000000 is the most negative int value, writing int x = 0x80000000; gives you -2147483648, with no minus sign in sight.

4. Underscores Make Big Numbers Readable

Since Java 7 you may place underscores anywhere between digits in a numeric literal. The compiler ignores them completely, so the value is unchanged.

Main.java
Run Online
HARD TO READ EASY TO READ-------------------------------------------4532750012345678 4_532_7500_1234_56782147483647 2_147_483_6471000000 1_000_0000xFFECDE5E 0xFF_EC_DE_5E0b1010100011110000 0b1010_1000_1111_0000

The rule is simple: an underscore must sit **between two digits**. These are all illegal and produce a compile error.

  • A leading underscore, as in _100
  • A trailing underscore, as in 100_
  • An underscore directly after a base prefix, so write 0xFF and never 0_xFF

Interestingly, Java tolerates consecutive underscores, so 1__0 is legal, and it also allows one right after the leading 0 of an octal literal, so 0_144 is legal too. The compiler simply ignores all of it.

Main.java
Run Online
public class UnderscoreDemo {
    public static void main(String[] args) {
        long phone = 9_876_543_210L;
        int mask = 0xFF_EC_DE_5E;
        byte small = 0b0000_1111;
        System.out.println(phone + " " + mask + " " + small);
        // _100, 100_ and 0_xFF would all fail to compile
    }
}

5. Suffixes and the Type of an Integer Literal

This is the rule beginners get wrong most often, and it surprises almost everyone. An integer literal is a plain int unless you say otherwise. It is never promoted to long automatically just because the number is large.

Main.java
Run Online
HOW JAVA TYPES AN INTEGER LITERAL Does the literal have an L or l suffix? | +-----+-----+ | | yes no | | v v long int(always)(always, even for a huge number) A bare literal larger than 2147483647 is simply a COMPILE ERROR, not an automatic long.
Main.java
Run Online
public class LiteralTypes {
    public static void main(String[] args) {
        int small = 100;
        // an int, as always
        long forced = 100L;
        // the L suffix makes it a long
        long big = 10000000000L;
        // the L is REQUIRED here
        long upper = 0xCAFEBABEL;
        // hex literals can also take L
        System.out.println(small);
        System.out.println(forced);
        System.out.println(big);
        System.out.println(upper);
        // long broken = 10000000000;    ERROR, no L suffix so it tries int
    }
}
  • The suffix may be written L or l, and L is preferred because a lowercase l is easily mistaken for the digit 1.
  • A bare integer literal is a compile error as soon as it exceeds 2147483647, so 10000000000 will not compile and neither will long x = 10000000000.
  • Hexadecimal, octal and binary literals accept the same L suffix, as in 0xCAFEBABEL.
  • The one special case is the literal 2147483648. The JLS allows it only as the operand of a unary minus, which is what makes Integer.MIN_VALUE writable as -2147483648.

6. Floating-Point Literals and Scientific Notation

A floating-point literal holds a decimal value. The most important rule is that a decimal with no suffix is always a double, never a float.

Main.java
Run Online
FLOATING-POINT FORMS 3.14 a double, because no suffix was given 3.14f a float, because of the f suffix 3.14d a double written explicitly 1.5e10 scientific notation, also a double 3.2e-8 a small number written with a negative exponent 1_000.5 underscores are allowed here too
Main.java
Run Online
public class FloatingLiterals {
    public static void main(String[] args) {
        double price = 1499.99;
        double big = 1.5e10;
        // 15,000,000,000
        double small = 3.2e-8;
        float ratio = 0.75f;
        // f is required to get a float
        double grouped = 1_000_000.5;
        System.out.println(price + " " + big + " " + small);
        System.out.println(ratio + " " + grouped);
    }
}
  • Scientific notation uses e or E, and the exponent may be negative, as in 3.2e-8.
  • You cannot assign a plain double literal straight into a float, because the compiler rejects it as a lossy conversion. The f suffix is the correct fix, and a (float) cast also works but discards precision.
  • Float keeps only about seven significant digits, while double keeps about sixteen, which is why accumulating values into a float drifts much sooner.
  • Java also accepts hexadecimal floating-point literals such as 0x1.8p3, but almost nobody uses them, so keep that one as background knowledge.

7. Character Literals and Escape Sequences

A character literal holds exactly one character and must use single quotes. Some characters cannot be typed directly, either because they are invisible or because they have a special meaning in code, so Java provides escape sequences for them.

EscapeProducesWhen You Need It
\nNew linePrinting multi-line messages
\tTabAligning output in columns
\rCarriage returnOld style line breaks
\bBackspaceTerminal progress effects
\fForm feedPage breaks in old printers
\\A backslashWindows paths such as C:\\temp
\'A single quoteA char literal that holds a quote
\"A double quoteInside a String literal
\sA spaceReadable text blocks, Java 15 and later
\uXXXXAny Unicode characterCharacters your keyboard lacks
Main.java
Run Online
public class EscapeDemo {
    public static void main(String[] args) {
        char newline = '\n';
        char tab = '\t';
        char backslash = '\\';
        char quote = '\'';
        char unicode = 'A';
        System.out.println("First line" + newline + "Second line");
        System.out.print("Name:" + tab + "Tanmoy" + newline);
        System.out.println("backslash = " + backslash);
        System.out.println("quote = " + quote);
        System.out.println("unicode A = " + unicode);
    }
}

Note the doubling. To print one backslash you must write two, and to hold a single quote inside a char literal you must write it escaped. This is the single most common source of syntax errors in string work.

8. The Unicode Escape Trap Everyone Falls Into

A backslash u followed by exactly four hexadecimal digits is a Unicode escape, and the compiler translates it before it parses anything else. That last part causes genuine confusion.

Main.java
Run Online
WHY A UNICODE ESCAPE IN A COMMENT BREAKS THE BUILD You write: // remember to use \\u0041 for the letter A
Compiler: replaces \\u0041 with the letter A FIRST, before it even looks at what a comment is Result: your comment silently changed, harmless here WORSE CASE: // line one \\u000A line two
Compiler: \\u000A turns into a real line terminator Result: the next word lands on a new line, javac fails, and the error points at the wrong place Rule: the backslash-u sequence is processed everywhere, including comments. Never paste one into a comment.
Main.java
Run Online
public class UnicodeDemo {
    public static void main(String[] args) {
        char copyright = '©';
        // direct, and easiest
        char greek = 'Ω';
        // also direct
        char a = 'A';
        // the explicit escape form
        System.out.println(copyright + " " + greek + " " + a);
        System.out.println("To print a backslash then u, write: " + "\\u0041");
    }
}
  • Prefer typing or pasting the character itself, because it reads better than an escape.
  • Every Unicode escape must have exactly four hexadecimal digits.
  • Never paste a backslash-u sequence into a comment, because the compiler acts on it there too.

9. String Literals and the String Pool

A String literal is any text written in double quotes. It can hold any number of characters, it accepts the same escape sequences as a char, and it produces a String object rather than a primitive.

Main.java
Run Online
public class StringLiterals {
    public static void main(String[] args) {
        String simple = "Hello";
        String path = "C:\\Program Files\\Java";
        String quoted = "She said \"hello\" to me";
        String newline = "Line one\nLine two";
        String empty = "";
        System.out.println(simple + " " + path);
        System.out.println(quoted);
        System.out.println(newline);
        System.out.println("empty length = " + empty.length());
    }
}

Java quietly reuses String literals through something called the string pool. Two identical literals usually point at the very same object, which is why comparing them with equals gives true.

Main.java
Run Online
String first = "Java";
String second = "Java";
System.out.println(first.equals(second));
// true, same characters
System.out.println("pooling means: " +(first == second));
// usually true
String forced = new String("Java");
System.out.println("with new: " +(forced == first));
// false

10. Text Blocks: Multi-Line Strings Without the Pain

Java 15 gave us text blocks, written with three double quotes. They are the cleanest way to embed JSON, SQL or HTML in code, because the formatting is preserved exactly and nothing needs escaping.

Main.java
Run Online
public class TextBlockDemo {
    public static void main(String[] args) {
        String json = """
                {
                  "status": "success",
                  "code": 200
                }
                """;
        String sql = """
                SELECT name, salary
                FROM employees
                WHERE department = 'IT'
                """;
        System.out.println(json);
        System.out.println(sql);
    }
}
  • The opening triple quote must be followed by a line break, which the compiler then discards.
  • Incidental indentation is stripped automatically, so your code stays neat.
  • Quotes inside the block do not need escaping, which removes the ugliest part of embedded strings.
  • Add a backslash on the opening line if you want to keep the closing delimiter on the same line.

11. Boolean and Null Literals

Java has exactly two boolean literals and exactly one null literal, and every one of them must be written in lower case.

  • true and false are the only boolean literals. TRUE, True and FALSE will not compile.
  • null is a literal rather than a keyword, and it can only ever be assigned to a reference type.
Main.java
Run Online
public class BooleanAndNull {
    public static void main(String[] args) {
        boolean isReady = true;
        boolean hasFailed = false;
        String nickname = null;
        int[] scores = null;
        System.out.println(isReady + " " + hasFailed);
        System.out.println("nickname is null? " +(nickname == null));
        // boolean wrong = TRUE;    ERROR, must be lower case
        // int count = null;         ERROR, null cannot go into a primitive
    }
}

Null deserves care rather than fear. It simply means no object has been assigned yet, so any attempt to use the variable throws a NullPointerException. Checking before you use it is the whole habit.

12. Class Literals and Other Forms

A class literal is written with the word class after a type name. It always gives back a Class object, and it is genuinely useful in reflection, frameworks and unit tests.

Main.java
Run Online
public class ClassLiteralDemo {
    public static void main(String[] args) {
        System.out.println(String.class.getName());
        // java.lang.String
        System.out.println(int.class.getName());
        // int
        System.out.println(int[].class.getName());
        // [I  (an internal form)
        System.out.println(int[].class.getSimpleName());
        // int[]  (readable)
        System.out.println(String.class == String.class);
        // true
        // Handy when you want to build a message from a type
        String label = Integer.class.getSimpleName();
        // Integer
        System.out.println("Label: " + label);
    }
}
  • String.class, int.class and int[].class all produce a Class object.
  • Be careful with arrays. int[].class.getName() returns the internal form [I, while getSimpleName() returns the friendly int[]. An ordinary class such as String gives java.lang.String from getName().
  • Class literals are not affected by autoboxing, and they never return null.
  • A method reference such as String::length is a different idea, but you will meet it in the same chapter of the language.

13. Common Literal Mistakes Beginners Make

What You WroteWhat HappensCorrect Version
int n = 1_00;Legal, but misleading groupingint n = 100;
int n = 0789;Invalid octal digitint n = 789;
int id = 98765432100;Too large for an int literallong id = 98765432100L;
int n = 1__0;Legal, but a typo you meant to avoidint n = 1_000;
float r = 0.75;Lossy conversion from double to floatfloat r = 0.75f;
String s = 'A';A char is not a StringString s = "A";
char c = "A";A String is not a charchar c = 'A';
String p = "C:\temp";\t becomes a tabString p = "C:\\temp";
boolean b = True;Must be lower caseboolean b = true;
int x = null;null cannot go into a primitiveInteger x = null;
  • Mixing single and double quotes is the most common syntax error beginners make.
  • Forgetting the double backslash in a Windows path is the most common logic error, because it still compiles and simply prints the wrong thing.
  • Forgetting the L suffix produces a confusing error about a number too large, not about a missing suffix.

14. Java Literals Cheat Sheet

QuestionAnswer
Decimal 100 written in octal0144
Decimal 100 written in hex0x64
Decimal 100 written in binary0b01100100
Underscores allowed?Yes, since Java 7, but only between digits
Type of a plain whole numberAlways int, however large. Add L for a long
Suffix that forces longL or l
Type of 3.14double, never float
Suffix that forces floatf or F
Scientific notation1.5e10, exponent may be negative
Char literal quotesSingle quotes only, one character
String literal quotesDouble quotes, any length
Boolean literalstrue and false, lower case only
Null literalnull, reference types only
Negative number literalDoes not exist, the minus is an operator
Text blocksTriple double quotes, final in Java 15

With literals clear, the next topic, constants in Java, is a natural next step, because a constant is simply a value you give a name to so the literal appears in one place only.

Runnable Code Example: Java Literals

Java 17+
Main.java
Run Online
public class LiteralsDemo {
    public static void main(String[] args) {
        // ---------- Integer literals in four bases ----------
        int decimal = 100;
        int octal = 0144;
        // 0 prefix means octal
        int hex = 0x64;
        // 0x prefix means hexadecimal
        int binary = 0b0110_0100;
        // 0b prefix means binary, Java 7+
        System.out.println("All four are 100: " + decimal + " " + octal + " " + hex + " " + binary);
        // ---------- Underscores for readability ----------
        long accountNumber = 4_532_7500_1234_5678L;
        int mask = 0x0F_FF_EC_DE;
        System.out.println("account = " + accountNumber + ", mask = " + mask);
        // ---------- Floating point and scientific notation ----------
        double price = 1499.99;
        // this is a double
        double scientific = 1.5e10;
        // 15,000,000,000
        float ratio = 0.75f;
        // f suffix forces a float
        double tiny = 3.2e-8;
        System.out.println("price = " + price + ", scientific = " + scientific);
        System.out.println("ratio = " + ratio + ", tiny = " + tiny);
        // ---------- Character literals and escapes ----------
        char grade = 'A';
        char tab = '\t';
        char newline = '\n';
        char backslash = '\\';
        char copyright = '©';
        char unicode = 'A';
        System.out.print("Grade = " + grade);
        System.out.print(tab + "unicode A = " + unicode);
        System.out.println(newline + "backslash = " + backslash + ", copyright = " + copyright);
        // ---------- String literals ----------
        String greeting = "Hello, Java!";
        String path = "C:\\Users\\tanmoy";
        String quoted = "She said \"hi\"";
        System.out.println(greeting);
        System.out.println("path = " + path);
        System.out.println(quoted);
        // ---------- Text block, Java 15+ ----------
        String json = """
                {
                  "status": "success",
                  "code": 200
                }
                """;
        System.out.println(json);
        // ---------- Boolean and null ----------
        boolean isActive = true;
        boolean hasError = false;
        String nickname = null;
        // null is a literal, not a keyword
        System.out.println("active = " + isActive + ", error = " + hasError);
        System.out.println("nickname is null? " +(nickname == null));
        // ---------- Class literals ----------
        System.out.println("String class = " + String.class.getName());
        System.out.println("int class    = " + int.class.getName());
        System.out.println("int[] class  = " + int[].class.getName());
        System.out.println("int[] simple = " + int[].class.getSimpleName());
    }
}

Common Java Technical Interview Questions & Answers

Interview Prep
Q1

What is a literal in Java?

A literal is the fixed value written directly in your code, such as 100, 3.14, 'A', "Java", true or null. It is not a variable, so it can never be changed, and it is not stored anywhere until your program actually uses it.
Q2

How does Java decide the type of an integer literal?

It is an int. The only way to get a long is to add an L or l suffix, so long x = 10000000000; is a compile error while long x = 10000000000L; is fine. A bare literal larger than 2147483647 is an error rather than an automatic long.
Q3

What is the difference between octal, hexadecimal and binary literals?

Octal literals start with a zero such as 0144, hexadecimal literals start with 0x such as 0x64, and binary literals start with 0b such as 0b01100100, which was added in Java 7. All of them are just different ways of writing the same number.
Q4

Can I use underscores in numbers in Java?

Yes, since Java 7. Write 4_532_7500_1234_5678 and the compiler ignores the underscores. An underscore must sit between digits, so _100, 100_ and 0_xFF are illegal, though 1__0 is tolerated.
Q5

What type is a decimal number with no suffix?

double. The literal 3.14 is a double, not a float. If you want a float you must add the f suffix, as in 3.14f, otherwise the value is silently widened to double at some point.
Q6

Why is -100 not treated as a negative literal?

Java has no negative numeric literals. The minus sign is a unary minus operator applied to the positive literal 100, which means you cannot apply it the way you might expect in every context, and -2147483648 needs special care because 2147483648 alone does not fit in an int.
Q7

What is a Unicode escape in Java and why is it dangerous?

A backslash u followed by exactly four hexadecimal digits represents any character, so 'A' is a legal char literal. The danger is that the compiler processes these escapes before it parses anything, even inside comments, so a stray escape sequence can insert a newline into a comment and break the whole file.
Q8

How do single quotes and double quotes differ?

Single quotes create a char literal holding exactly one character, while double quotes create a String object. 'A' and "A" are different types with different memory cost and different methods.
Q9

Are String literals stored separately every time they appear?

No. String literals are placed in the string pool, and by default identical literals share one object, so two occurrences of "Java" usually point at the same instance. The new keyword bypasses that behaviour and always creates a separate object.
Q10

What are text blocks?

Text blocks were finalised in Java 15 and are written with three double quotes. They let you write multi-line JSON, SQL or HTML exactly as it appears, with no escaping and no repeated plus signs for line breaks.
Q11

Is null a keyword in Java?

No, null is a literal rather than a keyword, but it can only ever be assigned to a reference type. It can never be a primitive, so int x = null; will never compile.
Q12

What is TRUE, and is it valid Java?

No. The boolean literals are exactly true and false in lower case. Writing TRUE, True or False is a compile error, and the same rule applies to NULL, which must always be written as null.

Key Takeaways, Best Practices & Clean Code Rules

Java Best Practice & Production Rules

Use underscores in any number a person has to read, because 4_532_7500_1234_5678 is instantly clearer than the same digits run together. Be deliberate about suffixes: add L to anything that may grow beyond two billion, and add f only when you truly want float precision. Prefer hex with 0x when reading colour codes, memory masks or raw bytes, and binary when you are explaining bit flags to someone. Reach for text blocks instead of long chains of quotes and plus signs the moment a string spans more than one line. Remember that every escape you type is a chance for a bug, so keep literals simple and build complicated strings with StringBuilder or formatted text instead. Finally, use named constants for any value that appears more than once, so a literal that appears in five places is a value you only have to change in one place later.
We value your privacy & transparency

OperateTools uses cookies and local storage to ensure basic tool functionality, preserve preferences, and analyze aggregated traffic. We never sell your personal data or index your document files. Learn more in our Privacy Policy.