Lesson 5 of 24 Variables and Literals
Lesson 5 ⏱ 10 min read

Variables and Literals

Java မှာ data သိမ်းဆည်းတဲ့ variables တွေနဲ့ literal values တွေကို လေ့လာကြမယ်။

1. Variables ဆိုတာ ဘာလဲ?

A variable is a container that stores data values during program execution.

Simple Variable Example
int age = 25;
String name = "John";
double salary = 5000.50;

System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
📦 မြန်မာလို ရှင်းပြရင်

Variable ဆိုတာ data တန်ဖိုး သိမ်းဆည်းထားနိုင်တဲ့ container (သေတ္တာ) တစ်ခု ဖြစ်ပါတယ်။

  • Variable name: သေတ္တာပေါ်က အမည် (age, name, salary)
  • Variable value: သေတ္တာထဲက အရာ (25, "John", 5000.50)
  • Data type: သေတ္တာ အမျိုးအစား (int, String, double)

ဘာကြောင့် လိုအပ်လဲ?

  • Store data - Information သိမ်းထားနိုင်တယ်
  • Reuse values - တူညီတဲ့ value ကို နေရာအများကြီးမှာ သုံးလို့ရတယ်
  • Modify data - Value ပြောင်းလဲနိုင်တယ်
  • Readable code - Code နားလည်ရလွယ်တယ်

2. Variable Declaration (ကြေညာခြင်း)

Syntax: dataType variableName;

Declaration Examples
// Single declarations
int age;
String name;
double salary;
boolean isStudent;

// Multiple declarations
int x, y, z;
💡 Declaration အကြောင်း
  • dataType - Variable မှာ သိမ်းမယ့် data အမျိုးအစား
  • variableName - Variable အမည် (ကိုယ်တိုင်ရွေးနိုင်တယ်)
  • Declaration ပြီးရင် memory မှာ နေရာရပါပြီ
  • ဒါပေမယ့် value မရှိသေးပါ (uninitialized)

3. Variable Initialization (Value ပေးခြင်း)

Declaration + Initialization Together (Recommended)

Combined Approach
int age = 25;
String name = "Alice";
double price = 99.99;
boolean isActive = true;

int a = 10, b = 20, c = 30;

Separate Steps

Two-Step Process
// Declare first
int score;
String city;

// Initialize later
score = 100;
city = "Yangon";

System.out.println("Score: " + score);
System.out.println("City: " + city);

⚠️ Important Rules

  • Local variables must be initialized before use
  • Uninitialized variable သုံးရင် compilation error ပေါ်ပါတယ်
  • Best practice: Declaration နဲ့ initialization ကို တစ်ကြိမ်တည်း လုပ်ပါ
// ❌ Error
int x;
System.out.println(x);  // Error!

// ✅ Correct
int y = 10;
System.out.println(y);  // Works

4. Variable Assignment (Value ပြောင်းလဲခြင်း)

Reassignment Example
// Initial value
int score = 50;
System.out.println("Initial: " + score);

// Reassign new value
score = 75;
System.out.println("Updated: " + score);

// Update based on previous value
score = score + 10;
System.out.println("Final: " + score);  // 85
🔄 Assignment အကြောင်း
  • = operator က right side value ကို left side variable မှာ သိမ်းတယ်
  • Old value က ပျောက်သွားပြီး new value ဖြစ်သွားတယ်
  • Self-assignment လုပ်လို့ ရတယ်: x = x + 1;
  • Data type က compatible ဖြစ်ရပါမယ်
int age = 25;     // ✅ Correct
age = 30;         // ✅ Correct
age = "Thirty";   // ❌ Error! Type mismatch

5. Variable Naming Rules (အမည်ပေးစည်းမျဉ်းများ)

✅ Valid Naming Rules

  • Start with letter, $ or _ - Digit နဲ့ မစနိုင်ပါ
  • Can contain letters, digits, $ and _
  • Case-sensitive - age ≠ Age ≠ AGE
  • No spaces - Use camelCase instead
  • Cannot use Java keywords - int, class, public စတာတွေ မသုံးနိုင်ပါ
Examples
// ✅ Valid names
int age;
int studentAge;
int student_age;
int _count;
int $price;
int age2;

// ❌ Invalid names
int 2age;        // Cannot start with digit
int student-age; // Cannot use hyphen
int my age;      // Cannot have space
int class;       // Java keyword
int public;      // Java keyword

📝 Naming Conventions (Best Practices)

  • camelCase for variables: studentName, totalScore
  • Descriptive names: age လို့ရေးပါ, a လို့ မရေးပါနဲ့
  • Avoid abbreviations: number လို့ရေးပါ, num လို့ တတ်နိုင်သမျှ ရှောင်ပါ
  • Start with lowercase: userName (not UserName)
  • Constants in UPPER_CASE: MAX_VALUE, PI
Good vs Bad Examples
// ❌ Bad naming
int a = 25;
int x = "John";
int sd = 5000;

// ✅ Good naming
int studentAge = 25;
String studentName = "John";
double studentSalary = 5000;

6. Literals (တန်ဖိုး အမျိုးအစားများ)

A literal is a fixed value written directly in the code.

6.1 Integer Literals

Integer Examples
int decimal = 100;      // Decimal (base 10)
int binary = 0b1010;    // Binary (base 2) = 10
int octal = 0144;       // Octal (base 8) = 100
int hex = 0x64;         // Hexadecimal (base 16) = 100

long bigNumber = 1000000000L;  // Long literal (L suffix)
🔢 Integer Literals အကြောင်း
  • Decimal: ပုံမှန် ဂဏန်း - 10, 100, 255
  • Binary: 0b နဲ့ စတယ် - 0b1010 = 10
  • Octal: 0 နဲ့ စတယ် - 0144 = 100
  • Hexadecimal: 0x နဲ့ စတယ် - 0xFF = 255
  • Long suffix: L or l (capital L ပိုကောင်းတယ်)
  • Underscore: Readability အတွက် _ သုံးလို့ရတယ် - 1_000_000

6.2 Floating-Point Literals

Decimal Numbers
double price = 99.99;      // double (default)
float rate = 5.5f;         // float (f suffix required)
double scientific = 1.5e3; // Scientific notation = 1500.0
double negative = -3.14;

// Underscore for readability
double million = 1_000_000.50;
💰 Floating-Point အကြောင်း
  • Double: Default ဖြစ်တယ် (64-bit) - 3.14, 99.99
  • Float: f or F suffix လိုတယ် (32-bit) - 5.5f
  • Scientific notation: 1.5e3 = 1.5 × 10Âł = 1500
  • Precision: double က float ထက် accurate ပိုများတယ်

6.3 Character Literals

Single Characters
char letter = 'A';
char digit = '9';
char symbol = '@';

// Escape sequences
char newline = '\n';
char tab = '\t';
char quote = '\'';
char backslash = '\\';

// Unicode
char heart = '\u2665';  // ♥
🔤 Character Literals အကြောင်း
  • Single quotes: 'A', 'B', '1' (double quotes မဟုတ်ပါ)
  • One character only: 'AB' မရပါ, "AB" က String ပါ
  • Escape sequences: \n (newline), \t (tab), \' (quote)
  • Unicode: \uXXXX format - \u0041 = 'A'

6.4 String Literals

Text Strings
String name = "John Doe";
String message = "Hello, World!";
String empty = "";          // Empty string
String number = "123";      // String, not number!

// Escape sequences in strings
String path = "C:\\Users\\Desktop";
String quote = "He said, \"Hello\"";
String multi = "Line 1\nLine 2\nLine 3";
📝 String Literals အကြောင်း
  • Double quotes: "Hello" (single quotes မဟုတ်ပါ)
  • Multiple characters: "", "A", "ABC", "Hello World"
  • Escape sequences work: \n, \t, \", \\
  • Immutable: String value ပြောင်းလို့မရပါ (create new one)
  • Concatenation: + operator နဲ့ ပေါင်းလို့ ရတယ်

6.5 Boolean Literals

True or False
boolean isStudent = true;
boolean isActive = false;

// Commonly used in conditions
boolean hasPermission = true;
boolean isComplete = false;

System.out.println(isStudent);  // true
System.out.println(isActive);   // false
✓✗ Boolean အကြောင်း
  • Only two values: true or false
  • Lowercase only: True, FALSE, 1, 0 မရပါ
  • Used for logic: Conditions, loops, flags
  • Default value: false (for class-level variables)

7. Complete Example

VariableDemo.java
public class VariableDemo {
    public static void main(String[] args) {
        // Integer variables
        int studentCount = 30;
        int totalMarks = 2850;
        
        // Floating-point
        double averageScore = 85.5;
        double percentage = 95.67;
        
        // Character
        char grade = 'A';
        
        // String
        String courseName = "Java Programming";
        String instructor = "Mr. Smith";
        
        // Boolean
        boolean isPassed = true;
        boolean isCompleted = false;
        
        // Display information
        System.out.println("=== Course Information ===");
        System.out.println("Course: " + courseName);
        System.out.println("Instructor: " + instructor);
        System.out.println("Students: " + studentCount);
        System.out.println("Average Score: " + averageScore);
        System.out.println("Percentage: " + percentage + "%");
        System.out.println("Grade: " + grade);
        System.out.println("Passed: " + isPassed);
        System.out.println("Completed: " + isCompleted);
        
        // Calculate
        double scorePerStudent = (double) totalMarks / studentCount;
        System.out.println("Score per student: " + scorePerStudent);
    }
}
Output
=== Course Information ===
Course: Java Programming
Instructor: Mr. Smith
Students: 30
Average Score: 85.5
Percentage: 95.67%
Grade: A
Passed: true
Completed: false
Score per student: 95.0

8. Key Takeaways

  • Variables store data - Container for values
  • Declaration: dataType variableName;
  • Initialization: Give it a value
  • Assignment: Change the value using =
  • Naming rules: Start with letter/$/_, no spaces, no keywords
  • camelCase convention: studentName, totalScore
  • Integer literals: 100, 0b1010, 0x64, 1000L
  • Float literals: 99.99, 5.5f, 1.5e3
  • Char literals: 'A', '\n', '\u2665'
  • String literals: "Hello", "Java"
  • Boolean literals: true, false
  • Local variables must be initialized before use

💡 Practice Exercise

Create a StudentInfo program:

  • Declare variables: name, age, grade, gpa, isEnrolled
  • Initialize with appropriate values
  • Print all information
  • Calculate and print years until graduation (assume 4 year program)

💡 Quick Quiz

Q1: Which is a valid variable name?

Q2: What's the correct way to declare and initialize an integer?

Q3: Which literal is a character?

← Previous
Next →

Your Notes

0 notes
✓ Saved