Literals
In computer programming, a literal is a notation for representing a fixed value in source code. Literals directly express specific data types' values within the code, such as numbers, characters, strings, or boolean values. Unlike variables and constants, which are named entities used to store data values that can be retrieved and manipulated, literals are the values themselves as written in the code.
Types of Literals:
Integer Literals: Represent whole numbers without fractions, such as
42
,-1
,0
.Floating-Point Literals: Represent real numbers, which can include fractional parts, written with a decimal point or in exponential notation, such as
3.14
,-0.01
,2.5e2
.Character Literals: Represent single characters, typically enclosed in single quotes, such as
'a'
,'1'
,'@'
.String Literals: Represent sequences of characters enclosed in double quotes (in most languages), such as
"Hello, world!"
.Boolean Literals: Represent truth values, usually written as
true
andfalse
.Null Literal: Represents the absence of a value or a null reference, usually written as
null
in many languages (orNone
in Python,nil
in some other languages).
Characteristics of Literals:
Immutability: The value of a literal does not change; it is a fixed part of the code.
Direct Representation: Literals represent values directly in the code. When the program runs, these literals are interpreted as the values they represent.
Type Inference: In some languages, the type of a literal can be inferred from its notation. For example,
42
is clearly an integer, while3.14
is a floating-point number.
Examples:
Usage:
Literals are used throughout programming to initialize variables, pass arguments to functions, and specify conditions in control structures. They are foundational to expressing basic values and structures directly in code, making them an indispensable part of programming syntax.
Last updated
Was this helpful?