1. Constants ဆိုတာ ဘာလဲ?
A constant is a variable whose value cannot be changed once assigned.
// Regular variable (can change)
int age = 25;
age = 30; // ✅ OK
// Constant (cannot change)
final int MAX_AGE = 100;
MAX_AGE = 120; // ❌ Error! Cannot reassign
Constant ဆိုတာ value ကို program အတွင်းမှာ ပြောင်းလို့ မရတဲ့ variable ပါ။ Once assigned ဖြစ်ပြီဆို အပြောင်းအလဲ မရှိတော့ပါ။
- Immutable: Value ပြောင်းလို့ မရပါ
- Read-only: Read သာ လုပ်လို့ရတယ်၊ write မရပါ
- Fixed values: PI, MAX_VALUE, TAX_RATE စတဲ့ fixed တန်ဖိုးတွေ အတွက်
- Type safety: Accidental changes ကို ကာကွယ်ပေးတယ်
ဘာကြောင့် လိုအပ်လဲ?
- Prevent accidental changes - တမင်မဟုတ်ပဲ ပြောင်းခြင်းမှ ကာကွယ်တယ်
- Meaningful names - 3.14159 ထက် PI က နားလည်ရလွယ်တယ်
- Maintainability - တစ်နေရာတည်း ပြောင်းရင် တစ်ခါတည်း အကုန် ပြောင်းသွားတယ်
- Thread-safety - Multiple threads တွေမှာ safe တယ်
Immutable
Value cannot be changed
Protected
Prevents accidental changes
Fixed Values
PI, MAX_SIZE, TAX_RATE
2. The final Keyword
The final keyword is used to declare constants in Java.
2.1 Final Variables
final dataType VARIABLE_NAME = value;
// Mathematical constants
final double PI = 3.14159265359;
final double E = 2.71828182846;
// Configuration constants
final int MAX_USERS = 100;
final int MIN_AGE = 18;
final String APP_NAME = "MyApp";
// Physical constants
final double SPEED_OF_LIGHT = 299792458; // m/s
final double GRAVITY = 9.81; // m/s²
System.out.println("PI: " + PI);
System.out.println("Max users: " + MAX_USERS);
final keyword က variable ကို constant အဖြစ် declare
လုပ်ပေးပါတယ်။
- Must initialize: Declaration လုပ်တဲ့ အချိန်မှာပဲ value ပေးရပါမယ်
- Cannot reassign: Value ကို နောက်မှ ပြောင်းလို့ မရပါ
- Compile-time check: Compiler က reassignment ကို error ပေးပါတယ်
- Local or instance: Method ထဲမှာရော class level မှာရော သုံးလို့ရတယ်
2.2 Attempting to Change Final Variable
final int MAX_SIZE = 100;
// ❌ This will cause a compilation error
MAX_SIZE = 200; // Error: cannot assign a value to final variable
System.out.println(MAX_SIZE);
error: cannot assign a value to final variable MAX_SIZE
MAX_SIZE = 200;
^
⚠️ Important Rules
- Must initialize when declared - Later initialization မရပါ (local variables)
- One-time assignment - တစ်ခါသာ assign လုပ်လို့ ရတယ်
- Compiler enforces - Compilation error ပေါ်မယ်
// ❌ Error: Not initialized
final int x;
x = 10; // Too late for local final variable
// ✅ Correct: Initialize immediately
final int y = 10;
3. Naming Conventions for Constants
Constants follow a specific naming convention in Java.
📝 Constant Naming Rules
- ALL UPPERCASE: All letters must be uppercase
- Underscore separator: Use _ to separate words
- Descriptive names: Make the purpose clear
- No abbreviations: Use full words when possible
// ✅ Good constant names
final int MAX_STUDENTS = 100;
final double TAX_RATE = 0.15;
final String DATABASE_URL = "jdbc:mysql://localhost";
final int DEFAULT_TIMEOUT = 30;
final double CONVERSION_RATE = 1.5;
final int MINIMUM_PASSWORD_LENGTH = 8;
// ❌ Bad constant names (don't follow convention)
final int maxStudents = 100; // Not uppercase
final double TaxRate = 0.15; // Mixed case
final String databaseurl = "..."; // No separator
final int x = 30; // Not descriptive
Constants တွေအတွက် SCREAMING_SNAKE_CASE သုံးပါတယ်:
- UPPERCASE: စာလုံးကြီး အားလုံး - MAX_VALUE
- UNDERSCORE: စကားလုံးကြား _ နဲ့ ခွဲပါ - MAX_RETRY_COUNT
- DESCRIPTIVE: ရှင်းရှင်းလင်းလင်း အမည်ပေးပါ - SPEED_OF_LIGHT
ဥပမာများ:
- ✅
MAX_SIZE,MIN_AGE,TAX_RATE - ✅
DATABASE_URL,API_KEY,DEFAULT_LANGUAGE - ❌
maxSize,max_Size,MAXSIZE
| Wrong ❌ | Correct ✅ | Reason |
|---|---|---|
maxValue
|
MAX_VALUE
|
Not uppercase |
TAXRATE
|
TAX_RATE
|
No separator |
MAX_VAL
|
MAX_VALUE
|
Abbreviation |
x |
MAX_CAPACITY
|
Not descriptive |
4. Class-Level Constants (static final)
Constants shared across all instances of a class use static final.
public class MathConstants {
// Class-level constants (static final)
public static final double PI = 3.14159265359;
public static final double E = 2.71828182846;
public static final int MAX_ITERATIONS = 1000;
public static void main(String[] args) {
// Access without creating instance
System.out.println("PI: " + MathConstants.PI);
System.out.println("E: " + MathConstants.E);
// Calculate circle area
double radius = 5.0;
double area = PI * radius * radius;
System.out.println("Area: " + area);
}
}
static final က class-level constant ဖြစ်ပါတယ်။
- static: Class ကိုယ်တိုင်နှင့် ဆိုင်တယ်၊ instance မလိုပါ
- final: Value ပြောင်းလို့ မရပါ
- Shared: All objects တွေက တူညီတဲ့ value ကို share လုပ်ကြတယ်
- Memory efficient: တစ်ခါတည်း memory မှာ ရှိတယ်
Access pattern: ClassName.CONSTANT_NAME
// Access from anywhere
double pi = MathConstants.PI;
int max = MathConstants.MAX_ITERATIONS;
Real-World Example
public class AppConfig {
// Application constants
public static final String APP_NAME = "StudentManager";
public static final String VERSION = "1.0.0";
public static final int MAX_USERS = 1000;
public static final int SESSION_TIMEOUT = 1800; // 30 minutes
// Database constants
public static final String DB_HOST = "localhost";
public static final int DB_PORT = 3306;
public static final String DB_NAME = "school";
// Tax and rates
public static final double TAX_RATE = 0.10;
public static final double DISCOUNT_RATE = 0.15;
}
public class Main {
public static void main(String[] args) {
System.out.println("App: " + AppConfig.APP_NAME);
System.out.println("Version: " + AppConfig.VERSION);
System.out.println("Max Users: " + AppConfig.MAX_USERS);
// Calculate price with tax
double price = 100.0;
double total = price * (1 + AppConfig.TAX_RATE);
System.out.println("Total with tax: " + total);
}
}
5. Final with Different Data Types
5.1 Primitive Types
// Integer types
final byte MAX_BYTE = 127;
final short MAX_SHORT = 32767;
final int MAX_INT = 2147483647;
final long MAX_LONG = 9223372036854775807L;
// Floating-point
final float PI_FLOAT = 3.14159f;
final double PI_DOUBLE = 3.14159265359;
// Character
final char GRADE_A = 'A';
final char NEWLINE = '\n';
// Boolean
final boolean IS_PRODUCTION = true;
final boolean DEBUG_MODE = false;
5.2 Reference Types (String, Arrays, Objects)
// String constant
final String WELCOME_MESSAGE = "Welcome to Java!";
final String ERROR_MESSAGE = "An error occurred";
// Array constant (reference is final, but elements can change!)
final int[] FIBONACCI = {1, 1, 2, 3, 5, 8, 13};
FIBONACCI[0] = 10; // ✅ OK! Can modify elements
// FIBONACCI = new int[5]; // ❌ Error! Cannot reassign array
// Array of Strings
final String[] DAYS = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
DAYS[0] = "Monday"; // ✅ OK! Can modify elements
⚠️ Important: Final Reference Variables
Final reference ဆိုတာ reference ကိုယ်တိုင် ကို ပြောင်းလို့မရဘူး ဆိုတာပါ။ ဒါပေမယ့် object ရဲ့ content ကို ပြောင်းလို့ ရပါတယ်။
final int[] numbers = {1, 2, 3};
// ✅ OK: Modify array contents
numbers[0] = 10;
numbers[1] = 20;
// ❌ Error: Cannot reassign reference
numbers = new int[5]; // Compilation error!
final String message = "Hello";
// message = "Hi"; // ❌ Error! Strings are immutable anyway
Summary: Final = Reference မပြောင်း, Content ပြောင်းလို့ရတယ်
6. Constants vs Variables Comparison
| Aspect | Variable | Constant (final) |
|---|---|---|
| Declaration |
int age = 25;
|
final int MAX_AGE = 100;
|
| Reassignment | ✅ Allowed | ❌ Not allowed |
| Naming | camelCase | UPPER_SNAKE_CASE |
| Use Case | Values that change | Fixed values |
| Examples | counter, score, name | PI, MAX_SIZE, TAX_RATE |
public class Comparison {
public static void main(String[] args) {
// Variable - can change
int studentCount = 30;
studentCount = 35; // ✅ OK
studentCount = 40; // ✅ OK
System.out.println("Count: " + studentCount);
// Constant - cannot change
final int MAX_CAPACITY = 50;
// MAX_CAPACITY = 60; // ❌ Error!
System.out.println("Max: " + MAX_CAPACITY);
// Use constant in calculation
if (studentCount > MAX_CAPACITY) {
System.out.println("Exceeded capacity!");
} else {
System.out.println("Within capacity");
}
}
}
7. Best Practices
✅ When to Use Constants
- Mathematical values: PI, E, GOLDEN_RATIO
- Configuration: MAX_USERS, DEFAULT_TIMEOUT, API_URL
- Physical constants: SPEED_OF_LIGHT, GRAVITY
- Status codes: SUCCESS_CODE, ERROR_CODE
- Magic numbers: Any hardcoded number used multiple times
- Fixed strings: ERROR_MESSAGES, DEFAULT_LANGUAGE
❌ When NOT to Use Constants
- Values that change: user input, current time, counters
- Temporary variables: loop variables, calculation intermediates
- Method parameters: Don't make parameters final unless needed
- Local scope only: If used only once in one method
// ❌ Bad: Magic numbers scattered everywhere
double area1 = 3.14159 * 5 * 5;
double area2 = 3.14159 * 10 * 10;
double circumference = 2 * 3.14159 * 5;
// ✅ Good: Use constant
final double PI = 3.14159;
double area1 = PI * 5 * 5;
double area2 = PI * 10 * 10;
double circumference = 2 * PI * 5;
// ❌ Bad: No constant for tax rate
double total1 = price * 1.10;
double total2 = amount * 1.10;
// ✅ Good: Use constant
final double TAX_RATE = 0.10;
double total1 = price * (1 + TAX_RATE);
double total2 = amount * (1 + TAX_RATE);
- Group related constants: ဆက်စပ်တဲ့ constants တွေကို class တစ်ခုထဲ စုထားပါ
- Document purpose: Comment ထည့်ပြီး constant ရဲ့ ရည်ရွယ်ချက် ရှင်းပြပါ
- Use meaningful names: MAX_SIZE က x ထက် ကောင်းတယ်
- Avoid magic numbers: Hardcoded numbers တွေကို constants အဖြစ် လုပ်ပါ
- static final for class-level: တစ်ခုထက် ပိုသော instance မှာ သုံးမယ်ဆို static final လုပ်ပါ
8. Complete Example
public class ShoppingCart {
// Constants for the application
public static final double TAX_RATE = 0.10; // 10% tax
public static final double DISCOUNT_RATE = 0.15; // 15% discount
public static final double FREE_SHIPPING_THRESHOLD = 50.0;
public static final double SHIPPING_COST = 5.99;
public static final int MAX_ITEMS = 100;
public static void main(String[] args) {
// Product prices
double itemPrice1 = 25.00;
double itemPrice2 = 30.00;
int quantity = 2;
// Calculate subtotal
double subtotal = (itemPrice1 + itemPrice2) * quantity;
System.out.println("Subtotal: $" + subtotal);
// Apply discount
double discount = subtotal * DISCOUNT_RATE;
double afterDiscount = subtotal - discount;
System.out.println("Discount: $" + discount);
System.out.println("After discount: $" + afterDiscount);
// Add tax
double tax = afterDiscount * TAX_RATE;
double total = afterDiscount + tax;
System.out.println("Tax: $" + tax);
// Calculate shipping
double shipping = (total >= FREE_SHIPPING_THRESHOLD) ? 0 : SHIPPING_COST;
total += shipping;
if (shipping == 0) {
System.out.println("Free shipping!");
} else {
System.out.println("Shipping: $" + shipping);
}
System.out.println("Total: $" + total);
// Check item limit
if (quantity > MAX_ITEMS) {
System.out.println("Exceeded maximum items!");
}
}
}
Subtotal: $110.0
Discount: $16.5
After discount: $93.5
Tax: $9.35
Total: $102.85
Free shipping!
9. Key Takeaways
- final keyword: Makes variable immutable (cannot reassign)
- Constants naming: UPPER_SNAKE_CASE convention
- Must initialize: Assign value when declaring (local)
- static final: Class-level constants shared by all instances
- Compile-time check: Compiler prevents reassignment
- Reference types: Reference final, content can change
- Use for fixed values: PI, MAX_SIZE, TAX_RATE
- Avoid magic numbers: Replace with named constants
- Group constants: Create config/constants classes
- Document purpose: Add comments for clarity
- Meaningful names: MAX_USERS better than X
- Thread-safe: Constants are safe for concurrent access
🎉 Congratulations!
Module 2: Variables & Data Types - COMPLETED!
You've successfully learned:
- ✅ Variables and Literals
- ✅ Data Types (8 primitives + references)
- ✅ Operators (Arithmetic, Relational, Logical)
- ✅ Constants and Final keyword
Next: Module 3 - Control Flow (If-Else, Switch, Loops)
💡 Practice Exercise
Create a BankAccount class with constants:
- MINIMUM_BALANCE (final double)
- INTEREST_RATE (static final double)
- MAX_WITHDRAWAL (static final double)
- CURRENCY (static final String)
- Calculate interest using the constant rate
- Validate withdrawal against MAX_WITHDRAWAL
💡 Quick Quiz
Q1: Which keyword makes a variable constant?
Q2: What is the correct naming for constants?
Q3: Can you change a final variable after initialization?