Java Reference
In-Depth Information
7. public static void main(String [] args) {
8. out.println(“counter = “ + counter);
9. House one = new House();
10. House two = new House();
11. one.getKitchen();
12. two.getKitchen();
13. one.getKitchen();
14. out.println(“counter = “ + counter);
15. }
16.}
This code compiles successfully and has the same output as HouseTest . Notice the static
imports allow counter and out to be referenced by their simple names and not prefi xed
with their corresponding class name.
Because static imports are a fairly new concept in Java, expect at least one
question on the exam to test your knowledge of how to properly declare
and use a static import.
Local Variables
A local variable is a variable defi ned within a method, which includes any method
parameters. A local variable gets created in memory on the call stack when the method
executes, and is deleted from memory when the method returns and the call stack memory
is destroyed. Local variables never appear on the heap, although a local variable that is a
reference can certainly refer to an object on the heap.
Local variables must be initialized before use. They do not have a default value and
contain garbage data until initialized. The compiler enforces this rule. For example, the
following code generates a compiler error:
4. public int notValid() {
5. int y = 10;
6. int x;
7. int reply = x + y;
8. return reply;
9. }
The ints y and x are local variables and y is initialized to 10. However, because x is not
initialized before it is used in the expression on line 7, the compiler generates the following
error:
Test.java:5: variable x might not have been initialized
int reply = x + y;
^
Search WWH ::




Custom Search