Variables, Parameters, Fields, and Scope

variable : variable is declared inside a method, constructor, initializer block, or block statement. The variable can be used only in that block statement (or method or constructor or initializer block), and only after its declaration.

parameter: parameter is a special kind of variable: it is declared in the parameter list of a method or constructor,and is given a value when the method or constructor is called. The parameter can be used only in that method or constructor, and only after its declaration.

field:A field is declared inside a class, but not inside a method or constructor or initializer block of the class. It can be used anywhere in the class, also textually before its declaration.

Variable Declarations:

The purpose of a variable is to hold a value during the execution of a block statement (or method or constructor or initializer block). A variable-declaration has one of the forms
variable-modifier type varname1, varname2, ... ;
variable-modifier type varname1 = initializer1, ... ;

A variable-modifier may be final or absent. If a variable is declared final, then it must be initialized or assigned at most once at run-time (exactly once if it is ever used): it is a named constant. However, if the variable has reference type, then the object or array pointed to by the variable may still be modified. A variable initializer may be an expression or an array initializer .

Execution of the variable declaration will reserve space for the variable, then evaluate the initializer, if any, and store the resulting value in the variable. Unlike a field, a variable is not given a default value when declared, but the compiler checks that it has been given a value before it is used.

Scope of Variables, Parameters, and Fields:

The scope of a name is that part of the program in which the name is visible. The scope of a variable extends from just after its declaration to the end of the innermost enclosing block statement. The scope of a method or constructor parameter is the entire method or constructor body. For a control variable x declared in a for statement
for (int x = ...; ...; ...) body

the scope is the entire for statement, including the header and the body.

Within the scope of a variable or parameter x, one cannot redeclare x. However, one may declare a variable x within the scope of a field x, thus shadowing the field. Hence the scope of a field x is the entire class, except where shadowed by a variable or parameter of the same name, and except for initializers preceding the field's declaration

related post
comments and types in java

No comments:

Post a Comment