Java Variables

What Is a Variable?

A variable stores data in memory.

In Java, you must declare a variable with a data type. This allows Java to catch errors during compilation.

int age = 25;
String name = "Alice";

Declaring and Initializing Variables

You can declare variables and optionally initialize them at the same time.

int x;
x = 5;
int y = 10;

Java Data Types

Java has several built-in types for storing different kinds of data:

  • int – whole numbers
  • double – decimals
  • char – single characters
  • boolean – true or false
  • String – sequences of characters
int age = 30;
double pi = 3.14;
char grade = 'A';
boolean isJavaFun = true;
String city = "Toronto";

Variable Naming Rules

  • Start with a letter, _, or $
  • Cannot begin with a number
  • Cannot use reserved Java keywords
  • Case-sensitive (e.g., scoreScore)
// Valid
String firstName = "John";
int _count = 10;

// Invalid
int 1score = 90;
String class = "History";

Scope and Lifetime

A variable declared inside a method is only accessible in that method. Fields (variables at class level) live as long as the object exists.

public class Dog {
    String name;  // instance variable

    public void bark() {
        int volume = 5;  // local variable
        System.out.println(name + " barks at volume " + volume);
    }
}

Constants with final

Use final to create constants that cannot be changed after being initialized.

final double PI = 3.14159;
// PI = 3.0; // This will cause a compile-time error

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic