Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

Creating Behavior with Methods 145

Variable Scope Within Methods


Whenyou create a variable or an object inside a method in one of your
classes, it is usable only inside that method. The reason for this is the con-
cept of variable scope. Scope is the block in which a variable exists in a pro-
gram. If you go outside of the part of the program defined by the scope,
you can no longer use the variable.


The {and }statements in a program define the boundaries for a variable’s
scope. Any variable created within these marks cannot be used outside of
them. For example, consider the following statements:


if (numFiles < 1) {
String warning = “No files remaining.”;
}
System.out.println(warning);


This code does not work—and does not compile in NetBeans—because the
warningvariable was created inside the brackets of the ifblock. Those
brackets define the scope of the variable. The warningvariable does not
exist outside of the brackets, so the System.out.println()method cannot
use it as an argument.


When you use a set of brackets inside another set of brackets, you need to
pay attention to the scope of the enclosed variables. Take a look at the fol-
lowing example:


if (infectedFiles < 5) {
int status = 1;
if (infectedFiles < 1) {
booleanfirstVirus = true;
status = 0;
} else{
firstVirus = false;
}
}


See any problems? In this example the statusvariable can be used any-
where, but the statement that assigns a value to the firstVirusvariable
causes a compiler error. Because firstVirusis created within the scope of
the if (infectedFiles < 1)statement, it doesn’t exist inside the scope of
the elsestatement that follows.


To fix the problem, firstVirusmust be created outside both of these
blocks so that its scope includes both of them. One solution is to create
firstVirusone line after statusis created.

Free download pdf