Welcome to our guide on literals! In programming, literals are values that are directly written into the code, representing specific data types. They are used to assign values to variables or as constants in the program. In this article, we will explore the different types of literals and provide examples to help you understand their usage.
Numeric Literals
Numeric literals represent numbers and can be categorized into three main types:
Integer Literals
Integer literals represent whole numbers without any fractional or decimal parts. They can be written in decimal, binary, octal, or hexadecimal formats. Here are a few examples:
- Decimal: 42
- Binary: 0b101010
- Octal: 0o52
- Hexadecimal: 0x2A
Floating-Point Literals
Floating-point literals represent numbers with fractional parts. They can be written in decimal or exponential notation. Here are some examples:
- Decimal: 3.14
- Exponential: 6.022e23
Complex Literals
Complex literals represent complex numbers with real and imaginary parts. They are written in the form of a + bj
, where a
and b
are numeric values. Here is an example:
- Complex: 2 + 3j
String Literals
String literals represent sequences of characters enclosed in single quotes (”) or double quotes (“”). They can include letters, numbers, symbols, and whitespace. Here are a few examples:
- Single-Quoted: ‘Hello, World!’
- Double-Quoted: “Welcome to our website!”
Boolean Literals
Boolean literals represent the truth values of logic. They can be either true
or false
. Here are some examples:
- True: true
- False: false
Character Literals
Character literals represent individual characters and are enclosed in single quotes (”). They can include letters, numbers, symbols, and special characters. Here is an example:
- Character: ‘A’
Null Literal
The null literal represents the absence of a value. It is often used to indicate that a variable does not currently have a value assigned to it. Here is an example:
- Null: null
Conclusion
In this article, we have explored the different types of literals and provided examples to help you understand their usage. Whether you are working with numbers, strings, booleans, characters, or null values, literals play a crucial role in representing specific data types in your code. By using literals effectively, you can assign values to variables and constants, making your programs more dynamic and functional.