On this page, we will learn about Java variables, What is a Java variable? What is a local variable? What is an instance variable? What is a static variable? Local Variable Example, Instance Variable Example, and Static Variable Example.
A Variable is a container which clasp the value while the Java program is executed. A variable is allocated with a data type. Variable is a name of a memory location. There are three types of variables in java, these are:
Variable is name of reserved space allotted in memory. In alternative words, it’s a reputation of memory location. It’s a mix of “vary + able” meaning its worth can be modified.
import java.io.*;
Class Simple{
Public static void main(String args[]){
int x = 20; // x is a variable
}
}
A variable declared within the body of the strategy is named native variable. You’ll use this variable solely at intervals that technique and also the different strategies within the category are not even aware that the variable exists.
import java.io.*;
public class A {
public void TeacherAge(){
// local variable age
int age = 25;
System.out.println("a = " + age);
}
public static void main(String args[]){
Teacher obj = new TeacherAge();
obj.TeacherAge();
}
}
a = 25
A variable declared within the category however outside the body of the tactic, is named instance variable. It’s not declared as static.
It is referred to as instance variable as a result of its worth is instance specific and isn’t shared among instances.
import java.io.*;
class Marks {
int banMarks;
}
class MarksDemo {
public static void main(String args[]){
// first object
Marks obj1 = new Marks();
obj1.engMarks = 50;
System.out.println("Marks = " + obj1.banMarks);
}
}
Marks = 50
A variable which is declared as static is termed static variable. It cannot be native. You can produce a single copy of static variable and share among all the instances of the category . Memory allocation for static variable happens just once when the category is loaded in the memory.
To access static variables, you don't need to create an object of that class, you can simply access the variable as class_name.variable_name;
.
import java.io.*;
class Emp {
public static double salary;
public static String name = "Tuhin";
}
public class EmpDemo {
public static void main(String args[]){
Emp.salary = 1000;
System.out.println(Emp.name);
System.out.println(Emp.salary);
}
}
Tuhin
1000