A variable is a name which is associated with a value that can be changed. For example when I write int i=10;
here variable name is i which is associated with value 10, int is a data type that represents that this variable can hold integer values. We will cover the data types in the next tutorial. In this tutorial, we will discuss about variables.
A variable is the name given to a memory location. It is the basic unit of storage in a program.
We can declare variables in java as follows:
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
float simpleInterest; //Declaring float variable
int time = 10, speed = 20; //Declaring and Initializing integer variable
char var = 'h'; // Declaring and Initializing character variable
To declare a variable follow this syntax:
data_type variable_name = value;
here value is optional because in java, you can declare the variable first and then later assign the value to it.
For example: Here num is a variable and int is a data type. We will discuss the data type in next tutorial so do not worry too much about it, just understand that int
data type allows this num variable to hold integer values. You can read data types here but I would recommend you to finish reading this guide before proceeding to the next one.
int num;
Similarly we can assign the values to the variables while declaring them, like this:
char ch = 'A';
int number = 100;
or we can do it like this:
char ch;
int number;
...
ch = 'A';
number = 100;
There are certain rules for defining a valid java variables. These rules must be followed, otherwise we get compile-time error. These rules are also valid for other languages like C,C++.
Reserved Words can’t be used as an identifier. For example “int while = 20;” is an invalid statement as while is a reserved word. There are 53 reserved words in Java.
Examples of valid identifiers :
MyVariable
MYVARIABLE
myvariable
x
i
x1
i1
_myvariable
$myvariable
sum_of_array
geeks123
Examples of invalid identifiers :
My Variable // contains a space
123geeks // Begins with a digit
a+c // plus sign is not an alphanumeric character
variable-2 // hyphen is not an alphanumeric character
sum_&_difference // ampersand is not an alphanumeric character
Reserved Words
Any programming language reserves some words to represent functionalities defined by that language. These words are called reserved words.They can be briefly categorised into two parts : keywords(50) and literals(3).
keywords define functionalities and literals defines a value.
Identifiers are used by symbol tables in various analyzing phases(like lexical,syntax,semantic) of a compiler architecture.
Note : The keywords const and goto are reserved, even though they are not currently used. In place of const, final keyword is used. Some keywords like strictfp are included in later versions of Java.
There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable
These variables are declared inside method of the class. Their scope is limited to the method which means that You can’t change their values and access them outside of the method.
In this example, I have declared the instance variable with the same name as local variable, this is to demonstrate the scope of local variables.
public class VariableExample {
// instance variable
public String myVar="instance variable";
public void myMethod(){
// local variable
String myVar = "Inside Method";
System.out.println(myVar);
}
public static void main(String args[]){
// Creating object
VariableExample obj = new VariableExample();
/* We are calling the method, that changes the
* value of myVar. We are displaying myVar again after
* the method call, to demonstrate that the local
* variable scope is limited to the method itself.
*/
System.out.println("Calling Method");
obj.myMethod();
System.out.println(obj.myVar);
}
}
Output:
Calling Method
Inside Method
instance variable
If I hadn’t declared the instance variable and only declared the local variable inside method then the statement System.out.println(obj.myVar); would have thrown compilation error. As you cannot change and access local variables outside the method.
Static variables are also known as class variable because they are associated with the class and common for all the instances of class. For example, If I create three objects of a class and access this static variable, it would be common for all, the changes made to the variable using one of the object would reflect when you access it through other objects.
public class StaticVarExample {
public static String myClassVar="class or static variable";
public static void main(String args[]){
StaticVarExample obj = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();
StaticVarExample obj3 = new StaticVarExample();
//All three will display "class or static variable"
System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
//changing the value of static variable using obj2
obj2.myClassVar = "Changed Text";
//All three will display "Changed Text"
System.out.println(obj.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(obj3.myClassVar);
}
}
Output:
class or static variable
class or static variable
class or static variable
Changed Text
Changed Text
Changed Text
As you can see all three statements displayed the same output irrespective of the instance through which it is being accessed. That’s is why we can access the static variables without using the objects like this:
System.out.println(myClassVar);
Do note that only static variables can be accessed like this. This doesn’t apply for instance and local variables.
Each instance(objects) of class has its own copy of instance variable. Unlike static variable, instance variables have their own separate copy of instance variable. We have changed the instance variable value using object obj2 in the following program and when we displayed the variable using all three objects, only the obj2 value got changed, others remain unchanged. This shows that they have their own copy of instance variable.
public class InstanceVarExample {
String myInstanceVar="instance variable";
public static void main(String args[]){
InstanceVarExample obj = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();
InstanceVarExample obj3 = new InstanceVarExample();
System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
obj2.myInstanceVar = "Changed Text";
System.out.println(obj.myInstanceVar);
System.out.println(obj2.myInstanceVar);
System.out.println(obj3.myInstanceVar);
}
}
Output:
instance variable
instance variable
instance variable
instance variable
Changed Text
instance variable
Instance variable Vs Static variable
Syntax for static and instance variables:
class Example
{
static int a; //static variable
int b; //instance variable
}
Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all variables are lexically (or statically) scoped, i.e.scope of a variable can determined at compile time and independent of function call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be covered under following categories.
Member Variables (Class Level Scope)
These variables must be declared inside class (outside any function). They can be directly accessed anywhere in class. Let’s take a look at an example:
public class Test
{
// All variables defined directly inside a class
// are member variables
int a;
private String b
void method1() {....}
int method2() {....}
char c;
}
Modifier Package Subclass World
public Yes Yes Yes
protected Yes Yes No
Default (no
modifier) Yes No No
private No No No
Local Variables (Method Level Scope)
Variables declared inside a method have method level scope and can’t be accessed outside the method.
public class Test
{
void method1()
{
// Local variable (Method level scope)
int x;
}
}
Note : Local variables don’t exist after method’s execution is over.
Here’s another example of method scope, except this time the variable got passed in as a parameter to the method:
class Test
{
private int x;
public void setX(int x)
{
this.x = x;
}
}
The above code uses this keyword to differentiate between the local and class variables.
As an exercise, predict the output of following Java program.
|
Output:
Test.x: 22
t.x: 22
t.y: 33
y: 44
Loop Variables (Block Scope)
A variable declared inside pair of brackets “{” and “}” in a method has scope withing the brackets only.
public class Test { public static void main(String args[]) { { // The variable x has scope within // brackets int x = 10; System.out.println(x); }
// Uncommenting below line would produce // error since variable x is out of scope.
// System.out.println(x); } } |
Output:
10
As another example, consider following program with a for loop.
|
Output:
11: error: cannot find symbol
System.out.println(x); ^
The right way of doing above is,
|
Output:
0
1
2
3
4
Let’s look at tricky example of loop scope. Predict the output of following program. You may be surprised if you are regular C/C++ programmer.
|
Output :
6: error: variable a is already defined in method go(int)
for (int a = 0; a < 5; a++)
^
1 error
As an exercise, predict the output of following Java program.
|
Some Important Points about Variable scope in Java: