Saturday, January 10, 2009

What is an instance variable in Java

Welcome back to Java Code Online. You must have heard the instance variable a multiple number of times while writing your Java code, but do you really understand what is a instance variable in Java. Today I will discussing about instance variables in Java.

An instance variable in Java is one which is declared within a class and not within a method. Whenever you write code in Java, you do it with the help of classes. In most of the classes you need to declare some variables for some purpose or the other. These variables which are declared within the class but not within the method are called instance variables in Java.

If you declare the variable within a method, then it becomes a local variable of that method and not an instance variable of the class. So you need to declare it within a class but outside any method. I will clarify my point with an example.

class JavaCode{
int code;
float test;
//Some Java Code here
}

In the above Java Code, the variables "code" and "test" are local to a class but are outside any method, and are therefore instance variables of this class. I hope you got my point now.

One important point about instance variable is that, they always get a default value. If you declare any instance variable in your Java Code and use them without initializing them, then also the compiler will not complain, and it will compile properly. This happens because the compiler assigns the instance variables a default value. So if the instance variables are not initialized then the default value is used in their place.

The default values of the various type of variables is shown below:-
integers-----------0
floating points----0.0
booleans-----------false
references---------null

These are default values which are assigned to various types of variables. So to summarize the whole thing.
1. instance variables are declared inside a class but not within a method.
2. instance variables always have a default value assigned to them.

I hope this article helped you to understand what is an instance variable in Java. If you liked the article then do leave a comment. For more info on Java, keep buzzing Java Code Online.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.