Users Online

· Guests Online: 26

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#00002 Variables in Java

1.1.            Variables in Java

 

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.

 

  • The value stored in a variable can be changed during program execution.
  • A variable is only a name given to a memory location, all the operations done on the variable effects that memory location.
  • In Java, all the variables must be declared before use.

 

How to Declare a variable in Java

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;

 

Variables naming convention in java

  1. Variables naming cannot contain white spaces, for example: int num ber = 100; is invalid because the variable name has space in it.
  2. Variable name can begin with special characters such as $ and _
  3.  As per the java coding standards the variable name should begin with a lower case letter, for example int number; For lengthy variables names that has more than one words do it like this: int smallNumber; int bigNumber; (start the second word with capital letter).
  4. Variable names are case sensitive in Java.

 

 

Rules for defining Java variables

 

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++.

  • The only allowed characters for variables are all alphanumeric characters([A-Z],[a-z],[0-9]), ‘$‘(dollar sign) and ‘_‘ (underscore).For example “geek@” is not a valid java identifier as it contain ‘@’ special character.
  • variables should not start with digits([0-9]). For example “123geeks” is a not a valid java variable
  • Java variables are case-sensitive.
  • There is no limit on the length of the identifier but it is advisable to use an optimum length of 4 – 15 letters only.

 

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.

Types of Variables in Java

There are three types of variables in Java.
1) Local variable 2) Static (or class) variable 3) Instance variable

Local 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.

Example of Local variable

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 (or class) Variable

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.

Example of static variable

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.

Instance variable

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.

Example 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

  • Each object will have its own copy of instance variable whereas We can only have one copy of a static variable per class irrespective of how many objects we create.
  • Changes made in an instance variable using one object will not be reflected in other objects as each object has its own copy of instance variable. In case of static, changes will be reflected in other objects as static variables are common to all object of a class.
  • We can access instance variables through object references and Static Variables can be accessed directly using class name.

 

Syntax for static and instance variables:

class Example
    {
        static int a; //static variable
        int b;        //instance variable
    }

Scope of Variables In Java

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;
}
  • We can declare class variables anywhere in class, but outside methods.
  • Access specified of member variables doesn’t effect scope of them within a class.
  • Member variables can be accessed outside a class with following rules

 

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.

public class Test

{

    static int x = 11;

    private int y = 33;

    public void method1(int x)

    {

        Test t = new Test();

        this.x = 22;

        y = 44;

  

        System.out.println("Test.x: " + Test.x);

        System.out.println("t.x: " + t.x);

        System.out.println("t.y: " + t.y);

        System.out.println("y: " + y);

    }

  

    public static void main(String args[])

    {

        Test t = new Test();

        t.method1(5);

    }

}

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.

class Test

{

    public static void main(String args[])

    {

        for (int x = 0; x < 4; x++)

        {

            System.out.println(x);

        }

  

        // Will produce error

        System.out.println(x);

    }

}

 

Output:

11: error: cannot find symbol
        System.out.println(x);                           ^

The right way of doing above is,

// Above program after correcting the error

class Test

{

    public static void main(String args[])

    {

        int x;

        for (x = 0; x < 4; x++)

        {

            System.out.println(x);

        }

  

       System.out.println(x);

    }

}

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.

class Test

{

    public static void main(String args[])

    {

        int a = 5;

        for (int a = 0; a < 5; a++)

        {

            System.out.println(a);

        }

    }

}

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.

class Test

{

    public static void main(String args[])

    {

        {

            int x = 5;

            {

                int x = 10;

                System.out.println(x);

            }

        }

    }

}

Some Important Points about Variable scope in Java:

 

  • In general, a set of curly brackets { } defines a scope.
  • In Java we can usually access a variable as long as it was defined within the same set of brackets as the code we are writing or within any curly brackets inside of the curly brackets where the variable was defined.
  • Any variable defined in a class outside of any method can be used by all member methods.
  • When a method has the same local variable as a member, this keyword can be used to reference the current class variable.
  • For a variable to be read after the termination of a loop, It must be declared before the body of the loop.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.07 seconds
10,800,409 unique visits