Variables need to be declared before they can be used, following is the basic form of variable declaration −
data type variable [ = value][, variable [ = value] ...] ;
Following is an example of variable declaration and initialization in Java −
int a, b, c; //declared vairables int a = 10, b = 10; // assigned values byte B = 22; //
Declare and initialize a variable of type byte: Bdouble pi = 3.14159; //
Declare and assign a variable of type double: PIchar a = 'a'; //
Declare a char type variable a, and initialize the value to: 'a'
This chapter will explain the various variable types in the Java language. There are three kinds of variables in Java −
- local variable
- instance variable
- class/static variable
1. Local variables
- Local variables are generally declared within methods, constructors or blocks.
- Local variables are created when a program enters a method, constructor, or block, and are destroyed once the method, constructor, or block exits.
- Access modifiers cannot be used on local variables.
- Local variables are only visible within the declared method, constructor or block.
- Local variables implement stack levels internally.
- Local variables do not have default values, so after declaring a local variable, assign it an initial value before using it for the first time.
Example
Here, age
is a local variable. This is dogAge()
defined in a method and its scope is limited to this method.
public class Test {
public void dogAge() {
int age = 0;
age = age + 5;
System.out.println("Dog age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.dogAge();
}
}
Execute the above sample code and get the following results:
Dog age is : 5
Example
The following example uses a variable age
, but does not initialize it, so an error occurs at compile time.
public class Test {
public void dogAge() {
int age;
age = age + 5;
System.out.println("Dog age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.dogAge();
}
}
Execute the above sample code and get the following result (error):
Test.java:4:variable number might not have been initialized
age = age + 5;
^
1 error
2. Instance variables
- Instance variables are declared within a class, but outside a method, constructor, or block.
- When space is allocated for an object in the heap, a slot is created for each instance variable value.
new
Instance variables are created when an object is created using keywords and are destroyed when the object is destroyed.- Instance variables contain values referenced by multiple methods, constructors, or blocks, or essential parts of an object's state that exist throughout the class.
- Instance variables can be declared at the class level before or after use.
- Access modifiers can be given for instance variables.
- Instance variables are visible to all methods, constructors and blocks in the class. In general, it is recommended to make these variables private (access level). However, access modifiers can be used to provide subclass visibility to these variables.
- Instance variables have default values. The default is for numbers, it is
0
for booleans, and it isfalse
for object referencesnull
. Values can be specified during declaration or in the constructor. - Instance variables can be accessed directly by calling the variable name in the class. However, in static methods (when instance variables have accessibility), they should be called using fully qualified names like:
ObjectReference.VariableName
import java.io.*; public class Employee { // This instance variable is visible to subclasses. public String name; // The salary variable is only visible in the Employee class. private double salary; // The name variable is specified in the constructor. public Employee (String empName) { name = empName; } // assign a value to the salary variable public void setSalary(double empSal) { salary = empSal; } // This method prints the employee details. public void printEmp() { System.out.println("name : " + name ); System.out.println("salary :" + salary); } public static void main(String args[]) { Employee empOne = new Employee("Maxsu"); empOne. setSalary(15999); empOne. printEmp(); } }
Output:
name : Maxsu
salary :15999.0
3. Classes/static variables
- Class variables (also known as static variables) are
static
declared using the keyword within a class, but outside a method, constructor, or block. - There is only one copy of each class variable per class, no matter how many objects are created from it.
- Static variables are rarely used except when declared as constants. Constants are variables declared as
public/private
,final
and .static
The initial value of a constant cannot be changed. - Static variables are stored in static memory. Static variables are rarely used other than declared ones
final
and used as public or private constants. - Static variables are created when the program starts and are destroyed when the program stops.
- Visibility is similar to instance variables. However, most static variables are public because they must be available to users of that class.
- Defaults are the same as instance variables. For numbers, the default is
0
; for boolean types, the default isfalse
; for object references, the default isnull
. Values can be specified during declaration or in the constructor. Additionally, values can be assigned in special static initializer blocks. ClassName.VariableName
Static variables can be accessed by calling them with the class name .- When
public static final
declaring , the variable names (constants) are all uppercase. If the static variable is notpublic
andfinal
, the naming syntax is the same as instance and local variable naming rules.
Example
import java.io.*; public class Employee { // the salary variable is a private static variable private static double salary; // DEPARTMENT is a constant public static final String DEPARTMENT = "R&D Department"; public static void main(String args[]) { salary = 19999; System.out.println(DEPARTMENT + "average salary:" + salary); } }
Output:
R&D department average salary:19999