Sunday, September 6, 2015

Variable types

This had to be my previous post(i.e. before methods) but never mind!!

A variable provides us with named storage that our programs can manipulate. Each variable in Java has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
You must declare all variables before they can be used. The basic form of a variable declaration is shown here:

data type variable [ = value][, variable [= value] ...] ;

Here data type is one of Java's datatypes and variable is the name of the variable. To declare more than one variable of the specified type, you can use a comma-separated list.
int a, b, c;         // Declares three ints, a, b, and c.
int a = 10, b = 10;  // Example of initialization
byte B = 22;         // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a';        // the char variable a is initialized with value 'a'
There are three kinds of variables in Java:
  • Local variables: Local variables are declared in methods, constructors, or blocks(i'l discuss constructors in java later).There is no default value for local variables so local variables should be declared and an initial value should be assigned before the first use.

Example:

Here, age is a local variable. This is defined inside printAge() method and its scope is limited to this method only.
public class Test{ 
   public void printAge(){
      int age = 0;     // age is initialized
      age = age + 7;
      System.out.println("Age is : " + age);
   }
   
   public static void main(String args[]){
      Test test = new Test();
      test.printAge();
   }
}
This would produce the following result:
Age is: 7

Example:

Following example uses age without initializing it, so it would give an error at the time of compilation.
public class Test{ 
   public void printAge(){
      int age;  //age is not initialized
      age = age + 7;
      System.out.println("Age is : " + age);
   }
   
   public static void main(String args[]){
      Test test = new Test();
      test.printAge();
   }
}
This would produce the following error while compiling it:
Test.java:4:variable number might not have been initialized
age = age + 7;
         ^
1 error
  • Instance variables: Instance variables are declared in a class, but outside a method, constructor or any block.
  • Class/static variables: Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
I will write about Instance Variables and Static variables in my next post. 
Keep practicing!!

No comments:

Post a Comment