19 October 2010
0 What is Variables in Java?
Variables in Java
Declaring and using primitive data types is Java similar to that of C.
int flag;
int maxCount=100;
int maxCount=100;
Unlike C, in Java, variables can be declared anywhere in the program.
int index = 10;
System.out.println(“Program starts here”);
int j = 20;
for (int index=0; index <maxCount; index++) {
int z = index * 10;
}
System.out.println(“Program starts here”);
int j = 20;
for (int index=0; index <maxCount; index++) {
int z = index * 10;
}
Best Practice while dealing with Java Variables: Declare a variable in program only when required. Do not declare variables upfront like in C.
Local Variables in Java
In Java, if a local variable is used without initializing it, the compiler will show an errorclass Sample{
public static void main (String [] args){
int count;
System.out.println(count);//This will give Error
}
}
public static void main (String [] args){
int count;
System.out.println(count);//This will give Error
}
}
Instance variables
Instance variables are declared in a class, but outside a method. They are also called member or field variables. When an object is allocated in the heap, there is a slot in it for each instance variable value. Therefore an instance variable is created when an object is created and destroyed when the object is destroyed. Visible in all methods and constructors of the defining class, should generally be declared private, but may be given greater visibility.Class/static variables
Class/static variables are declared with the static keyword in a class, but outside a method. There is only one copy per class, regardless of how many objects are created from it. They are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.Reference variables in Java
Reference variables are used in Java to store the references of the objects created by the operator "new"Any one of the following syntax can be used to create a reference to an int array
int x[];
int [] x;
int [] x;
Subscribe to:
Post Comments (Atom)
0 comments:
Please give your valuable comments.