Learning Outcomes#
हा chapter पूर्ण केल्यानंतर तुम्ही:
- Java मध्ये variable म्हणजे काय आणि त्याची गरज का असते हे explain करू शकाल.
- declaration, initialization आणि assignment यांच्यातील फरक ओळखू शकाल.
- योग्य आणि चुकीची variable names identify करू शकाल.
- professional Java naming conventions वापरून meaningful variable names लिहू शकाल.
- local, instance आणि static variables code मधून identify करू शकाल.
- local variable वापरण्यापूर्वी value assign का करावी लागते हे reason करू शकाल.
- instance variable प्रत्येक object साठी independent का असते हे explain करू शकाल.
- static variable class-level shared state कशी represent करते हे beginner level वर समजू शकाल.
- variable-related common compile-time mistakes diagnose करू शकाल.
- beginner-level interview questions confidently answer करू शकाल.
या chapter मधील examples Java SE 26 language rules शी compatible आहेत. सध्या JDK 26 हा latest Java SE release आहे आणि JDK 25 हा latest LTS release आहे.
या chapter मध्ये int, String, double, boolean यांसारखे types examples मध्ये वापरले जातील. त्यांचे types, ranges आणि detailed behavior पुढच्या Java Data Types chapter मध्ये शिकणार आहोत.1. What is a Variable?#
समजा आपण एक student learning application बनवत आहोत.
आपल्याला student बद्दल अशी माहिती temporarily program मध्ये ठेवायची आहे:
- student चे नाव
- age
- completed lessons
- score
- login status
उदाहरण:
Name = Rahul
Age = 22
Score = 85Program ला ही values कुठेतरी ठेवावी लागतील, जेणेकरून पुढे त्या वापरता किंवा बदलता येतील.
यासाठी variables वापरले जातात.
Definition#
A variable is a named storage location associated with a type, used to hold a value that a program can access and, when allowed, change.
मराठीत सांगायचे तर:
Variable म्हणजे program मधील value ठेवण्यासाठी वापरली जाणारी ओळख असलेली storage location.
Java Language Specification देखील variable ला associated type असलेली storage location म्हणून define करते.
उदाहरण:
Java
int age = 22;यामध्ये:
int → variable चा type
age → variable चे name
22 → variable मध्ये ठेवलेली valueConceptually:
Variable Name
↓
age
┌───────────────┐
│ 22 │
└───────────────┘आपण नंतर age हे नाव वापरून त्यामधील value access करू शकतो.
Java
public class StudentProfile {
public static void main(String[] args) {
int age = 22;
System.out.println(age);
}
}Text
22Variable का आवश्यक आहे?#
Consider:
Java
System.out.println(500);
System.out.println(500 * 12);
System.out.println(500 * 24);इथे 500 ही value repeated आहे.
त्याऐवजी:
Java
int monthlyFee = 500;
System.out.println(monthlyFee);
System.out.println(monthlyFee * 12);
System.out.println(monthlyFee * 24);आता fee बदलायची असेल तर एका ठिकाणी बदल करता येतो.
int monthlyFee = 600;Variable मुळे code:
- readable होतो
- maintain करणे सोपे होते
- values reuse करता येतात
- calculations करता येतात
- runtime information store करता येते
- changing state represent करता येते
Real-world thinking#
Requirement:
Student ने किती lessons complete केले आहेत ते track करायचे आहे.
Value:
12पण code मध्ये फक्त 12 पाहिल्यावर त्याचा अर्थ कळत नाही.
int completedLessons = 12;आता value चा business meaning स्पष्ट झाला.
Important Principle#
Variable फक्त value ठेवत नाही.
Good variable name त्या value चा meaning देखील communicate करते.
Weak:
int x = 12;Better:
int completedLessons = 12;2. Variable Declaration#
Variable वापरण्यापूर्वी Java ला त्याबद्दल सांगावे लागते.
याला variable declaration म्हणतात.
Definition#
A variable declaration introduces a variable by specifying its type and identifier.
मराठीत:
Variable declaration म्हणजे Java compiler ला:
- variable चा type काय आहे
- variable चे नाव काय आहे
हे सांगणे.
Basic syntax:
type variableName;Example:
Java
int age;इथे:
int → type
age → variable identifier/name
; → statement terminatorआता आपण variable declare केला आहे.
पण local variable असल्यास अजून त्याला usable value दिलेली नाही.
Declaration examples#
Java
int age;
String studentName;
double coursePrice;
boolean courseCompleted;या chapter मध्ये types चे detailed explanation करणार नाही. ते पुढच्या Java Data Types chapter मध्ये येईल.
आत्ता फक्त pattern समजा:
Type + Variable NameDeclaration vs Value#
हे दोन वेगळे concepts आहेत.
int age;याचा अर्थ:
age नावाचा variable declare केला.हे:
age = 25;याचा अर्थ:
age ला value assign केली.आणि हे:
int age = 25;यामध्ये declaration आणि initial value दोन्ही एकाच statement मध्ये आहेत.
Multiple variables एका statement मध्ये declare करता येतात का?#
हो.
हे legal आहे:
Java
int age, score, attempts;पण beginner आणि production readability साठी सामान्यतः हे जास्त स्पष्ट आहे:
Java
int age;
int score;
int attempts;कारण प्रत्येक variable चा purpose वेगळा दिसतो.
3. Variable Initialization#
Variable declare केल्यानंतर त्यामध्ये usable value ठेवणे आवश्यक असते.
Definition#
Initialization is the process of giving a variable its initial value.
मराठीत:
Variable ला पहिली meaningful value देण्याच्या प्रक्रियेला initialization म्हणतो.
Example:
Java
int age = 22;इथे:
Declaration
↓
int age
Initialization
↓
= 22Declaration आणि Initialization एकत्र#
Production code मध्ये हा pattern खूप common आहे:
Java
String studentName = "Rahul";
int completedLessons = 15;
boolean courseCompleted = false;Variable तयार करतानाच meaningful value उपलब्ध असेल तर declaration सोबत initialize करणे code अधिक clear बनवते.
Declare first, assign later#
कधी value सुरुवातीला available नसते.
Conceptually:
Java
int score;
score = 90;
System.out.println(score);इथे:
int score; → declaration
score = 90; → assignmentscore = 90 ही declaration मधील initializer नाही; ती नंतरची assignment आहे.
Assignment म्हणजे काय?#
Definition#
Assignment stores a value into an already declared variable.
मराठीत:
Already declared variable मध्ये value ठेवण्याच्या operation ला assignment म्हणतो.
Example:
Java
int score;
score = 80;Reassignment#
जर variable change करण्याची परवानगी असेल तर त्याला नवीन value पुन्हा assign करता येते.
Java
int completedLessons = 5;
completedLessons = 6;
completedLessons = 7;
System.out.println(completedLessons);Text
7Flow:
completedLessons
↓
5
↓
6
↓
7Current value 7 आहे.
Declaration, Initialization, Assignment, Reassignment#
| Operation | Example | Meaning |
|---|---|---|
| Declaration | int score; | variable introduce केला |
| Declaration + Initialization | int score = 80; | variable declare करून initial value दिली |
| Assignment | score = 80; | declared variable मध्ये value ठेवली |
| Reassignment | score = 90; | existing value नवीन value ने बदलली |
हा distinction interview मध्येही महत्त्वाचा आहे.
Local variable बद्दल एक critical rule#
हे code पाहा:
Java
public class Example {
public static void main(String[] args) {
int score;
System.out.println(score);
}
}हे valid runnable program नाही.
कारण score हा local variable आहे आणि त्याला वापरण्यापूर्वी value assign केलेली नाही.
Correct:
Java
public class Example {
public static void main(String[] args) {
int score = 0;
System.out.println(score);
}
}Java definite-assignment rules local variable ची value initialized किंवा assigned असल्याचे compiler ला verify करता आले पाहिजे, अन्यथा variable वापरता येत नाही.
हा rule आपण Local Variables section मध्ये detail मध्ये समजून घेऊ.
4. Variable Naming Rules#
Variable चे नाव technically identifier असते.
Definition#
An identifier is a name used to identify a declared program element such as a variable.
मराठीत:
Identifier म्हणजे program मधील variable सारख्या declared element ला ओळखण्यासाठी वापरलेले नाव.
उदाहरण:
int studentAge = 22;studentAge हा identifier आहे.
Rule 1 — Variable name digit ने start करू शकत नाही#
Valid:
int age2;
int student2;Invalid:
int 2age;कारण first character valid Java identifier-start character असला पाहिजे. Digits नंतर वापरता येतात.
Rule 2 — Spaces allowed नाहीत#
Invalid:
int student age;Java याला एक variable name म्हणून treat करणार नाही.
Correct:
int studentAge;Rule 3 — Reserved keyword variable name म्हणून वापरता येत नाही#
Invalid:
int class;Invalid:
int static;Invalid:
int public;कारण class, static, public हे reserved keywords आहेत.
Rule 4 — Variable names case-sensitive आहेत#
हे तीन वेगवेगळे identifiers आहेत:
Java
int age = 20;
int Age = 30;
int AGE = 40;Java साठी:
age ≠ Age ≠ AGEहे technically valid असले तरी असे confusing naming करू नये.
Rule 5 — _ single-character variable name म्हणून वापरता येत नाही#
Modern Java मध्ये हे invalid आहे:
int _ = 10;_ single character आता reserved keyword आहे.
पण multi-character identifier मध्ये underscore येऊ शकतो:
int student_age = 20;हे syntactically possible आहे.
परंतु regular Java variables साठी studentAge conventionally better आहे.
Java SE 26 identifier rules नुसार underscore multi-character identifier मध्ये वापरता येतो, पण _ एकटा identifier म्हणून वापरता येत नाही.
Rule 6 — $ technically legal आहे, पण normal code मध्ये avoid करा#
हे technically legal असू शकते:
int $total = 100;पण professional application code मध्ये असे names वापरणे avoid करा.
Java specification $ identifier मध्ये permit करते, पण सामान्य source code मध्ये त्याचा वापर recommended नाही.
Better:
int total = 100;Rule 7 — Meaningful names वापरा#
Weak:
int x = 25;Better:
int studentAge = 25;Weak:
int n = 10;Better:
int totalLessons = 10;Variable नाव पाहिल्यावर त्यामध्ये काय value आहे याचा purpose अंदाज येणे आवश्यक आहे.
Naming Convention — lowerCamelCase#
Java variables साठी widely used convention:
first word lowercase
next words start with uppercase letterExamples:
studentName
coursePrice
completedLessons
loginAttempts
isActive
totalScoreयाला lowerCamelCase म्हणतात.
Oracle's Java naming guidance देखील ordinary field/variable names mixed case मध्ये lowercase first letter ने लिहिण्याची convention दाखवते.
Valid vs Recommended#
एक important difference:
Syntax rule#
Compiler काय accept करतो.
Naming convention#
Professional developers काय prefer करतात.
उदाहरण:
int $Student_Age = 25;काही contexts मध्ये technically valid असले तरी हा good professional variable name नाही.
Better:
int studentAge = 25;Variable Naming Checklist#
Variable name लिहिताना स्वतःला विचारा:
- नाव valid identifier आहे का?
- digit ने start होत नाही ना?
- keyword नाही ना?
- spaces नाहीत ना?
- purpose स्पष्ट आहे का?
- lowerCamelCase वापरले आहे का?
- unnecessary
$किंवा_नाहीत ना? - नाव unnecessarily short नाही ना?
5. Local Variables#
आता variable कुठे declare केला आहे यावरून त्याचे behavior बदलते.
सगळ्यात आधी local variable पाहू.
Definition#
A local variable is a variable declared within a method, block, or another local statement context and used within its permitted scope.
मराठीत:
Method किंवा block च्या आत declare केलेल्या आणि त्या local scope मध्ये वापरल्या जाणाऱ्या variable ला local variable म्हणतो.
Example:
Java
public class CourseProgress {
public static void main(String[] args) {
int completedLessons = 12;
System.out.println(completedLessons);
}
}completedLessons हा local variable आहे.
कारण तो main method च्या आत declare केला आहे.
Local म्हणजे "nearby scope"#
Conceptually:
main() method starts
↓
local variable created
↓
variable used
↓
method/block finishes
↓
local variable no longer usable thereBeginner level वर इतके लक्षात ठेवा:
Local variable त्या method किंवा block च्या local work साठी असतो.
Practical example#
समजा method चा purpose discount calculate करणे आहे.
Java
public class CoursePrice {
public static void main(String[] args) {
int coursePrice = 2000;
int discount = 500;
int finalPrice = coursePrice - discount;
System.out.println(finalPrice);
}
}Text
1500इथे:
coursePrice
discount
finalPriceहे सर्व main method मधील local variables आहेत.
Local variable ला default value मिळत नाही#
हा अत्यंत महत्त्वाचा rule आहे.
Wrong:
Java
public class ScoreExample {
public static void main(String[] args) {
int score;
System.out.println(score);
}
}score वापरण्यापूर्वी value दिलेली नाही.
Correct:
Java
public class ScoreExample {
public static void main(String[] args) {
int score = 0;
System.out.println(score);
}
}Java मध्ये local variable चा value use करण्यापूर्वी compiler ला तो definitely assigned असल्याचे verify करता आले पाहिजे.
Local variable scope#
Definition#
Scope is the region of source code where a declared name can be referred to.
मराठीत:
Variable कुठल्या code region मध्ये accessible आहे त्याला त्याचा scope म्हणतो.
Example:
Java
public class ScopeExample {
public static void main(String[] args) {
int score = 80;
{
int bonus = 10;
System.out.println(score);
System.out.println(bonus);
}
System.out.println(score);
}
}bonus inner block च्या आत आहे.
Block:
{
...
}त्या block बाहेर bonus वापरण्याचा प्रयत्न केला तर compile-time problem येईल.
Wrong:
{
int bonus = 10;
}
System.out.println(bonus);Mental Model#
main method
│
├── score
│
├── inner block
│ └── bonus
│
└── score still accessiblebonus चा scope inner block पर्यंत आहे.
Local variable कधी वापरायचा?#
जेव्हा value फक्त एखाद्या temporary calculation किंवा method-level operation साठी आवश्यक आहे.
Examples:
int total;
double finalPrice;
boolean eligible;
String message;Use case:
Requirement:
Course price वर discount calculate करायचा.
Temporary values:
coursePrice
discount
finalPrice
Best fit:
Local variablesकारण त्यांची गरज त्या calculation पुरतीच आहे.
6. Instance Variables#
आता समजा application मध्ये अनेक students आहेत.
Student 1:
Name = Rahul
Completed Lessons = 12Student 2:
Name = Sneha
Completed Lessons = 7प्रत्येक student ची value independent आहे.
ही object-specific state instance variables ने represent करता येते.
Definition#
An instance variable is a non-static field declared in a class, with a separate variable associated with each object of that class.
मराठीत:
Class मध्ये method च्या बाहेर आणि static शिवाय declare केलेल्या field ला instance variable म्हणतात.
प्रत्येक object ला त्या instance variable ची स्वतःची independent copy मिळते. Java Language Specification देखील प्रत्येक newly created object सोबत non-static field ची new instance variable तयार होते असे specify करते.
Class आणि Object — आवश्यक इतकाच context#
या chapter साठी एवढे समजा:
class म्हणजे object ची structure/template.
object म्हणजे त्या class वर आधारित actual instance.
उदाहरण:
Class
Student
Objects
Rahul Student
Sneha Student
Amit StudentObjects detail मध्ये पुढील appropriate chapter मध्ये शिकू.
Instance variable example#
Java
public class Student {
String name;
int completedLessons;
public static void main(String[] args) {
Student student1 = new Student();
Student student2 = new Student();
student1.name = "Rahul";
student1.completedLessons = 12;
student2.name = "Sneha";
student2.completedLessons = 7;
System.out.println(student1.name);
System.out.println(student1.completedLessons);
System.out.println(student2.name);
System.out.println(student2.completedLessons);
}
}Text
Rahul
12
Sneha
7name आणि completedLessons instance variables आहेत.
दोन objects मध्ये separate copies#
Conceptually:
Student class
│
├───────────────┐
│ │
student1 student2
│ │
├─ name ├─ name
│ Rahul │ Sneha
│ │
└─ lessons └─ lessons
12 7जेव्हा आपण:
student1.completedLessons = 20;करतो, तेव्हा student2.completedLessons automatically बदलत नाही.
कारण दोन्ही objects कडे independent instance variables आहेत.
Instance variables object state represent करतात#
Real application मध्ये:
class Student {
String name;
String email;
int completedLessons;
}प्रत्येक Student object ला वेगळे:
name
email
completedLessonsअसू शकतात.
यालाच object-specific state म्हणू शकतो.
Definition#
State represents the current data associated with an object.
मराठीत:
एखाद्या object शी सध्या संबंधित असलेल्या values म्हणजे त्या object ची state.
Instance variables ला default values मिळतात#
Local variable पेक्षा हा important difference आहे.
उदाहरण:
Java
public class Student {
int completedLessons;
boolean active;
String name;
public static void main(String[] args) {
Student student = new Student();
System.out.println(student.completedLessons);
System.out.println(student.active);
System.out.println(student.name);
}
}Fields automatically default-initialized होतात.
या example मध्ये:
completedLessons → 0
active → false
name → nullDetailed data-type rules पुढच्या chapter मध्ये शिकू. येथे फक्त variable behavior लक्षात ठेवा:
Instance variablesना default initialization मिळते; ordinary local variablesना मिळत नाही.
Java SE specification class variables आणि instance variablesना creation वेळी default value मिळते असे स्पष्ट करते.
7. Static Variables — Introduction#
आता scenario बदलू.
आपल्याकडे 10,000 students आहेत.
प्रत्येक student चे:
name
completedLessonsवेगळे आहेत.
पण सर्व students साठी training platform एकच आहे:
CodeLangs AIही value प्रत्येक object मध्ये duplicate ठेवण्याऐवजी class-level shared variable म्हणून ठेवता येते.
इथे static variable उपयोगी पडतो.
Definition#
A static variable is a field declared with the static keyword and associated with the class rather than with each individual object.
मराठीत:
Class मध्ये static keyword वापरून declare केलेल्या field ला static variable किंवा class variable म्हणतात.
त्याची प्रत्येक object साठी separate copy नसते.
त्या class संदर्भात एक shared variable असतो. Java specification static field साठी एकच incarnation असते असे specify करते.
Static variable syntax#
Java
static String platformName = "CodeLangs AI";Structure:
static
↓
static String platformName = "CodeLangs AI";
└──────────────────────────────────┘
fieldExample#
Java
public class Student {
String name;
static String platformName = "CodeLangs AI";
public static void main(String[] args) {
Student student1 = new Student();
Student student2 = new Student();
student1.name = "Rahul";
student2.name = "Sneha";
System.out.println(student1.name);
System.out.println(student2.name);
System.out.println(Student.platformName);
}
}Text
Rahul
Sneha
CodeLangs AIInstance data:
student1.name → Rahul
student2.name → SnehaShared class data:
Student.platformName → CodeLangs AIStatic variable class name ने access करणे#
Beginner code मध्ये static variable class name वापरून access करणे अधिक clear असते:
Student.platformNameयामुळे reader ला लगेच कळते:
ही value specific object ची नसून class-level आहे.
Instance vs Static#
Student class
│
├── static platformName
│ └── "CodeLangs AI"
│
├── student1
│ └── name = "Rahul"
│
└── student2
└── name = "Sneha"Notice:
nameप्रत्येक object साठी वेगळा आहे.
पण:
platformNameshared आहे.
Static म्हणजे global variable आहे का?#
पूर्णपणे तसे समजू नका.
Beginner misconception:
static variable म्हणजे program मधून कुठूनही वापरण्यासाठी global variable.
हे incomplete understanding आहे.
Correct understanding:
static field class शी associated असतो, individual object शी नाही.त्याची accessibility इतर Java rules वरदेखील depend करते.
त्यामुळे फक्त "मला कुठूनही access करायचे आहे" म्हणून प्रत्येक variable static करू नका.
Local vs Instance vs Static — Core Comparison#
| Feature | Local Variable | Instance Variable | Static Variable |
|---|---|---|---|
| Usually declared | method/block मध्ये | class मध्ये, method बाहेर | class मध्ये static सह |
| Belongs to | local execution | each object | class |
| Separate per object | Not applicable | Yes | No |
| Shared across objects | No | No | Yes |
| Automatic field default value | No | Yes | Yes |
| Typical purpose | temporary work | object state | class-wide shared data |
One Connected Example#
आता तिन्ही concepts एका realistic example मध्ये पाहू.
Java
public class CourseEnrollment {
String studentName;
int completedLessons;
static String platformName = "CodeLangs AI";
void showProgress() {
int remainingLessons = 20 - completedLessons;
System.out.println(studentName);
System.out.println(completedLessons);
System.out.println(remainingLessons);
System.out.println(platformName);
}
public static void main(String[] args) {
CourseEnrollment enrollment = new CourseEnrollment();
enrollment.studentName = "Rahul";
enrollment.completedLessons = 12;
enrollment.showProgress();
}
}Text
Rahul
12
8
CodeLangs AIClassification:
studentName → instance variable
completedLessons → instance variable
platformName → static variable
remainingLessons → local variable
enrollment → local variableReasoning:
studentName#
Student-specific आहे.
म्हणून instance variable.
completedLessons#
प्रत्येक student ची progress वेगळी.
म्हणून instance variable.
platformName#
सर्व enrollment objects साठी common.
म्हणून static variable.
remainingLessons#
showProgress() calculation पुरता temporary data आहे.
म्हणून local variable.
हा variable selection चा professional विचार आहे:
Value कोणाशी संबंधित आहे?
↓
Temporary calculation?
→ Local
Specific object?
→ Instance
Whole class/shared?
→ StaticPractical / Real-World Application#
Scenario — Online Course Application#
Requirement:
आपल्याला course enrollment model करायचे आहे.
प्रत्येक student साठी:
student name
course name
completed lessonsवेगळे आहेत.
पण company/platform name सर्वांसाठी common आहे.
Progress display करताना:
remaining lessonstemporary calculate करायचे आहेत.
Analysis:
| Data | Best Variable Kind | Reason |
|---|---|---|
studentName | Instance | प्रत्येक student वेगळा |
courseName | Instance | enrollment-specific |
completedLessons | Instance | प्रत्येक learner ची progress वेगळी |
platformName | Static | सर्व objects मध्ये common |
remainingLessons | Local | temporary calculation |
Implementation:
Java
public class Enrollment {
String studentName;
String courseName;
int completedLessons;
static String platformName = "CodeLangs AI";
void displayProgress() {
int totalLessons = 20;
int remainingLessons = totalLessons - completedLessons;
System.out.println("Student: " + studentName);
System.out.println("Course: " + courseName);
System.out.println("Completed: " + completedLessons);
System.out.println("Remaining: " + remainingLessons);
System.out.println("Platform: " + platformName);
}
public static void main(String[] args) {
Enrollment enrollment = new Enrollment();
enrollment.studentName = "Sneha";
enrollment.courseName = "Java Beginner Course";
enrollment.completedLessons = 14;
enrollment.displayProgress();
}
}Text
Student: Sneha
Course: Java Beginner Course
Completed: 14
Remaining: 6
Platform: CodeLangs AIया example मध्ये variable निवड arbitrary नाही.
ती requirement वर आधारित आहे.
Requirement → Variable Decision#
Professional development मध्ये असा विचार करा:
Requirement
↓
Value कोण represent करते?
↓
Value किती काळ लागेल?
↓
ती object-specific आहे का?
↓
ती सर्व objects मध्ये common आहे का?
↓
योग्य variable location निवडाहे reasoning coding पेक्षा जास्त महत्त्वाचे आहे.
Common Mistakes & Misconceptions#
Mistake 1 — Declaration म्हणजे initialization असे समजणे#
int score;हे initialization नाही.
हे declaration आहे.
Initialization:
int score = 80;Mistake 2 — Local variable automatically 0 होईल असे समजणे#
Wrong assumption:
int score;
System.out.println(score);"int आहे म्हणून 0 मिळेल."
Local variables साठी हे चुकीचे आहे.
Local variable वापरण्यापूर्वी assigned असणे आवश्यक आहे.
Mistake 3 — Instance variable आणि local variable एकच समजणे#
Compare:
class Student {
int score;
void calculate() {
int bonus = 10;
}
}score:
instance variablebonus:
local variableLocation आणि ownership वेगळे आहेत.
Mistake 4 — प्रत्येक variable static करणे#
Beginner अनेकदा compiler errors avoid करण्यासाठी:
static int score;
static String name;
static int age;असे करतो.
हे चुकीचे design होऊ शकते.
प्रश्न विचारा:
ही value सर्व objects मध्ये खरंच shared आहे का?
जर नाही:
static वापरू नका.Mistake 5 — Static variable प्रत्येक object साठी वेगळी समजणे#
जर:
static String platformName;असेल तर ती class-level shared variable आहे.
प्रत्येक object ची independent copy नाही.
Mistake 6 — Instance variable सर्व objects मध्ये shared आहे असे समजणे#
String studentName;जर non-static field असेल तर:
student1.studentName
student2.studentNameवेगवेगळ्या values ठेवू शकतात.
Mistake 7 — Variable name digit ने सुरू करणे#
Invalid:
int 1score;Correct:
int score1;Mistake 8 — Keyword variable name म्हणून वापरणे#
Invalid:
int static;Correct:
int staticCount;Mistake 9 — Case mismatch#
Declaration:
int studentAge = 20;Wrong usage:
System.out.println(studentage);studentAge आणि studentage वेगवेगळे identifiers आहेत.
Mistake 10 — Meaningless names#
Weak:
int a;
int b;
int c;Better:
int coursePrice;
int discountAmount;
int finalPrice;Mistake 11 — Scope ignore करणे#
Wrong:
{
int score = 80;
}
System.out.println(score);score त्याच्या valid local scope बाहेर वापरला आहे.
Mistake 12 — "Static म्हणजे faster" असे समजणे#
static keyword चा primary purpose:
make value class-associatedहा performance shortcut नाही.
Variable static करायचा निर्णय ownership/design वर based असावा.
Hands-On Practice#
Practice 1 — Identify the Parts#
Code:
Java
int completedLessons = 12;Learner Task#
Identify:
- type
- variable name
- initial value
Hint 1#
Variable declaration pattern आठवा:
type variableName = value;Solution#
Type = int
Variable Name = completedLessons
Initial Value = 12Practice 2 — Fix the Variable Names#
खालील names professional Java naming मध्ये rewrite करा:
Student_Name
COURSEprice
x
completed_lessonsHint#
Use:
lowerCamelCase
meaningful namesSolution#
studentName
coursePrice
studentCount
completedLessonsx चा exact replacement context वर depend करतो. येथे learner count represent करतो असे assume केल्यामुळे studentCount meaningful आहे.
Practice 3 — Find the Problem#
Java
public class Test {
public static void main(String[] args) {
int total;
System.out.println(total);
}
}Learner Task#
Code मध्ये problem काय आहे?
Hint#
Local variable initialization rule आठवा.
Solution#
total local variable आहे.
त्याला use करण्यापूर्वी value assign केलेली नाही.
Correct:
Java
public class Test {
public static void main(String[] args) {
int total = 0;
System.out.println(total);
}
}Practice 4 — Classify Variables#
Java
public class Student {
String name;
static String instituteName = "CodeLangs AI";
void showDetails() {
int completedLessons = 10;
System.out.println(name);
System.out.println(instituteName);
System.out.println(completedLessons);
}
}Classify:
name
instituteName
completedLessonsSolution#
name → Instance Variable
instituteName → Static Variable
completedLessons → Local VariablePractice 5 — Requirement Analysis#
Requirement:
प्रत्येक employee ची salary वेगळी आहे. Company name सर्व employees साठी common आहे. Monthly salary वरून annual salary temporary calculate करायची आहे.
Choose variable types.
Think Before Viewing Solution#
Questions:
- Employee-specific data कोणते?
- Shared data कोणते?
- Temporary calculation कोणते?
Solution#
salary → Instance Variable
companyName → Static Variable
annualSalary → Local VariableReason:
salary
→ प्रत्येक employee साठी वेगळी
companyName
→ सर्व employee objects साठी common
annualSalary
→ calculation पुरती temporaryInterview Preparation#
1. What is a variable in Java?
A variable is a named storage location associated with a type. It stores a value that can be accessed and, unless restricted, changed during program execution.
What the interviewer is testing: Whether you understand a variable conceptually instead of describing it only as "a container."
2. What is variable declaration?
Variable declaration introduces a variable by specifying its type and identifier.
Example:
int age;Here, int is the type and age is the variable name.
3. What is variable initialization?
Variable initialization means providing an initial value to a variable.
Example:
int age = 25;Here, 25 is the initial value.
4. What is the difference between declaration and initialization?
Declaration introduces a variable:
int score;Initialization provides its initial value:
int score = 90;A declaration and initialization can happen in the same statement.
5. What is assignment?
Assignment stores a value in an already declared variable.
Example:
int score;
score = 90;6. Can the value of a variable be changed after initialization?
Yes, if the variable is allowed to be reassigned.
Example:
int score = 70;
score = 90;The current value becomes 90.
7. What are the basic rules for naming variables in Java?
A variable name must be a valid Java identifier. It cannot start with a digit, cannot contain spaces, and cannot be a reserved keyword. Java identifiers are case-sensitive. Although $ and _ can appear in valid identifiers under specific rules, normal application code should use clear lowerCamelCase names.
8. Are Java variable names case-sensitive?
Yes.
age
Age
AGEare three different identifiers.
Common weak answer: "No, they represent the same variable."
That is incorrect.
9. Can a variable name start with a number?
No.
Invalid:
int 2score;Valid:
int score2;10. Can _ be used as a variable name?
A single underscore _ cannot be used as an ordinary identifier in modern Java because it is a reserved keyword. Underscore may appear as part of a longer valid identifier.
Example:
int student_age;However, studentAge follows the normal Java variable naming convention better.
11. What is a local variable?
A local variable is declared within a method, block, or another local statement context and is usable only within its permitted scope.
Example:
void calculate() {
int total = 10;
}total is a local variable.
12. Do local variables get default values in Java?
No. A local variable must be definitely assigned before its value is used.
Example:
int total;
System.out.println(total);is not valid because total has not been assigned a value before use.
What the interviewer is testing: A very common distinction between local variables and fields.
13. What is an instance variable?
An instance variable is a non-static field declared in a class. Each object of that class has its own associated instance variable.
Example:
class Student {
String name;
}Different Student objects can have different values for name.
14. Do instance variables receive default values?
Yes. Instance fields are automatically initialized with the default value associated with their type when the object is created.
For example, an int field defaults to 0, a boolean field defaults to false, and a reference field such as String defaults to null.
15. What is a static variable?
A static variable is a field declared with the static keyword. It is associated with the class rather than with each individual object.
Example:
static String platformName = "CodeLangs AI";16. What is another common name for a static variable?
A static field is commonly called a class variable.
17. What is the main difference between instance and static variables?
An instance variable belongs to an object, so different objects can have different values.
A static variable belongs to the class and is shared at the class level.
18. What is the difference between local, instance, and static variables?
A local variable is used for local method or block-level work.
An instance variable stores object-specific state.
A static variable stores class-level shared state.
19. Why should meaningful variable names be used?
Meaningful names communicate the purpose of stored data, improve readability, reduce misunderstanding, and make code easier to maintain.
Example:
int completedLessons;is clearer than:
int x;20. Should every field be made static for easy access?
No.
static should be used when the data logically belongs to the class rather than to individual objects.
Making fields static only to make access easier can create incorrect shared state and poor design.
Quick Revision#
Variable#
Named storage location associated with a type.Example:
int age = 25;Declaration#
int age;Introduces variable name and type.
Initialization#
int age = 25;Provides initial value.
Assignment#
age = 25;Stores a value in an already declared variable.
Reassignment#
age = 26;Replaces existing value.
Naming#
Prefer:
studentName
coursePrice
completedLessonsAvoid:
x
$student
Student_Nameunless a specific technical reason exists.
Local Variable#
void calculate() {
int total = 10;
}- local scope
- temporary work
- must be assigned before use
- no automatic local default initialization
Instance Variable#
class Student {
String name;
}- belongs to object
- separate value for each object
- field receives default initialization
Static Variable#
class Student {
static String platformName;
}- belongs to class
- shared class-level value
- commonly called class variable
Core Mental Model#
Where should the value live?
│
├── Temporary method/block work
│ ↓
│ Local
│
├── Different for each object
│ ↓
│ Instance
│
└── Shared at class level
↓
StaticYou Should Now Be Able To#
आता तुम्ही independently:
- variable define करू शकता
- declaration आणि initialization वेगळे सांगू शकता
- assignment आणि reassignment identify करू शकता
- valid आणि invalid variable names ओळखू शकता
- lowerCamelCase naming वापरू शकता
- local variable code मध्ये शोधू शकता
- uninitialized local variable problem diagnose करू शकता
- instance variable identify करू शकता
- static variable identify करू शकता
- instance आणि static ownership explain करू शकता
- requirement पाहून Local vs Instance vs Static निवडू शकता
- beginner interview questions confidently answer करू शकता
Final Challenge#
Requirement#
एका learning platform साठी StudentCourse class तयार करायची आहे.
Requirements:
- प्रत्येक student चे नाव वेगळे असेल.
- प्रत्येक student ने complete केलेल्या lessons ची संख्या वेगळी असेल.
- platform चे नाव सर्व students साठी common असेल.
showProgress()method मध्ये remaining lessons calculate करायचे आहेत.- total lessons
20assume करा. - meaningful variable names वापरा.
- local, instance आणि static variables योग्य ठिकाणी वापरा.
Attempt करण्यापूर्वी solution पाहू नका.
Hint 1#
Student-specific values:
Instance variablesHint 2#
Shared platform value:
Static variableHint 3#
Temporary calculation:
Local variableSolution#
Java
public class StudentCourse {
String studentName;
int completedLessons;
static String platformName = "CodeLangs AI";
void showProgress() {
int totalLessons = 20;
int remainingLessons = totalLessons - completedLessons;
System.out.println("Student: " + studentName);
System.out.println("Completed Lessons: " + completedLessons);
System.out.println("Remaining Lessons: " + remainingLessons);
System.out.println("Platform: " + platformName);
}
public static void main(String[] args) {
StudentCourse student1 = new StudentCourse();
StudentCourse student2 = new StudentCourse();
student1.studentName = "Rahul";
student1.completedLessons = 12;
student2.studentName = "Sneha";
student2.completedLessons = 16;
student1.showProgress();
student2.showProgress();
}
}Text
Student: Rahul
Completed Lessons: 12
Remaining Lessons: 8
Platform: CodeLangs AI
Student: Sneha
Completed Lessons: 16
Remaining Lessons: 4
Platform: CodeLangs AIClassification:
studentName → Instance Variable
completedLessons → Instance Variable
platformName → Static Variable
totalLessons → Local Variable
remainingLessons → Local Variable
student1 → Local Variable
student2 → Local Variable