Literals and the var Keyword
Explore the key concepts of Java literals such as numeric, character, boolean, string, and null values. Understand how literals represent fixed data directly in code. Learn to declare variables efficiently using the var keyword introduced in Java 10, which allows the compiler to infer types based on assigned values while maintaining static typing. Gain insight into rules and best practices for using var to write clean, readable code.
When we write a program, we work with different values: numbers, text, and true/false decisions. Sometimes we create these values while the program is running, but other times we write the values directly into the code. These directly written values are called literals.
What makes something a literal?
A literal has three key properties:
It appears directly in the source code.
It represents a concrete value.
It is not stored in a variable by itself.
Look at the code below.
int x = 10;
Here, x is a variable and 10 is a literal. The variable stores the literal’s value. Remember, literals do not change; variables do.
Working with numeric literals
Java applies default types to all numeric literals, but we can override them when necessary:
Defaults: Any whole number (e.g.,
100) is treated as anint. Any decimal (e.g.,10.5) is treated as adoubleby default.Suffixes: To specify a different type, we append a letter to the number. We add
Lto denote along(for integers larger than 2 billion) andFto denote afloat(to save memory on decimals)....