Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

Java Variables

Types of Variables

Java has three kinds of variables, each with a different scope and lifetime.

TypeDeclared InScopeDefault Value
LocalInside a method or blockWithin that method/block onlyNone (must be initialized)
InstanceInside a class, outside methodsEntire object0 / null / false
StaticInside a class with static keywordEntire class (shared by all objects)0 / null / false
Variable Types
public class VariableTypes {

    // Instance variable — belongs to each object
    String name = "Java";

    // Static variable — shared across all instances
    static int instanceCount = 0;

    public void display() {
        // Local variable — exists only inside this method
        int localVar = 10;
        instanceCount++;
        System.out.println("Name: " + name);
        System.out.println("Local: " + localVar);
        System.out.println("Count: " + instanceCount);
    }

    public static void main(String[] args) {
        VariableTypes obj1 = new VariableTypes();
        VariableTypes obj2 = new VariableTypes();
        obj1.display();
        obj2.display();
        // instanceCount is now 2 — shared by both objects
    }
}

Naming Conventions

Java follows well-established naming conventions to keep code readable and consistent.

  • Variables & methods: camelCase — e.g., firstName, calculateTotal()
  • Classes: PascalCase — e.g., BankAccount, HelloWorld
  • Constants: UPPER_SNAKE_CASE — e.g., MAX_SIZE, PI
  • Packages: all lowercase — e.g., com.example.utils
  • Variable names must start with a letter, $, or _ (not a digit).
  • Reserved keywords (int, class, for, etc.) cannot be used as names.

Constants with final

Use the final keyword to declare a constant. Once assigned, its value cannot be changed.

Constants and var keyword
public class Constants {

    // Class-level constant (static final)
    static final double PI = 3.141592653589793;
    static final int MAX_USERS = 100;

    public static void main(String[] args) {
        // PI = 3.14;  // ERROR: cannot assign a value to a final variable

        // var keyword (Java 10+) — type is inferred by the compiler
        var message = "Hello";      // inferred as String
        var count   = 42;           // inferred as int
        var price   = 9.99;         // inferred as double

        System.out.println("PI = " + PI);
        System.out.println("Max users = " + MAX_USERS);
        System.out.println(message + " " + count + " " + price);

        // var only works for local variables — not for fields or parameters
    }
}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.