Java Reference
In-Depth Information
Scoping
As mentioned previously, the exam objectives state that you need to be able to develop code
that uses “static, instance, and local variables.” Each of these three types of variables has a
different scope. Scope refers to that portion of code where a variable can be accessed. There
are three kinds of variables in Java, depending on their scope:
Instance variables These variables represent the nonstatic fi elds of a class.
Class variables These variables represent the static fi elds of a class.
Local variables These variables are defi ned inside a method. Local variables are only
accessible within the method in which they are declared.
This section discusses these three types of variables in detail, starting with a discussion
of instance variables.
Instance Variables
Instance variables are the nonstatic fi elds of your class, often referred to simply as fi elds .
These variables get allocated in memory when a new object is instantiated. Because the new
operator zeroes the memory for an object, all fi elds initially have their corresponding zero
value, which are as follows:
Primitive numeric fields initialize to 0. This includes byte , short , int , long , float and
double .
boolean types initialize to false .
char types initialize to the null character '\u0000' .
Reference types initialize to null .
Instance variables are always initialized during object instantiation, so you can use an
instance variable even if you do not specifi cally assign it a value.
Let's take a look at an example. Suppose we have the following class named Television :
1. public class Television {
2. public int channel;
3. public double diagonal;
4. public String brand;
5.
6. public Television() {
7. channel = 4;
8. }
9. }
Search WWH ::




Custom Search