Java Variables
- A variable is a container used to store data values in Java.
- Every variable has a data type, name, and value.
- Variables allow programs to store and manipulate information.
- Java requires variables to be declared before use.
What is a Variable in Java?
A variable in Java is a named memory location used to store data. The value stored inside a variable can be changed during program execution.
For example, a variable can store numbers, text, characters, or true/false values.
Java Variable Syntax
javac Main.java
java Main
Example of Java Variable
class Main {
public static void main(String[] args) {
int age = 20;
System.out.println(age);
}
}
Types of Variables in Java
Local Variable
A variable declared inside a method or block is called a local variable.
Instance Variable
A variable declared inside a class but outside methods is called an instance variable.
Static Variable
A variable declared with the static keyword is called a static variable.
Declaring and Initializing Variables
In Java, creating a variable is called declaration. Assigning a value to a variable is called initialization.
int number;
number = 50;
Java Variable Naming Rules
- Variable names cannot start with numbers.
- Spaces are not allowed in variable names.
- Java variable names are case-sensitive.
- Use meaningful names for better readability.
Java Variables and Data Types
Every Java variable must have a data type that defines what kind of value it can store.
int number = 10;
String name = "Java";
boolean status = true;
Key Points to Remember
- Variables store data values in Java.
- Every variable requires a data type.
- Values stored in variables can change.
- Java supports local, instance, and static variables.