Constants and Literals

Constants

A constant is a variable whose value cannot be changed once it is assigned. Constants are declared using the final keyword. They are often used for fixed values like mathematical constants or configuration settings.

Syntax

Example

  • final ensures the value assigned to the variable cannot be changed.
  • By convention, constants are written in uppercase letters with underscores separating words.

Literals

Literals are the fixed values directly written in the code. They represent specific data and can be of different types such as integers, floating-point numbers, characters, strings, or boolean values.

Types of Literals

Type Syntax Example Explanation
Integer 10, -50 Whole numbers without decimals.
Floating-point 3.14, 2.5E3 Numbers with decimals or in scientific notation.
Character 'A', 'z' Enclosed in single quotes, representing one character.
String "Hello", "Java" Enclosed in double quotes, representing a sequence of characters.
Boolean true, false Represents logical values.

Example