Literals and constants (final)
Literals and constants
Section titled “Literals and constants”Literals
Section titled “Literals”A literal is a fixed value written directly in the source code.
Examples:
int age = 25; // integer literaldouble pi = 3.14159; // floating‑point literalchar grade = 'A'; // character literalString name = "Alice"; // string literal (an object)boolean flag = true; // boolean literalInteger literal forms:
int dec = 42; // decimalint oct = 052; // octal (prefix 0)int hex = 0x2A; // hexadecimal (prefix 0x)int bin = 0b101010; // binary (prefix 0b)Underscores in literals (Java 7+):
int million = 1_000_000;long creditCard = 1234_5678_9012_3456L;Constants
Section titled “Constants”A constant is a variable whose value cannot be changed after initialization. Declare it with the final keyword.
final double PI = 3.141592653589793;final int MAX_USERS = 100;Convention: Constant names are in uppercase with underscores.
Blank final: you can declare a final variable without initializing it immediately, but you must assign it exactly once.
final int SIZE;SIZE = 10; // allowed only onceStatic constants are often used for shared immutable values:
public class MathConstants { public static final double PI = 3.14159; public static final double E = 2.71828;}They can be accessed as MathConstants.PI without creating an instance.