Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Variables in Java  RSS feed

Monowar Hossain
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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"
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I put a link to this in
because I think that you intended this as a response to that question.
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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;
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!