It's not a secret anymore!
The moose likes Beginning Java and the fly likes Variables in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variables in Java" Watch "Variables in Java" New topic

Variables in Java

Monowar Hossain

Joined: Sep 19, 2001
Posts: 2
When first time I was learning java then its different types of variables make me confused. So I study so many books and then come out with a clear concept about different types of variables of java. Here I try to give a short description of different types of variables in an easy manner-
There are three types of variables in java-
1. Instance variables:
Instance variables that are members of a class and are instantiated for each object of the class. In other words, all instances, i.e. objects, of the class will have their own instances of these variables, which are the local to the object. The values of these variables at any given time constitute the state of the object.
2. Static variables:
Static variables that are also members of a class, but these are not instantiated for any object of the class and there for belongs only to the class. Only the static methods can use static variables.
3. Local variables:
Local variables are declared in methods and in blocks, are instantiated for each invocation of the method or block. In java, local variables must be declared before they can be used.
Here is an example of these variables-
public class temp
int x; // instance variable
static int y; //static variable
public static void main(String [] args)
int z; //local variable

Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
I put a link to this in
because I think that you intended this as a response to that question.

"JavaRanch, where the deer and the Certified play" - David O'Meara
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Monowar,
You are close but not quite. You are confusing terminology and some concepts. Here's my try.
1. Instance variables
Variables that belong to each object of the class type. The variables make up the object state.
2. Static variables
Variables that belong to the class. There is only one static variable regardless of the number of objects that exist in the JVM.
NOTE: Any method (static or not) can use static variables because they are initialized at load time!
3. Local variables
Variables that are declared inside any method or block. They must be declared and initialized (except arrays) before use.
Just to be clear:
Instatiation --> A a = new A();
Applies to objects only not variables.
Declaration --> int b;
Initialization --> b = 5;
Declaration & Initialization --> int b = 5;
I agree. Here's the link:
subject: Variables in Java
jQuery in Action, 3rd edition