-
Book Overview & Buying
-
Table Of Contents
OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808
By :
You've learned that local variables are declared within a method. How many local variables do you see in this example?
public void eat(int piecesOfCheese) {
int bitesOfCheese = 1;
}
There are two local variables in this method. bitesOfCheese is declared inside the method. piecesOfCheese is called a method parameter. It is also local to the method. Both of these variables are said to have a scope local to the method. This means they cannot be used outside the method.
Local variables can never have a scope larger than the method they are defined in. However, they can have a smaller scope. Consider this example:
3: public void eatIfHungry(boolean hungry) {
4: if (hungry) {
5: int bitesOfCheese = 1;
6: } // bitesOfCheese goes out of scope here
7: System.out.println(bitesOfCheese);// DOES NOT COMPILE
8: }
hungry has a scope of the entire method. bitesOfCheese has a smaller scope. It is only available for use in the if statement because it is declared...
Change the font size
Change margin width
Change background colour