CodeLangs AISoftware Training Institute
Java for Beginners (Marathi)/Variables in Java
Dashboard
Chapter 5 · Java for Beginners

Variables in Java

3,539
words
17
min read
40
practice items
Interactive learning

Practice lab

Question 1 of 20 00:00

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

उदाहरण:

TEXT
Name = Rahul
Age = 22
Score = 85

Program ला ही 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

JAVA
int age = 22;

यामध्ये:

TEXT
int    → variable चा type
age    → variable चे name
22     → variable मध्ये ठेवलेली value

Conceptually:

TEXT
Variable Name
     ↓
   age
┌───────────────┐
│      22       │
└───────────────┘

आपण नंतर age हे नाव वापरून त्यामधील value access करू शकतो.

Java

JAVA
public class StudentProfile {

    public static void main(String[] args) {

        int age = 22;

        System.out.println(age);
    }
}

Text

TEXT
22

Variable का आवश्यक आहे?#

Consider:

Java

JAVA
System.out.println(500);
System.out.println(500 * 12);
System.out.println(500 * 24);

इथे 500 ही value repeated आहे.

त्याऐवजी:

Java

JAVA
int monthlyFee = 500;

System.out.println(monthlyFee);
System.out.println(monthlyFee * 12);
System.out.println(monthlyFee * 24);

आता fee बदलायची असेल तर एका ठिकाणी बदल करता येतो.

JAVA
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:

TEXT
12

पण code मध्ये फक्त 12 पाहिल्यावर त्याचा अर्थ कळत नाही.

JAVA
int completedLessons = 12;

आता value चा business meaning स्पष्ट झाला.

Important Principle#

Variable फक्त value ठेवत नाही.

Good variable name त्या value चा meaning देखील communicate करते.

Weak:

JAVA
int x = 12;

Better:

JAVA
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:

TEXT
type variableName;

Example:

Java

JAVA
int age;

इथे:

TEXT
int  → type
age  → variable identifier/name
;    → statement terminator

आता आपण variable declare केला आहे.

पण local variable असल्यास अजून त्याला usable value दिलेली नाही.


Declaration examples#

Java

JAVA
int age;
String studentName;
double coursePrice;
boolean courseCompleted;

या chapter मध्ये types चे detailed explanation करणार नाही. ते पुढच्या Java Data Types chapter मध्ये येईल.

आत्ता फक्त pattern समजा:

TEXT
Type + Variable Name

Declaration vs Value#

हे दोन वेगळे concepts आहेत.

JAVA
int age;

याचा अर्थ:

age नावाचा variable declare केला.

हे:

JAVA
age = 25;

याचा अर्थ:

age ला value assign केली.

आणि हे:

JAVA
int age = 25;

यामध्ये declaration आणि initial value दोन्ही एकाच statement मध्ये आहेत.


Multiple variables एका statement मध्ये declare करता येतात का?#

हो.

हे legal आहे:

Java

JAVA
int age, score, attempts;

पण beginner आणि production readability साठी सामान्यतः हे जास्त स्पष्ट आहे:

Java

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

JAVA
int age = 22;

इथे:

TEXT
Declaration
    ↓
int age

Initialization
     ↓
   = 22

Declaration आणि Initialization एकत्र#

Production code मध्ये हा pattern खूप common आहे:

Java

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

JAVA
int score;

score = 90;

System.out.println(score);

इथे:

TEXT
int score;   → declaration

score = 90;  → assignment

score = 90 ही declaration मधील initializer नाही; ती नंतरची assignment आहे.


Assignment म्हणजे काय?#

Definition#

Assignment stores a value into an already declared variable.

मराठीत:

Already declared variable मध्ये value ठेवण्याच्या operation ला assignment म्हणतो.

Example:

Java

JAVA
int score;

score = 80;

Reassignment#

जर variable change करण्याची परवानगी असेल तर त्याला नवीन value पुन्हा assign करता येते.

Java

JAVA
int completedLessons = 5;

completedLessons = 6;
completedLessons = 7;

System.out.println(completedLessons);

Text

TEXT
7

Flow:

TEXT
completedLessons
       ↓
       5
       ↓
       6
       ↓
       7

Current value 7 आहे.


Declaration, Initialization, Assignment, Reassignment#

OperationExampleMeaning
Declarationint score;variable introduce केला
Declaration + Initializationint score = 80;variable declare करून initial value दिली
Assignmentscore = 80;declared variable मध्ये value ठेवली
Reassignmentscore = 90;existing value नवीन value ने बदलली

हा distinction interview मध्येही महत्त्वाचा आहे.


Local variable बद्दल एक critical rule#

हे code पाहा:

Java

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

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 ला ओळखण्यासाठी वापरलेले नाव.

उदाहरण:

JAVA
int studentAge = 22;

studentAge हा identifier आहे.


Rule 1 — Variable name digit ने start करू शकत नाही#

Valid:

JAVA
int age2;
int student2;

Invalid:

JAVA
int 2age;

कारण first character valid Java identifier-start character असला पाहिजे. Digits नंतर वापरता येतात.


Rule 2 — Spaces allowed नाहीत#

Invalid:

JAVA
int student age;

Java याला एक variable name म्हणून treat करणार नाही.

Correct:

JAVA
int studentAge;

Rule 3 — Reserved keyword variable name म्हणून वापरता येत नाही#

Invalid:

JAVA
int class;

Invalid:

JAVA
int static;

Invalid:

JAVA
int public;

कारण class, static, public हे reserved keywords आहेत.


Rule 4 — Variable names case-sensitive आहेत#

हे तीन वेगवेगळे identifiers आहेत:

Java

JAVA
int age = 20;
int Age = 30;
int AGE = 40;

Java साठी:

TEXT
age ≠ Age ≠ AGE

हे technically valid असले तरी असे confusing naming करू नये.


Rule 5 — _ single-character variable name म्हणून वापरता येत नाही#

Modern Java मध्ये हे invalid आहे:

JAVA
int _ = 10;

_ single character आता reserved keyword आहे.

पण multi-character identifier मध्ये underscore येऊ शकतो:

JAVA
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 असू शकते:

JAVA
int $total = 100;

पण professional application code मध्ये असे names वापरणे avoid करा.

Java specification $ identifier मध्ये permit करते, पण सामान्य source code मध्ये त्याचा वापर recommended नाही.

Better:

JAVA
int total = 100;

Rule 7 — Meaningful names वापरा#

Weak:

JAVA
int x = 25;

Better:

JAVA
int studentAge = 25;

Weak:

JAVA
int n = 10;

Better:

JAVA
int totalLessons = 10;

Variable नाव पाहिल्यावर त्यामध्ये काय value आहे याचा purpose अंदाज येणे आवश्यक आहे.


Naming Convention — lowerCamelCase#

Java variables साठी widely used convention:

TEXT
first word lowercase
next words start with uppercase letter

Examples:

JAVA
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 करतात.

उदाहरण:

JAVA
int $Student_Age = 25;

काही contexts मध्ये technically valid असले तरी हा good professional variable name नाही.

Better:

JAVA
int studentAge = 25;

Variable Naming Checklist#

Variable name लिहिताना स्वतःला विचारा:

  1. नाव valid identifier आहे का?
  2. digit ने start होत नाही ना?
  3. keyword नाही ना?
  4. spaces नाहीत ना?
  5. purpose स्पष्ट आहे का?
  6. lowerCamelCase वापरले आहे का?
  7. unnecessary $ किंवा _ नाहीत ना?
  8. नाव 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

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:

TEXT
main() method starts
       ↓
local variable created
       ↓
variable used
       ↓
method/block finishes
       ↓
local variable no longer usable there

Beginner level वर इतके लक्षात ठेवा:

Local variable त्या method किंवा block च्या local work साठी असतो.

Practical example#

समजा method चा purpose discount calculate करणे आहे.

Java

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

TEXT
1500

इथे:

TEXT
coursePrice
discount
finalPrice

हे सर्व main method मधील local variables आहेत.


Local variable ला default value मिळत नाही#

हा अत्यंत महत्त्वाचा rule आहे.

Wrong:

Java

JAVA
public class ScoreExample {

    public static void main(String[] args) {

        int score;

        System.out.println(score);
    }
}

score वापरण्यापूर्वी value दिलेली नाही.

Correct:

Java

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

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:

JAVA
{
    ...
}

त्या block बाहेर bonus वापरण्याचा प्रयत्न केला तर compile-time problem येईल.

Wrong:

JAVA
{
    int bonus = 10;
}

System.out.println(bonus);

Mental Model#

TEXT
main method
│
├── score
│
├── inner block
│      └── bonus
│
└── score still accessible

bonus चा scope inner block पर्यंत आहे.


Local variable कधी वापरायचा?#

जेव्हा value फक्त एखाद्या temporary calculation किंवा method-level operation साठी आवश्यक आहे.

Examples:

JAVA
int total;
double finalPrice;
boolean eligible;
String message;

Use case:

TEXT
Requirement:
Course price वर discount calculate करायचा.

Temporary values:
coursePrice
discount
finalPrice

Best fit:
Local variables

कारण त्यांची गरज त्या calculation पुरतीच आहे.


6. Instance Variables#

आता समजा application मध्ये अनेक students आहेत.

Student 1:

TEXT
Name = Rahul
Completed Lessons = 12

Student 2:

TEXT
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.

उदाहरण:

TEXT
Class
Student

Objects
Rahul Student
Sneha Student
Amit Student

Objects detail मध्ये पुढील appropriate chapter मध्ये शिकू.


Instance variable example#

Java

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

TEXT
Rahul
12
Sneha
7

name आणि completedLessons instance variables आहेत.


दोन objects मध्ये separate copies#

Conceptually:

TEXT
Student class
     │
     ├───────────────┐
     │               │
student1          student2
     │               │
     ├─ name          ├─ name
     │  Rahul         │  Sneha
     │               │
     └─ lessons       └─ lessons
        12               7

जेव्हा आपण:

JAVA
student1.completedLessons = 20;

करतो, तेव्हा student2.completedLessons automatically बदलत नाही.

कारण दोन्ही objects कडे independent instance variables आहेत.


Instance variables object state represent करतात#

Real application मध्ये:

JAVA
class Student {

    String name;
    String email;
    int completedLessons;
}

प्रत्येक Student object ला वेगळे:

TEXT
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

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 मध्ये:

TEXT
completedLessons → 0
active           → false
name             → null

Detailed 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 चे:

TEXT
name
completedLessons

वेगळे आहेत.

पण सर्व students साठी training platform एकच आहे:

TEXT
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

JAVA
static String platformName = "CodeLangs AI";

Structure:

TEXT
static
   ↓
static String platformName = "CodeLangs AI";
       └──────────────────────────────────┘
                   field

Example#

Java

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

TEXT
Rahul
Sneha
CodeLangs AI

Instance data:

TEXT
student1.name → Rahul
student2.name → Sneha

Shared class data:

TEXT
Student.platformName → CodeLangs AI

Static variable class name ने access करणे#

Beginner code मध्ये static variable class name वापरून access करणे अधिक clear असते:

JAVA
Student.platformName

यामुळे reader ला लगेच कळते:

ही value specific object ची नसून class-level आहे.

Instance vs Static#

TEXT
Student class
│
├── static platformName
│      └── "CodeLangs AI"
│
├── student1
│      └── name = "Rahul"
│
└── student2
       └── name = "Sneha"

Notice:

TEXT
name

प्रत्येक object साठी वेगळा आहे.

पण:

TEXT
platformName

shared आहे.


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#

FeatureLocal VariableInstance VariableStatic Variable
Usually declaredmethod/block मध्येclass मध्ये, method बाहेरclass मध्ये static सह
Belongs tolocal executioneach objectclass
Separate per objectNot applicableYesNo
Shared across objectsNoNoYes
Automatic field default valueNoYesYes
Typical purposetemporary workobject stateclass-wide shared data

One Connected Example#

आता तिन्ही concepts एका realistic example मध्ये पाहू.

Java

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

TEXT
Rahul
12
8
CodeLangs AI

Classification:

TEXT
studentName       → instance variable
completedLessons  → instance variable
platformName      → static variable
remainingLessons  → local variable
enrollment        → local variable

Reasoning:

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 विचार आहे:

TEXT
Value कोणाशी संबंधित आहे?
        ↓
Temporary calculation?
        → Local

Specific object?
        → Instance

Whole class/shared?
        → Static

Practical / Real-World Application#

Scenario — Online Course Application#

Requirement:

आपल्याला course enrollment model करायचे आहे.

प्रत्येक student साठी:

TEXT
student name
course name
completed lessons

वेगळे आहेत.

पण company/platform name सर्वांसाठी common आहे.

Progress display करताना:

TEXT
remaining lessons

temporary calculate करायचे आहेत.

Analysis:

DataBest Variable KindReason
studentNameInstanceप्रत्येक student वेगळा
courseNameInstanceenrollment-specific
completedLessonsInstanceप्रत्येक learner ची progress वेगळी
platformNameStaticसर्व objects मध्ये common
remainingLessonsLocaltemporary calculation

Implementation:

Java

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

TEXT
Student: Sneha
Course: Java Beginner Course
Completed: 14
Remaining: 6
Platform: CodeLangs AI

या example मध्ये variable निवड arbitrary नाही.

ती requirement वर आधारित आहे.


Requirement → Variable Decision#

Professional development मध्ये असा विचार करा:

TEXT
Requirement
    ↓
Value कोण represent करते?
    ↓
Value किती काळ लागेल?
    ↓
ती object-specific आहे का?
    ↓
ती सर्व objects मध्ये common आहे का?
    ↓
योग्य variable location निवडा

हे reasoning coding पेक्षा जास्त महत्त्वाचे आहे.


Common Mistakes & Misconceptions#

Mistake 1 — Declaration म्हणजे initialization असे समजणे#

JAVA
int score;

हे initialization नाही.

हे declaration आहे.

Initialization:

JAVA
int score = 80;

Mistake 2 — Local variable automatically 0 होईल असे समजणे#

Wrong assumption:

JAVA
int score;

System.out.println(score);
"int आहे म्हणून 0 मिळेल."

Local variables साठी हे चुकीचे आहे.

Local variable वापरण्यापूर्वी assigned असणे आवश्यक आहे.


Mistake 3 — Instance variable आणि local variable एकच समजणे#

Compare:

JAVA
class Student {

    int score;

    void calculate() {
        int bonus = 10;
    }
}

score:

TEXT
instance variable

bonus:

TEXT
local variable

Location आणि ownership वेगळे आहेत.


Mistake 4 — प्रत्येक variable static करणे#

Beginner अनेकदा compiler errors avoid करण्यासाठी:

JAVA
static int score;
static String name;
static int age;

असे करतो.

हे चुकीचे design होऊ शकते.

प्रश्न विचारा:

ही value सर्व objects मध्ये खरंच shared आहे का?

जर नाही:

TEXT
static वापरू नका.

Mistake 5 — Static variable प्रत्येक object साठी वेगळी समजणे#

जर:

JAVA
static String platformName;

असेल तर ती class-level shared variable आहे.

प्रत्येक object ची independent copy नाही.


Mistake 6 — Instance variable सर्व objects मध्ये shared आहे असे समजणे#

JAVA
String studentName;

जर non-static field असेल तर:

TEXT
student1.studentName
student2.studentName

वेगवेगळ्या values ठेवू शकतात.


Mistake 7 — Variable name digit ने सुरू करणे#

Invalid:

JAVA
int 1score;

Correct:

JAVA
int score1;

Mistake 8 — Keyword variable name म्हणून वापरणे#

Invalid:

JAVA
int static;

Correct:

JAVA
int staticCount;

Mistake 9 — Case mismatch#

Declaration:

JAVA
int studentAge = 20;

Wrong usage:

JAVA
System.out.println(studentage);

studentAge आणि studentage वेगवेगळे identifiers आहेत.


Mistake 10 — Meaningless names#

Weak:

JAVA
int a;
int b;
int c;

Better:

JAVA
int coursePrice;
int discountAmount;
int finalPrice;

Mistake 11 — Scope ignore करणे#

Wrong:

JAVA
{
    int score = 80;
}

System.out.println(score);

score त्याच्या valid local scope बाहेर वापरला आहे.


Mistake 12 — "Static म्हणजे faster" असे समजणे#

static keyword चा primary purpose:

TEXT
make value class-associated

हा performance shortcut नाही.

Variable static करायचा निर्णय ownership/design वर based असावा.


Hands-On Practice#

Practice 1 — Identify the Parts#

Code:

Java

JAVA
int completedLessons = 12;

Learner Task#

Identify:

  1. type
  2. variable name
  3. initial value

Hint 1#

Variable declaration pattern आठवा:

TEXT
type variableName = value;

Solution#

TEXT
Type           = int
Variable Name  = completedLessons
Initial Value  = 12

Practice 2 — Fix the Variable Names#

खालील names professional Java naming मध्ये rewrite करा:

TEXT
Student_Name
COURSEprice
x
completed_lessons

Hint#

Use:

TEXT
lowerCamelCase
meaningful names

Solution#

TEXT
studentName
coursePrice
studentCount
completedLessons

x चा exact replacement context वर depend करतो. येथे learner count represent करतो असे assume केल्यामुळे studentCount meaningful आहे.


Practice 3 — Find the Problem#

Java

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

JAVA
public class Test {

    public static void main(String[] args) {

        int total = 0;

        System.out.println(total);
    }
}

Practice 4 — Classify Variables#

Java

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:

TEXT
name
instituteName
completedLessons

Solution#

TEXT
name              → Instance Variable
instituteName     → Static Variable
completedLessons  → Local Variable

Practice 5 — Requirement Analysis#

Requirement:

प्रत्येक employee ची salary वेगळी आहे. Company name सर्व employees साठी common आहे. Monthly salary वरून annual salary temporary calculate करायची आहे.

Choose variable types.

Think Before Viewing Solution#

Questions:

  1. Employee-specific data कोणते?
  2. Shared data कोणते?
  3. Temporary calculation कोणते?

Solution#

TEXT
salary         → Instance Variable
companyName    → Static Variable
annualSalary   → Local Variable

Reason:

TEXT
salary
→ प्रत्येक employee साठी वेगळी

companyName
→ सर्व employee objects साठी common

annualSalary
→ calculation पुरती temporary

Interview 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:

JAVA
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:

JAVA
int age = 25;

Here, 25 is the initial value.


4. What is the difference between declaration and initialization?

Declaration introduces a variable:

JAVA
int score;

Initialization provides its initial value:

JAVA
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:

JAVA
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:

JAVA
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.

JAVA
age
Age
AGE

are 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:

JAVA
int 2score;

Valid:

JAVA
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:

JAVA
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:

JAVA
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:

JAVA
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:

JAVA
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:

JAVA
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:

JAVA
int completedLessons;

is clearer than:

JAVA
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#

TEXT
Named storage location associated with a type.

Example:

JAVA
int age = 25;

Declaration#

JAVA
int age;

Introduces variable name and type.


Initialization#

JAVA
int age = 25;

Provides initial value.


Assignment#

JAVA
age = 25;

Stores a value in an already declared variable.


Reassignment#

JAVA
age = 26;

Replaces existing value.


Naming#

Prefer:

TEXT
studentName
coursePrice
completedLessons

Avoid:

TEXT
x
$student
Student_Name

unless a specific technical reason exists.


Local Variable#

JAVA
void calculate() {
    int total = 10;
}
  • local scope
  • temporary work
  • must be assigned before use
  • no automatic local default initialization

Instance Variable#

JAVA
class Student {
    String name;
}
  • belongs to object
  • separate value for each object
  • field receives default initialization

Static Variable#

JAVA
class Student {
    static String platformName;
}
  • belongs to class
  • shared class-level value
  • commonly called class variable

Core Mental Model#

TEXT
Where should the value live?
        │
        ├── Temporary method/block work
        │       ↓
        │     Local
        │
        ├── Different for each object
        │       ↓
        │    Instance
        │
        └── Shared at class level
                ↓
              Static

You 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:

  1. प्रत्येक student चे नाव वेगळे असेल.
  2. प्रत्येक student ने complete केलेल्या lessons ची संख्या वेगळी असेल.
  3. platform चे नाव सर्व students साठी common असेल.
  4. showProgress() method मध्ये remaining lessons calculate करायचे आहेत.
  5. total lessons 20 assume करा.
  6. meaningful variable names वापरा.
  7. local, instance आणि static variables योग्य ठिकाणी वापरा.

Attempt करण्यापूर्वी solution पाहू नका.

Hint 1#

Student-specific values:

TEXT
Instance variables

Hint 2#

Shared platform value:

TEXT
Static variable

Hint 3#

Temporary calculation:

TEXT
Local variable

Solution#

Java

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

TEXT
Student: Rahul
Completed Lessons: 12
Remaining Lessons: 8
Platform: CodeLangs AI
Student: Sneha
Completed Lessons: 16
Remaining Lessons: 4
Platform: CodeLangs AI

Classification:

TEXT
studentName       → Instance Variable
completedLessons  → Instance Variable
platformName      → Static Variable
totalLessons      → Local Variable
remainingLessons  → Local Variable
student1          → Local Variable
student2          → Local Variable