Sunday, April 5, 2015

Learning Java , if you know C : Part-2 , Static Keyword

Learning Java

2. Difference in static variable in C and Java.

 > In c we have two types of global variables : static global and non-static global. The difference is in the scope of these, static global variable can only be used inside the C file
   in which they are defined.
   In Java and also in C++, static global variable means CLASS VARIABLE, they are shared by all the instances.
   whereas non-static global variable are INSTANCE VARIABLE, they cannot be shared among different instances.
 
  ********************************************************* JAVA PROGRAM *********************************************************

  public class global1{

static int global=2;
public static void main(String args[])
{
System.out.println(global);
global++;

}
 }


public class global2{

public static void main(String args[])
{
System.out.println(global1.global);
global1.global++;

}
 }

   ********************************************************* JAVA PROGRAM *********************************************************

 The global variable when has static qualifier in front of it becomes CLASS variable, every object defined of that class will have a single copy.
 whereas non-static are OBJECT variables, every class will have it's own copy

No comments:

Post a Comment