Java Reference
In-Depth Information
Java allows this sort of “as needed” temporary variable definition. You can just
define variables as they are needed. There is no need to define them all up front, as
in COBOL. The language does attempt to tighten up some of the more egregious
rules defined by C and C++. (Many C and C++ programmers have struggled to
debug a program, only to discover that some instance of a program variable x was
really a different instance of x , even though both instances have the same name.)
Temporary local variables do have some benefits, mostly in the area of efficient
memory management. A block of code that temporarily needs a variable does not
need to define it as an instance variable for the whole class. Instead, the program-
mer can define it when necessary, as if it were an executable statement. Then the
system will delete the variable when the block of code is completed.
Java restricts the scope of the variable to the block of code in which it is defined.
Therefore, a program can define counter variables (x appears to be some sort of a
standard) as needed, confident that the compiler will detect conflicts in nested
blocks of code. Variables that must be shared by multiple blocks of code must be
defined as parameters or as class instance variables.
if (myErrorMsg.total_counter == 100) {
// Some logic
...
// Define a local variable.
int x;
...
}
// It will be deleted after the }.
Finally, values passed as parameters to Java methods are passed by value . This
means that a copy of the primitive data types (discussed in the following sections)
are passed rather than the variable itself. For object reference variables, the refer-
ence variable is passed, but it is in fact a reference to the object. As a result, any
passed primitive data type values are implicitly local variables. Any changes you
make to the objects referenced in passed object reference variables will be reflected
in the objects themselves. I'll discuss variable scope in Chapter 7, when I discuss
Java's flow control construct.
P RIMITIVE D ATA T YPES
As with any language, Java defines some native variable types that can be used to
store and represent data. Many languages (especially C) define standard data types,
but the implementation details for some types can vary slightly across systems,
Search WWH ::




Custom Search