Wednesday 28 August 2013

Static global Variables

Basically global variables doesn't exist in java.there is no concept of global variables in java but we might  say that Global variables are those which declared outside the definition block or methods.
global variables contains the default value.if we don't initialize the global variable then it takes the default values.
Default value for global variables:-

  •   int=> 0
  •   float=> 0.0f
  •   double=> 0.0
  •    boolean=>false
  •    string=>null
  •    char=.'\u0000'


Example:-




Example 2:-



first it print the default value 0.after we initialise i by 10 si it prints 10.

if we are working on global variables then the change in the value in any method will be visible or changed for all methods.

Example:-


change in the value of i in print method reflected in main method

in same scope we cannot declare same variable more then 1 time but in different scope we can do this the condition is the local scope variable has more priority over global scope variable

Example:-


in the above ex it give more priority to local variable instead of global variable....
in this condition if you want to use global variable then print the variable with the class name.
if the variable written with the class name then it refers to the global variable not local variable.

Example:-


in the second print function we write i with the class name so it refer to global variable.

You can also initialize value like  this;-



Legal forward reference in this it only checks the datatype of i and the return type of test method
if both are same then it transfer the value to i.it only transfer return value to i  no matter how many statements are present in test().
if return type is different then it will give compile time error.

2 comments :

  1. If we initialise without using static keyword then wat wud be the output ..

    ReplyDelete
    Replies
    1. bro if you declare any member as a static then there is no need to create the object of the class you will directly call that method bu using the class name.
      if you do not declare the member as static then you have to make the object of class for using it.
      Because first of all it allocates memory to all static member...
      and we create objects for allocating memory so for static member we do not make the objects and for allocating memory to non static members we must create the objects.......
      Thanx....

      Delete