Java के Variables
In this page:
dataType variableName = value;
dataType a, b, c;
variableName = newValue;
Variable Declaration
एक variable declare करना (जैसे int age;) इसके type के अनुसार sized memory में एक slot reserve करता है, लेकिन वह slot तब तक garbage या एक default value रखता है जब तक आप असल में इसे कुछ assign न करें।
उदाहरण: Variable Declaration
public class Main {
public static void main(String[] args) {
int age; // declared - not yet assigned a meaningful value
age = 25; // now assigned
System.out.println(age);
}
}
Login to try C/C++/Java/PHP code in the editor
Variable Initialization
Declaration और assignment को एक line में combine करना, जैसे int age = 25;, सबसे आम pattern है और किसी variable को meaningful value दिए जाने से पहले गलती से उपयोग करने के risk से बचाता है।
उदाहरण: Variable Initialization
public class Main {
public static void main(String[] args) {
int age = 25; // declaration and assignment combined
System.out.println(age);
}
}
Login to try C/C++/Java/PHP code in the editor
Modifying Variables
Reassignment बस उसी memory slot में एक नई value लिखता है, जब तक नई value का type match करे (या variable के declared type में automatically convert हो सके)।
उदाहरण: Modifying Variables
public class Main {
public static void main(String[] args) {
int age = 25;
age = 26; // reassigned - new value must match the declared type
System.out.println(age);
}
}
Login to try C/C++/Java/PHP code in the editor
Multiple Variables
int x = 1, y = 2, z = 3; लिखना एक statement में तीन अलग int variables declare करता है -- closely related values के लिए convenient, हालांकि clarity अक्सर unrelated वालों के लिए अलग lines पसंद करती है।
उदाहरण: Multiple Variables
// Define the class Main
public class Main {
// Program entry point: the JVM starts running here
public static void main(String[] args) {
int x = 1, y = 2, z = 3;
// Print a line to the console
System.out.println(x + " " + y + " " + z);
}
}
Login to try C/C++/Java/PHP code in the editor
Variable Scope
Local variables सिर्फ उस method या block के अंदर रहते हैं जहां वे declared हैं और इसके return होने पर गायब हो जाते हैं, जबकि instance variables (class level पर declared) object की lifetime के लिए persist करते हैं और उस class में हर method को visible हैं।
उदाहरण: Variable Scope
public class Main {
int instanceVar = 100; // lives as long as the object exists
void showLocal() {
int localVar = 5; // exists only inside this method
System.out.println(localVar);
}
public static void main(String[] args) {
new Main().showLocal();
}
}
Login to try C/C++/Java/PHP code in the editor
- एक local variable को initialize किए बिना उपयोग करना, जो
might not have been initializedcompile error है। - उसी scope में उसी variable को दो बार declare करना, जैसे
int x = 1; int x = 2;। - किसी variable को इसके declared block के बाहर उपयोग करना, जैसे loop के बाद एक loop variable।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: