Literals in Java
1. Definition of Literals:
- Fixed values represented in human-readable form (e.g., number 100).
- Also called constants.
- Intuitive and frequently used.
two. Types of Literals:
- Primitive Types: Can be any primitive data type.
- Characters: Delimited by single quotes (e.g., 'a', '%').
3. Integer Literals:
- Numbers without fractional components (e.g., 10, -100).
- Represented as int by default.
- Can be specified as long using l or L (e.g., 12L).
4. Floating Point Literals:
- Include a decimal point and fractional component (e.g., 11,123).
- Represented as double by default.
- Can be specified as a float using F or f (e.g., 10.19F).
- Support scientific notation.
5. Assignment to Variables:
- Integer literals can be assigned to char, byte, short if the value fits.
- Integer literals can be assigned to long.
6. Underscores in Literals (JDK 7):
- Makes reading large values easier (e.g., 123_45_1234).
7. Hexadecimal, Octal and Binary Literals:
- Hexadecimals: Start with 0x or 0X (e.g., 0xFF).
- Octals: Start with zero (e.g., 011).
- Binaries (JDK 7): Start with 0b or 0B (e.g., 0b1100).
8. Character Escape Sequences:
- Used to represent special characters (e.g., \n for new line, \t for tab).
- Examples: ch = '\t';, ch = '\'';.
9. String Literals:
- Set of characters enclosed in double quotes (e.g., "this is a test").
- May contain escape sequences (e.g., \n, \t).
Example of use in System.out.println:
System.out.println("First line\nSecond line");
System.out.println("A\tB\tC");
10. Escape Sequence Table:
- \': Single quote
- \": Double quotes
- \: Backslash
- \r: Return by car
- \n: New line
- \f: Page feed
- \t: Horizontal tab
- \b: Backspace
- \ddd: Octal constant
- \uxxxx: Hexadecimal constant