Literals and the var Keyword
Explore how to use various Java literals such as numeric values, characters, booleans, strings, and the special null literal. Understand how to apply the var keyword introduced in Java 10 for concise and type-safe variable declarations, along with its rules and best practices for clear 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)....