Friday, June 4, 2010

Different types of variables in java

There are three types of variables in java
1. Instance Variables
2. Static Variables
3. Local Variables

1. Instance Variables: Instance variables are also called global variables. Each instance of the class has its own copy of instance variables (This is the fact that they are called instance variables). These variables are not declared with in any of the methods in a class but they are declared with in the class. These variables are also called non-static fields.

2. Static Variables: Static variables are defined with in the class with static key word (This is the fact that they are called static variables). Static modifier tell the compiler that there is only one copy of this variable exists regardless of how many times the class has been instantiated.

3. Local Variables:
Local variables are defined with in the method. They are only accessible with in that method.

Here is the example for variables

public class Variables
{
public static int staticVariable = 0;
int instanceVariable = 0;
public static void main(String args[])
{
String localVariable = "Hello";
System.out.println(localVariable);
}
}

From the example:

Instance Variable is int instanceVariable = 0;
Static Variable is public static int staticVariable = 0;
Local Variable is String localVariable = "Hello";

No comments:

Post a Comment