Google+

45. Variable Declaration and Initialization






The variable is a basic unit of storage in a Java Program.


Declaring a Variable: In Java, all the programs must be declared before they can be used.

Program to demonstrate what happens when we use a variable without declaring it:

class VariableNotDeclared
{
   public static void main(String args[])
   {
        a=5;    //Using a variable without declaring it
        System.out.println(a);
   }
 }

Output of this program:

Error. "Cant find the symbol a . Symbol: Variable a  Location: VariableNotDeclared" 

This error is displayed because we've not declared the variable a.


Program to demonstrate that we can declare more than one variable of same type in a single statement

class MultiDeclarationsSingleStatement
{
   public static void main(String args[])
   {
      int a,b,c;    //Here I've delcared three variables a,b and c as int data type in a single statement
 
      a=3;
      b=4;
      c=5;
 
      System.out.println("a:"+a);
      System.out.println("b:"+b);
      System.out.println("c:"+c);

   }
 }

Output of this program:

a:3
b:4
c:5


Program to demonstrate that we can initialize the variables while declaring itself

class InitializingVariablesWhileDeclaration
{
   public static void main(String args[])
   {
      int a=3,b=4,c=5;    // Initializing the variables by assigning values while declaring the variables itself

      System.out.println("a:"+a);
      System.out.println("b:"+b);
      System.out.println("c:"+c);

   }
 }

Output of this program:

a:3
b:4
c:5


Program to demonstrate the dynamic initialization of variables 

class DynamicInitialization
{
   public static void main(String args[])
   {
      int a=3,b=4;

      int c=a+b;    // Initializing the variable c dynamically i.e. while performing a+b operation and assigning it to c

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

   }
 }

Output of this program:

c:7





Please comment below to feedback or ask questions.

Scope of Variables topic will be explained in the next post.




No comments: