Information can be stored in variables, which the programmer can then change and refer to later in the code. The data type of a Java variable can provide information about the size and organisation of the variable’s memory.
Syntax:
datatype variable = value
There are three types of variables in java:
- Local variable
- Instance variable
- Class/Static variable
- Local Variables:
A variable declared within the body of a method or constructor is referred to as a local variable. This is because the scope of a local variable is limited to the method or constructor in which it is defined, and it cannot be accessed by other methods in the class.To declare a local variable within the method body, the “static” keyword is used.
For example:
public class variableType {
public void localVariable() {
String name = "Ben";
int marks = 95;
System.out.println(name + " Scored " + marks + "%.");
}
public static void main(String[] args) {
variableType vt = new variableType();
vt.localVariable();
}
}
Output:
Ben Scored 95%.
If an attempt is made to access a local variable outside the method or constructor in which it was created, it will result in an error.
For example:
public class variableType {
public void localVariable() {
String name = "Ben";
int marks = 95;
}
public void notLocalVariable() {
System.out.println(name + " Scored " + marks + "%.");
}
public static void main(String[] args) {
variableType vt = new variableType();
vt.notLocalVariable();
}
}
Output:
name cannot be resolved to a variable
marks cannot be resolved to a variable