Variables and Constants in Java – Complete Master Guide
Java programming me variable ek container hota hai jo data store karta hai. Har program me data ko temporarily ya permanently store karne ke liye variables ka use hota hai. Agar aap Java seekh rahe hain to variables sabse important concept hai.
What is a Variable?
Variable ek named memory location hoti hai jisme value store hoti hai. Jab program run hota hai tab memory allocate hoti hai.
int age = 25;
Yaha: • int = data type • age = variable name • 25 = value
Rules for Declaring Variables
- Variable name number se start nahi ho sakta
- Special characters allowed nahi
- Java keywords use nahi kar sakte
- Case sensitive hote hain
Types of Variables in Java
1️⃣ Local Variable
Method ke andar declare hota hai.
void display(){
int num = 10;
}
Local variable sirf method ke andar accessible hota hai.
2️⃣ Instance Variable
Class ke andar but method ke bahar declare hota hai.
class Student{
String name;
}
Object create hone par instance variable initialize hota hai.
3️⃣ Static Variable
Static keyword ke sath declare hota hai.
class Test{
static int count = 0;
}
Static variable class level par shared hota hai.
Memory Concept (Stack vs Heap)
| Stack Memory | Heap Memory |
|---|---|
| Local variables | Objects |
| Fast access | Dynamic memory |
What is a Constant?
Constant wo variable hota hai jiska value change nahi hota. Java me final keyword se constant banate hain.
final double PI = 3.14159;
Why Use Constants?
- Security
- Fixed configuration values
- Mathematical constants
- Better readability
Naming Convention
Variable: camelCase Constant: UPPER_CASE
int studentAge;
final double MAX_VALUE = 100;
Default Values of Variables
| Data Type | Default Value |
|---|---|
| int | 0 |
| boolean | false |
| Object | null |
Interview Questions
Q1: Difference between instance and static variable?
Instance object specific hota hai, static class specific hota hai.
Q2: What happens if variable not initialized?
Local variable error dega.
Q3: Why use final keyword?
To make variable constant.
Common Mistakes
- Uninitialized local variable
- Wrong naming convention
- Static misuse
Best Practices
- Meaningful variable names
- Avoid global variables
- Use constants for fixed values
- Follow Java naming standards
Conclusion
Variables aur constants Java programming ka foundation hain. Inhe samajhna bahut zaruri hai agar aap software developer banna chahte hain.
Related Posts: Non-Primitive Data Types | Type Casting in Java
0 टिप्पणियाँ