Sunday 13 March 2016

The Java Language: Variable declaration and initialization

Variables are declared inside of methods and classes with a type name followed by one or more comma-separated variable names. For example:

 int foo;  
 double d1, d2;  
 boolean isFun;  
Variables can optionally be initialized with an expression of the appropriate type when they are declared:
 int foo = 42;  
 double d1 = 3.14, d2 = 2 * 3.14;  
 boolean isFun = true;  
Variables that are declared as members of a class are set to default values if they aren’t initialized. In this case, numeric types default to the appropriate flavor of zero, characters are set to the null character (\0), and Boolean variables have the value false. Local variables, which are declared inside a method and live only for the duration of a method call, on the other hand, must be explicitly initialized before they can be used. As we’ll see, the compiler enforces this rule so there is no danger of forgetting.

0 comments:

Post a Comment