Java.What are literals ?

🔥 What are Literals in Java?

Definition

Literals in Java are fixed, constant values that you write directly in your code. These are “hardcoded” values that represent themselves.


📦 Examples of Literals (Directly Represented Values)

TypeExampleExplanation
Integer Literal100, -25Whole numbers
Floating-point Literal3.14, -0.001Decimal numbers
Character Literal'A', '9'Single characters (always in single quotes)
String Literal"Hello", "Java"Text (always in double quotes)
Boolean Literaltrue, falseBoolean values
Null LiteralnullSpecial literal representing “no object”

✅ Simple Rule

If you type it directly into your code, and it’s a fixed value (not a variable or expression), it’s a literal.


🚫 What is NOT a Literal?

Here are things that are NOT literals:

Not LiteralExampleExplanation
Variableint x = 10;x is not a literal (but 10 is)
Expression5 + 3This is an expression (combines literals to compute a result)
Method Call ResultMath.sqrt(4)This is a computed value, not a literal
Object Referencenew String("hello")new String(...) creates an object, not a literal

📝 Special Case: String Pool

Even though "Hello" is a literal, when you do:





String s = "Hello";

The literal "Hello" gets stored in the String Pool, but s itself is a variable that points to it.
The literal is "Hello" — the value written directly in the code.


🔧 Quick Test

Which of these are literals?

int x = 5;              // 5 is a literal, x is not.
String s = "Java";       // "Java" is a literal, s is not.
boolean b = true;        // true is a literal, b is not.
double pi = 3.14159;     // 3.14159 is a literal, pi is not.
int sum = x + 10;        // 10 is a literal, x + 10 is an expression.
System.out.println("Hi"); // "Hi" is a literal.

✅ Summary Table

ExampleIs Literal?Why?
"Hello"✔️Direct value written into the code
42✔️Direct value written into the code
true✔️Direct value written into the code
myVariableThis is a variable name, not a literal
x + yExpression, not a literal
new Object()Creates an object, not a literal
This entry was posted in Без рубрики. Bookmark the permalink.