Search⌘ K
AI Features

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:

  1. It appears directly in the source code.

  2. It represents a concrete value.

  3. It is not stored in a variable by itself.

Look at the code below.

int x = 10;
Variable ‘x’ stored the literal's value

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 an int. Any decimal (e.g., 10.5) is treated as a double by default.

  • Suffixes: To specify a different type, we append a letter to the number. We add L to denote a long (for integers larger than 2 billion) and F to denote a float (to save memory on decimals).

  • ...