Java Literals
Table of Contents + β
In the last lesson you learned about Java non-primitive data types. Every time you wrote 7, 19.99, or "Alex", you were using a literal: a fixed value written straight into your code.
π€ What is a literal?
A literal is a fixed value written directly in your code. In int age = 25;, the 25 is the literal.
- A variable is a name that holds a value, like
age. - A literal is the actual value, like
25. - A variable can change later. A literal is fixed the moment you type it.
Think of it like a price tag. The number on the tag is the literal. The shelf it sits on is the variable. Java has one literal for each data type you already met. Letβs walk through them.
π’ Integer literals
An integer literal is a whole number, like 100 or -7. These are the most common literals you will use.
- A plain integer literal is an
intby default. - You can write the same number in four number systems.
- Very large numbers must be marked as
long.
This example writes whole numbers the normal way.
int score = 100;int temperature = -5;System.out.println(score);System.out.println(temperature);Output
100-5Four ways to write the same number
The same number can be written in different bases. A base is the number system used. Each form has a prefix so Java knows which one you mean.
- Decimal: base ten. No prefix.
42. - Binary: base two,
0and1. Prefix0b.0b101010. - Octal: base eight, digits
0to7. Prefix0(a leading zero).052. - Hex: base sixteen, digits
0β9andaβf. Prefix0x.0x2A.
All four write the same value, forty-two. They only look different. This program proves it.
int decimal = 42; // normal base tenint binary = 0b101010; // 0b prefix, base twoint octal = 052; // leading 0, base eightint hex = 0x2A; // 0x prefix, base sixteen
System.out.println(decimal);System.out.println(binary);System.out.println(octal);System.out.println(hex);The prefix only changes how you wrote it. The value stays the same.
Output
42424242Watch the leading zero
A leading 0 means octal, not decimal. So 010 is eight, not ten. Never pad a normal number with a leading zero, like writing 0123 and expecting one hundred twenty-three. Java reads it as octal.
You will mostly use decimal. Binary and hex show up with colors, flags, or bit work. Octal is rare today.
Big numbers need an L
An int only holds up to about two billion. A bigger literal must end in L to mark it as a long. Without the L, Java reads it as an int, sees it is too big, and the code will not compile.
This example stores a value larger than an int can hold.
long worldPopulation = 8000000000L; // L marks this as a longSystem.out.println(worldPopulation);Output
8000000000Always use capital L. A lowercase l looks almost exactly like the digit 1.
Underscores make big numbers readable
Java lets you put underscores inside number literals to group the digits. 1_000_000 is the same as 1000000, but far easier to read at a glance. Java ignores the underscores completely. They are only there to help your eyes. You can place them anywhere between digits, like 8_000_000_000L, but not at the very start, the very end, or next to the decimal point.
π§ Floating-point literals
A floating-point literal is a number with a decimal point, like 3.14 or 19.99. Java reads these as double by default. A double is precise, so it is the safe everyday choice.
This example uses plain decimal values, which are all doubles.
double price = 19.99;double pi = 3.14159;System.out.println(price);System.out.println(pi);Output
19.993.14159Suffixes pick the exact type:
- A plain decimal literal is a
double. - Add
f(orF) to make it a smallerfloat. - Add
d(orD) to mark adoubleout loud; optional, since that is the default.
This example shows both suffixes side by side.
float rating = 4.5f; // f makes this a floatdouble weight = 70.5d; // d is optional; double is the default anywaydouble cost = 12.0; // no suffix, still a double
System.out.println(rating);System.out.println(weight);System.out.println(cost);The f suffix matters because a float variable cannot accept a plain decimal literal. The literal is a double, and a double does not fit into the smaller float box. The f makes the value a float from the start.
Output
4.570.512.0You can also write decimals in scientific form using e. So 1.5e3 means 1.5 times ten to the power three, which is 1500.0. Handy for very large or very small decimals.
π€ Character literals
A character literal is a single character inside single quotes, like 'A'. A char holds exactly one character, no more.
This example stores two single letters.
char grade = 'A';char firstInitial = 'R';System.out.println(grade);System.out.println(firstInitial);Output
ARInside the computer a char is really a small number. Each character has a code from a system called Unicode, so 'A' is stored as sixty-five. That explains the next trick.
You can write a char using its Unicode escape: \u followed by four hex digits. So 'A' is the same as 'A', because 0041 in hex is sixty-five. Useful for characters you cannot type on your keyboard.
This example writes the letter A, plus a character you may not have on your keyboard.
char letter = 'A'; // A is the code for 'A'char heart = 'β€'; // a heart symbolSystem.out.println(letter);System.out.println(heart);Output
Aβ€Escape sequences inside a char
Some characters are hard to type directly, like a tab or a new line. For those, Java uses an escape sequence: a backslash \ followed by a letter. The backslash says the next character is special. Here are the common ones.
| Escape | What it does |
|---|---|
| \n | Starts a new line |
| \t | Inserts a tab space |
| \ | Inserts a single backslash |
| β | Inserts a single quote inside a char |
| β | Inserts a double quote inside a string |
A single quote inside a char needs escaping as '\'', or Java thinks the char ended early. Same for a backslash, written as '\\'.
π§΅ String literals
A string literal is text inside double quotes, like "Hello". A char holds one character; a string holds a whole run of them. Even an empty string "" is a valid literal.
This example stores a greeting and an empty string.
String greeting = "Hello, Java";String blank = "";System.out.println(greeting);System.out.println(greeting.length());System.out.println(blank.length());The length() part counts the characters. The empty string has length zero: empty, but still a real value.
Output
Hello, Java110The big rule is the quotes:
- Single quotes make a
char.'A'is a char. - Double quotes make a
String."A"is a string with one character. - They are not the same type, even when the text matches.
Strings use the same escape sequences as chars. Here is a new line and a quote mark inside one string.
System.out.println("Line one\nLine two");System.out.println("She said \"Hello\" to me");The \n breaks the text onto a second line. The \" puts a double quote inside the string without ending it early.
Output
Line oneLine twoShe said "Hello" to meβ Boolean and null literals
A boolean literal is one of two bare words: true or false. No quotes, no numbers. They answer any yes-or-no question your program asks.
This example stores both boolean values.
boolean isOnline = true;boolean isPaid = false;System.out.println(isOnline);System.out.println(isPaid);Output
truefalseOne more special literal is null. It means this points to nothing. When an object variable has no object yet, its value is null. You write it as a bare word, so null is not the same as the string "null".
This example sets a string variable to point at nothing.
String name = null; // no text yet, points to nothingSystem.out.println(name);You will meet null properly when we work with objects. For now, know it means pointing to no value. Do not mix it up with "null" in quotes, which is just ordinary text.
Output
nullβ οΈ Common Mistakes
A few literal mix-ups cause most early errors.
Forgetting the L on a big number. A whole number bigger than an int will not compile without an L.
// β Avoid: too big for int, no L, this will not compilelong population = 8000000000;
// β
Good: the L marks it as a longlong population = 8000000000L;Using the wrong quotes. Single quotes are for one char. Double quotes are for a String.
// β Avoid: double quotes try to put a String into a charchar grade = "A";
// β
Good: single quotes for a charchar grade = 'A';Forgetting to escape an inner quote. A double quote inside a string must be written as \", or Java thinks the string ended early.
// β Avoid: the string ends at the second quote, then breaksString s = "She said "Hello"";
// β
Good: escape the inner quotesString s = "She said \"Hello\"";Padding a number with a leading zero. A leading 0 means octal, so the value is not what you expect.
// β Avoid: leading 0 makes this octal, value is 9 not 11int code = 011;
// β
Good: no leading zero, plain decimal elevenint code = 11;β Best Practices
A few small habits keep your literals clean.
- Use capital
Lfor long literals, never lowercasel, becausellooks like the digit1. - Add underscores to long numbers, like
1_000_000, so they are easy to scan. - Pick
doublefor decimals unless you have a clear reason to usefloat. - Never pad a normal number with a leading zero, or you accidentally make it octal.
- Use
\uUnicode escapes only when you cannot type the character directly. Plain text is clearer when you can use it.
π§© What Youβve Learned
- β
A literal is a fixed value written straight into your code, like
25or"Alex". - β
Integer literals can be decimal, binary
0b, octal0, or hex0x; big ones need anL, and underscores like1_000_000aid reading. - β
Floating-point literals are decimals (a
doubleby default; addffor afloat,dis optional). - β
charliterals use single quotes and can hold escape sequences or\uUnicode codes;Stringliterals use double quotes. - β
Boolean literals are
trueorfalse, andnullmeans βpointing to no valueβ. - β
Escape sequences like
\n,\t, and\"put special characters inside chars and strings.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
In int age = 25; what is the literal?
Why: The literal is the fixed value written directly in the code, which is 25. age is the variable.
- 2
What does the underscore do in 1_000_000?
Why: Java ignores underscores in number literals. They only help your eyes group the digits.
- 3
Which escape sequence starts a new line?
Why: \n starts a new line. \t makes a tab, and \" inserts a double quote.
- 4
How do you put a double quote inside a string?
Why: Write \" so Java inserts a quote without ending the string early.
π Whatβs Next?
You can now write values of every kind. Time to do things with them. Next up is type casting, where you convert a value from one data type into another.