+84 1649 660 740

Friday, 29 August 2014

Initializing Variables In Java

After you declare a variable, you must explicitly initialize it by means of an assignment statement - you can never use the value of an uninitialized variable. For example, the Java compiler flags the following sequence of statement as an error:

int vacationDays;
System.out.println(vacationDays); // Error - variable not initialized
You assign to previously declared variable by using the variable name on the left, an equal sign (=), and then some Java expression with an appropriate value on the right.

int vacationDays;
vacationDays = 12;
Finally, in Java you can put declarations anywhere in your code. For example, the following is valid code in Java:

double salary = 65000.0;
System.out.println(salary);
int vacationDays = 12; //OK to declare a variable here
In Java, it is considered good style to declare variables as closely as possible to the point where they are first used.

* Note: C/C++ distinguish between the declaration and definition of a variable. For example,

int i = 10;
is a definition, whereas

extern int i;
is a declaration. In Java, no declarations are separate from definitions.

0 comments:

Post a Comment