Wednesday, 28 July 2010

Variables

Variables are temporary data holders. Variable names are identifiers. Variables are declared with a datatype. Java is a strongly typed language as the variable can only take a value that matches its declared type. This enforces good programming practice and reduces errors considerably. When variables are declared they may or may not be assigned or take on a value (initialized). Examples of each of the primitive datatypes available in Java are as follows:

byte x,y,z;             /* 08bits long, not assigned, multiple declaration */
short numberOfChildren; /* 16bits long */
int counter;            /* 32bits long */
long WorldPopulation;   /* 64bits long */

float pi;               /* 32bit single precision */
double avagadroNumber;  /* 64bit double precision */
boolean signal_flag;    /* true or false only */
char c;                 /* 16bit single Unicode character */

Constant variables
Variables can be made constant or read only by prepending the modifier final to the declaration. Java convention uses all uppercase for final variable names.

Local Variables
Local variables (also known as automatic variables) are declared in methods and in code blocks. The automatic variables are not automatically initialized.
A java programmer should explicitly initialize them before first use. These are automatically destroyed when they go out of scope.

Field Variables and Local Variables Field variables are variables that are declared as members of classes. Local variables, also referred to as automatic variables, are declared relative to (or local to) a method or constructor. <

Automatic Initialization Note
Field variables and the elements of arrays are automatically initialized to default values. Local variables are not automatically initialized. Failure to initialize a local variable results in a compilation error.

No comments:

Post a Comment