Java Reference
In-Depth Information
i ++;
}
public static void
main(String [] args)
{
i=3;
inc() ;
System.out.println(i);
}
}
Unlike the two previous examples where there were two variables
i
(one in the
main
method and one in the
inc
method), now we have a single variable
i
. No information is
passed between the methods. The
main
method tells the
inc
method to update the global
variable
i
.The
inc
method updates it and returns control to the
main
method. At this
point, the
main
method prints the value of the global variable
i
. For now, we will declare
all global variables as
static
, where the meaning of the
static
keyword will be discussed
in Chapter 6. Note that even global variables have scope. The scope of the variable
i
is
the block in which it is defined. Therefore, its scope will be the
Example
class. Remember
that the innermost block in which a variable is defined determines its scope. The innermost
block for the variable
i
is the
Example
class.
Comparing the two solutions, the first one is preferable. Good programming practices
call for global variables to be used sparingly. The reason is that if a global variable has an
incorrect value, then it is dicult to isolate the error. If your class contains ten methods,
then any of these methods could have changed the value of the global variable.
Note that a method can return only a single piece of information. For example, a method
that returns two integers cannot be created. Global variables are one way to solve this
problem. The method can simply modify two global variables and have
void
return type.
An example is shown next.
import
java . util .
∗
;
public class
Example
{
static int
firstNumber , secondNumber ;
public static void
main(String [] args)
{
readTwoIntegers () ;
System. out . println(firstNumber) ;
System . out . println (secondNumber) ;
}
public static void
readTwoIntegers ()
{
Scanner keyboard =
new
Scanner(System. in) ;
firstNumber = keyboard. nextInt () ;
secondNumber = keyboard . nextInt () ;
}
}
This is a bad design. Global variables should not be declared just because the
readTwoIntegers
method needs to return two integers. A much better approach is to
avoid using methods that return two integers. A program with an improved design is shown
next.
import
java . util .
∗
;
public class
Example
{
public static void
main(String [] args)
{
int
firstNumber , secondNumber ;
firstNumber = readInteger () ;
secondNumber = readInteger () ;