DEV Community

Cover image for Java Variables Explained — Simply and in Detail
DHANRAJ S
DHANRAJ S

Posted on

Java Variables Explained — Simply and in Detail

Hey!

Let me start with a simple question.

When you go to the grocery store — you pick up items and put them in a basket. The basket holds everything until you reach the billing counter.

Now imagine your program needs to remember something. A user's name. A price. A score. A status.

Where does it hold that information while the program is running?

In a variable.

A variable is your program's basket. It picks up a value and holds it until you need it.

Let us understand everything about variables in Java — from the basics to the details most beginners miss.


1. What Is a Variable?

A variable is a container that stores a value in memory.

Every variable has three things.

  • A type — what kind of data it holds
  • A name — how you refer to it
  • A value — what is actually stored in it
int age = 25;
Enter fullscreen mode Exit fullscreen mode

int — the type. This variable holds a whole number.
age — the name. This is how you use it in your code.
25 — the value. What is stored inside.

Simple. But there is a lot more to understand about how variables work in Java.


2. How to Declare a Variable

Declaring a variable means telling Java — "I need a container of this type with this name."

int age;
Enter fullscreen mode Exit fullscreen mode

That is a declaration. You told Java to create a container called age that holds integers. But you have not put anything in it yet.

Initializing means giving it a value.

age = 25;
Enter fullscreen mode Exit fullscreen mode

You can also declare and initialize in one line.

int age = 25;
Enter fullscreen mode Exit fullscreen mode

Most of the time — you do both in one line. Cleaner and easier to read.


3. Rules for Naming Variables

Quick question for you.

Can you name a variable 1score? Or my score? Or class?

Let us go through the rules.

Must start with a letter, underscore, or dollar sign

int age = 25;       // valid
int _count = 10;    // valid
int $price = 99;    // valid
int 1score = 5;     // invalid — cannot start with a number
Enter fullscreen mode Exit fullscreen mode

Cannot have spaces

int myScore = 100;   // valid
int my score = 100;  // invalid — space is not allowed
Enter fullscreen mode Exit fullscreen mode

Cannot use Java reserved words

Some words are reserved by Java — int, class, while, if, for, return and more. You cannot use them as variable names.

int class = 5;    // invalid  class is a reserved word
int myClass = 5;  // valid
Enter fullscreen mode Exit fullscreen mode

Case sensitive

int age = 25;
int Age = 30;
int AGE = 35;
Enter fullscreen mode Exit fullscreen mode

These are three completely different variables. Java sees age, Age, and AGE as different names.


4. Naming Conventions — How Java Developers Write Variable Names

Rules are what Java enforces. Conventions are what developers follow to keep code clean and readable.

Java follows camelCase for variable names.

Start with a lowercase letter. Every new word starts with an uppercase.

int totalPrice = 500;
String firstName = "Ravi";
boolean isLoggedIn = true;
double bankBalance = 15000.75;
Enter fullscreen mode Exit fullscreen mode

Not like this:

int TotalPrice = 500;      // looks like a class name
int total_price = 500;     // works but not Java convention
int totalprice = 500;      // hard to read
Enter fullscreen mode Exit fullscreen mode

camelCase makes your code easier to read. And it matches what every Java developer expects to see.


5. Types of Variables in Java

This is the part most tutorials rush through. But it is very important.

In Java — there are three types of variables based on where they are declared.

  • Local Variables
  • Instance Variables
  • Static Variables

Let us understand each one clearly.


6. Local Variables

A local variable is declared inside a method. It only exists inside that method. Once the method is done — the variable is gone.

public class Example {
    public static void main(String[] args) {
        int score = 95;  // local variable
        System.out.println("Score: " + score);
    }
}
Enter fullscreen mode Exit fullscreen mode

score is a local variable. It lives only inside main. You cannot access it anywhere else.

One important rule — local variables must be initialized before use.

public class Example {
    public static void main(String[] args) {
        int score;
        System.out.println(score);  // Error — score is not initialized
    }
}
Enter fullscreen mode Exit fullscreen mode

Java will give you a compile error. Unlike instance variables — local variables do not get a default value. You must give them a value before using them.

Quick question for you.

What do you think happens if you try to use a local variable outside the method it was declared in?

public class Example {
    public static void main(String[] args) {
        int score = 95;
    }

    public static void show() {
        System.out.println(score);  // Error — score not visible here
    }
}
Enter fullscreen mode Exit fullscreen mode

Compile error. score does not exist outside main. Local variables are strictly limited to the block they are declared in.


7. Instance Variables

An instance variable is declared inside a class — but outside any method. Every object created from that class gets its own copy.

public class Student {
    String name;      // instance variable
    int age;          // instance variable
    double marks;     // instance variable

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Ravi";
        s1.age = 20;
        s1.marks = 89.5;

        Student s2 = new Student();
        s2.name = "Anu";
        s2.age = 22;
        s2.marks = 94.0;

        System.out.println(s1.name + " - " + s1.marks);  // Ravi - 89.5
        System.out.println(s2.name + " - " + s2.marks);  // Anu - 94.0
    }
}
Enter fullscreen mode Exit fullscreen mode

s1 and s2 are two different objects. Each has their own name, age, and marks. Changing s1.name does not affect s2.name.

Instance variables get default values if you do not initialize them.

Type Default Value
int 0
double 0.0
boolean false
char '\u0000' (empty)
String / Object null

Quick question for you.

What will this print?

public class Example {
    int count;

    public static void main(String[] args) {
        Example e = new Example();
        System.out.println(e.count);
    }
}
Enter fullscreen mode Exit fullscreen mode

It prints 0. Because count is an instance variable. It was not initialized. So Java gave it the default value for int which is 0.


8. Static Variables

A static variable is declared with the static keyword inside a class. There is only one copy of it — shared across all objects.

public class Student {
    static String schoolName = "ABC School";  // static variable
    String name;                              // instance variable

    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Ravi";

        Student s2 = new Student();
        s2.name = "Anu";

        System.out.println(s1.name + " studies at " + Student.schoolName);
        System.out.println(s2.name + " studies at " + Student.schoolName);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Ravi studies at ABC School
Anu studies at ABC School
Enter fullscreen mode Exit fullscreen mode

schoolName is the same for every student. It belongs to the class — not to any individual object. That is what static means.

If you change Student.schoolName = "XYZ School" — it changes for every object at once. Because there is only one copy.


9. The final Keyword — Constants

Sometimes you want a variable whose value never changes. A constant.

Use the final keyword.

final double PI = 3.14159265;
final int MAX_SCORE = 100;
final String APP_NAME = "MyApp";
Enter fullscreen mode Exit fullscreen mode

Once assigned — you cannot change it.

final int MAX_SCORE = 100;
MAX_SCORE = 200;  // Error — cannot reassign a final variable
Enter fullscreen mode Exit fullscreen mode

Java convention for constants — write them in ALL_CAPS with underscores between words.

MAX_SCORE. PI. APP_NAME. MAX_RETRY_COUNT.

Every developer who reads your code will immediately know — this value never changes.


10. var — Type Inference (Java 10+)

From Java 10 onwards — you can use var instead of writing the type. Java figures out the type from the value you assign.

var age = 25;           // Java knows this is int
var name = "Ravi";      // Java knows this is String
var price = 99.99;      // Java knows this is double
var isActive = true;    // Java knows this is boolean
Enter fullscreen mode Exit fullscreen mode

This is called type inference. Java looks at the value on the right and decides the type.

But var only works for local variables. Not for instance variables or method parameters.

public class Example {
    var name = "Ravi";  // Error — var not allowed here

    public static void main(String[] args) {
        var score = 95;  // works fine here
    }
}
Enter fullscreen mode Exit fullscreen mode

Quick question for you.

Can you use var without assigning a value immediately?

var score;        // Error
var score = 95;   // Correct
Enter fullscreen mode Exit fullscreen mode

No. Because Java needs to see the value to figure out the type. Without a value — var does not know what type to use.


11. Scope of a Variable

Scope means — where in your code is this variable accessible?

Block scope

A variable declared inside {} only exists inside those curly braces.

public class Example {
    public static void main(String[] args) {
        int x = 10;

        if (x > 5) {
            int y = 20;  // y only exists inside this if block
            System.out.println(y);  // works fine
        }

        System.out.println(y);  // Error — y does not exist here
    }
}
Enter fullscreen mode Exit fullscreen mode

y was declared inside the if block. Once the if block ends — y is gone.

Method scope

A local variable exists only within the method it was declared in.

Class scope

Instance and static variables exist as long as the object or class exists.


12. Putting It All Together — One Full Example

public class BankAccount {

    static String bankName = "Java Bank";   // static — same for all accounts
    String accountHolder;                    // instance — different per account
    double balance;                          // instance — different per account
    final double MIN_BALANCE = 500.0;        // constant — never changes

    public void deposit(double amount) {
        double newBalance = balance + amount;  // local — only inside this method
        balance = newBalance;
        System.out.println("Deposited: " + amount + " | Balance: " + balance);
    }

    public void withdraw(double amount) {
        double remaining = balance - amount;   // local — only inside this method
        if (remaining >= MIN_BALANCE) {
            balance = remaining;
            System.out.println("Withdrawn: " + amount + " | Balance: " + balance);
        } else {
            System.out.println("Cannot withdraw. Minimum balance must be " + MIN_BALANCE);
        }
    }

    public static void main(String[] args) {
        BankAccount acc1 = new BankAccount();
        acc1.accountHolder = "Ravi";
        acc1.balance = 5000.0;

        System.out.println("Bank: " + BankAccount.bankName);
        System.out.println("Account holder: " + acc1.accountHolder);

        acc1.deposit(1000);
        acc1.withdraw(3000);
        acc1.withdraw(2000);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Bank: Java Bank
Account holder: Ravi
Deposited: 1000.0 | Balance: 6000.0
Withdrawn: 3000.0 | Balance: 3000.0
Cannot withdraw. Minimum balance must be 500.0
Enter fullscreen mode Exit fullscreen mode

This one example uses all four types — static, instance, local, and final — in a real context.

Read through it. Trace each variable. Notice where each one lives and how long it exists.


Quick Summary — 6 Things to Remember

  1. A variable needs a type, a name, and a value — declare it, initialize it, use it.

  2. Local variables — live inside a method. Must be initialized before use. Disappear when the method ends.

  3. Instance variables — live inside a class. Each object gets its own copy. Get default values automatically.

  4. Static variables — shared across all objects. One copy for the whole class. Access with the class name.

  5. final variables — constants. Value never changes. Write them in ALL_CAPS.

  6. var — lets Java figure out the type for local variables. Only works when you assign a value immediately.


Variables are the most basic building block of any Java program. You cannot write a single useful line without them.

The three types — local, instance, and static — seem similar at first. But once you understand scope and lifetime, each one has a clear and logical purpose.

Try writing the BankAccount program yourself. Add a new method. Add a new instance variable. Change the minimum balance constant and see it reflect everywhere.

That hands-on practice is what turns reading into understanding.

If you have a question — drop it in the comments below.


Thanks for reading. Keep building.

Top comments (0)