Constants
A constant is a variable whose value cannot be changed once it is assigned. Constants are declared using the final
keyword. They are often used for fixed values like mathematical constants or configuration settings.
Syntax
1 |
final data_type CONSTANT_NAME = value; |
Example
1 2 |
final double PI = 3.14159; final int MAX_USERS = 100; |
final
ensures the value assigned to the variable cannot be changed.- By convention, constants are written in uppercase letters with underscores separating words.
Literals
Literals are the fixed values directly written in the code. They represent specific data and can be of different types such as integers, floating-point numbers, characters, strings, or boolean values.
Types of Literals
Type | Syntax Example | Explanation |
---|---|---|
Integer | 10 , -50 |
Whole numbers without decimals. |
Floating-point | 3.14 , 2.5E3 |
Numbers with decimals or in scientific notation. |
Character | 'A' , 'z' |
Enclosed in single quotes, representing one character. |
String | "Hello" , "Java" |
Enclosed in double quotes, representing a sequence of characters. |
Boolean | true , false |
Represents logical values. |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class LiteralsExample { public static void main(String[] args) { int age = 25; // Integer literal double price = 19.99; // Floating-point literal char grade = 'A'; // Character literal String message = "Welcome!"; // String literal boolean isJavaFun = true; // Boolean literal System.out.println("Age: " + age); System.out.println("Price: $" + price); System.out.println("Grade: " + grade); System.out.println("Message: " + message); System.out.println("Is Java fun? " + isJavaFun); } } |