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";You can declare variables and optionally initialize them at the same time.
int x;
x = 5;
int y = 10;Java has several built-in types for storing different kinds of data:
int – whole numbersdouble – decimalschar – single charactersboolean – true or falseString – sequences of charactersint age = 30;
double pi = 3.14;
char grade = 'A';
boolean isJavaFun = true;
String city = "Toronto";_, or $score ≠ Score)// Valid
String firstName = "John";
int _count = 10;
// Invalid
int 1score = 90;
String class = "History";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);
}
}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 errorAsk the AI if you need help understanding or want to dive deeper in any topic