Variables

In Java variables are like place holders they are used to specify or reserve memory for a specified data type. Variables can also be referred as ingredients to make a program. You can declare a variable as follows :

datatype identifier = value;

Here “datatype” can be any data type in Java “identifier” refers  to the name of the variable and “value” is the data which is stored in that variable. In Java the value of a variable is also called literal.

Java has three types of variables  they are :

  • Local Variables
  • Static Variables

Instance Variables

Local Variables :

  • Local variables are declared inside a method or any block.
  • They are created when the method is called and are destroyed after methods execution.
  • They must be initialized before they are used because they dont have any default value.
  • They are implemented at stack level.
  • A local variable can be declared inside the body of the method or the paranthesis “()”
  • They are only visible inside the method or block in which they are declared.
  • If the variable is declared inside the paranthesis it should not be initialized inside the body of the method because the value is provided when the method is called

Example :

01   class MyClass{

02   public int cube(int a){  // a is not initialized in the method  body

03   return (a*a*a);

04   } // end od cube method

05   public void square(){

06   int a; // declared a variable named ‘a’

07   a = 5; //initializing ‘a’

08   System.out.println(“The value of  a is : ” + a);

09   } // end of square method

10   public static void main(String arguments[]){

11   MyClass m = new MyClass();   // creating object of the class MyClass

12   System.out.println(m.cube(5)); // calling method cube to find the cube of ‘5’

13   m.square(); // calling the method square

14   } // end of main

15  } //end of class

Output :

125

The value of a is : 5

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s