Constants
In this lesson, we will look at constants, values in a program that do not change.
We'll cover the following
Numeric, character, string, or Boolean values within a Java program that remain unchanged, or constant, during program execution can either have a name or be unnamed.
Unnamed constants
Earlier, we defined a literal as the Java representation of a specific fixed value, that is, a value that does not change. They are, in fact, unnamed constants. Literals conform to certain rules according to their data type:
- Integer literals are a sequence of digits without a decimal point or commas but can have a plus or minus sign. For example, 10 and –52 are integer literals.
- Floating-point literals are real numbers without commas but can have a plus or minus sign. They are written in one of two ways:
- Without an exponent but with a decimal point. For example,
3.14
,0.07
, and-50.0
are floating-point literals. - With an exponent. For example, in mathematics, we might write
0.00001234
as12.34 × 10–6
. In Java, we could write this value as12.34e-6
. The lettere
, which means “exponent”, represents both the multiplication operator and the10
. The number after thee
is an integer without a decimal point or comma. A plus sign is optional for positive exponents. - We can omit the decimal point in the number before the
e
, as long as we adjust the exponent to produce the correct value.
- Without an exponent but with a decimal point. For example,
- Character literals are single characters enclosed in single quotes.
- String literals are sequences of characters enclosed in double quotes.
- Boolean literals are the values
true
andfalse
.
Get hands-on with 1200+ tech skills courses.