Java Basics1
Java Basics1
Access Control
AL
Write code that declares, constructs, and initializes
arrays of any base type using any of the permitted
RI
forms both for declaration and for initialization.
Declare
TE
classes, inner classes, methods, instance
variables, static variables, and automatic (method
local) variables, making appropriate use of all per-
MA
mitted modifiers (such as public, final, static,
abstract, and so forth). State the significance of
each of these modifiers, both singly and in combi-
nation, and state the effect of package relation-
ED
Write code that declares, constructs, and
initializes arrays of any base type using
any of the permitted forms both for dec-
laration and for initialization.
Critical Information
You will need to know about the following aspects of arrays:
Declaration
Construction
Initialization
Chapter 1 Declarations and Access Control 3
These three steps are the first stages of an array’s life cycle. The exam
expects you to be familiar with all aspects of array declaration, con-
struction, and initialization.
Array Declaration
Java supports two formats for array declaration. The first format is
the classical C/C++ syntax, in which the element type comes first, fol-
lowed by the variable name, followed by square brackets. This syntax
is illustrated in line 1 as follows. The second format begins with the
element type, which is followed by the square brackets and then by
the variable name; the second format is illustrated in line 2 as follows.
1. int intarr[];
2. int[] intarr;
1. String myStrings[];
2. String[] myStrings;
1. float[][][][] matrixOfFloats;
2. float matrixOfFloats[][][][];
3. float[][][] matrixOfFloats[];
4 Java 2 Exam Notes
Array Construction
Array declaration is like declaration of any other object reference
variable. The declaration only tells the compiler about the type of
the variable. No runtime object is created until new is invoked. Note
that the declaration does not specify the number of elements in the
array; the number of elements is supplied at runtime, as shown in
the following examples:
1. long longarr[];
2. longarr = new long[10];
3. String[] myStrings;
4. myStrings = new String[22];
5. double[][] matrixOfDoubles;
6. matrixOfDoubles = new double[1152][900];
7. int[][] matrixOfInts;
8. matrixOfInts = new int[500][];
9. matrixOfInts[0] = new int[33];
10. matrixOfInts[1] = new int[44];
byte 0
short 0
int 0
long 0
char '\u0000'
float 0.0f
double 0.0d
boolean false
With this syntax, the invocation of new and the size of the array are
implicit. The array elements are initialized to the values given
between the brackets, rather than their default initialization values.
Exam Essentials
Know how to declare and construct arrays. The declaration
includes one empty pair of square brackets for each dimension of the
array. The square brackets can appear before or after the array name.
Arrays are constructed with the keyword new.
6 Java 2 Exam Notes
Know the default initialization values for all possible types. The
initialization values are zero for numeric type arrays, false for bool-
ean arrays, and null for object reference type arrays.
Know how to declare, construct, and initialize in a single statement.
This notation uses initialization values in curly brackets; for example,
int[] intarr = {1, 2, 3};.
Sample Questions
1. Which of the following are legal array declarations?
A. int[] z[];
B. String[][] z[];
C. char[] z;
D. char z[];
E. float[5] z;
2. What are the default initialization values for an array of type char?
Answer: '\u0000' (the null character). Table 1.1 lists initializa-
tion values for arrays of all primitive types.
Chapter 1 Declarations and Access Control 7
Answer: C and D are both legal. A is illegal because the array size
is stated explicitly. B is illegal because it uses square brackets
where curly brackets are required.
Declare classes, inner classes, methods,
instance variables, static variables, and
automatic (method local) variables, making
appropriate use of all permitted modifiers
(such as public, final, static, abstract, and
so forth). State the significance of each of
these modifiers, both singly and in combi-
nation, and state the effect of package
relationships on declared items qualified
by these modifiers.
Critical Information
A modifier is a Java keyword that affects the behavior of the feature
it precedes. (A feature of a class is the class itself, or a method, vari-
able, or inner class of the class.) Java’s modifiers are listed as follows:
private
protected
public
final
abstract
static
synchronized
transient
native
volatile
The first three of these modifiers (private, protected, and public)
are known as access modifiers. The remaining modifiers do not fall
into any clear-cut categories. (Another modifier, strictfp, is a new
addition to Java 2. It is discussed briefly in Chapter 4, “Language
Fundamentals,” but does not appear on the exam.)
Access
Mode Java Keyword Methods and Fields Inner Classes
Table 1.3 shows which access modes are available to which feature
types.
Chapter 1 Declarations and Access Control 11
One way to create a Java class that resides inside a package is to put
a package declaration at the beginning of your source file. (Further
details on package creation are not required knowledge for the Pro-
grammer’s Exam and are beyond the scope of this book.) If you do
not explicitly use a package declaration, a package might be implic-
itly created for you. At runtime, the Java environment creates a
“default package” that contains all classes in the current working
directory that do not explicitly belong to other packages.
packageA
packageB
class Parent
class ChildB
class ChildA
The childB subclass has access to all features of the Parent superclass
that are public or protected. The childA subclass also has access to
the public and protected features of Parent. In addition, since childA
and Parent are in the same package, childA has access to all default
features of Parent; this access would be the same if childA were not
a subclass of Parent.
You are not allowed to apply any access modifier other than public
to a method in an interface. The following interface generates a com-
piler error.
Chapter 1 Declarations and Access Control 13
Interface BadAccess {
protected double x(); // Compiler error
}
Access Examples
This section presents several examples of the use of access modifiers.
All the examples refer to a simple class called packageA.Parent,
which is listed below:
1. package packageA;
2.
3. public class Parent {
4. private int iPrivate;
5. int iDefault;
6. protected int iProtected;
7. public int iPublic;
8. }
The class definitions that follow illustrate each of the four Java access
modes. All the code compiles; lines that illustrate illegal access
attempts have been commented out.
The first example illustrates the private access mode. Since only the
Parent class may access a private feature of the Parent class, our
example is an expansion of Parent.
1. package packageA;
2.
3. public class Parent {
4. private int iPrivate;
5. int iDefault;
6. protected int iProtected;
7. public int iPublic;
8.
14 Java 2 Exam Notes
9. void xxx() {
10. iPrivate = 10; // My own
11. Parent other = new Parent();
12. other.iPrivate = 20; // Someone else’s
13. }
14. }
The next example illustrates the default access mode, which grants
access permission to all classes in the same package as the class that
owns the default feature. Here we will create a second class in the
packageA package.
1. package packageA;
2.
3. public class InSamePackage {
4. void makeItSo() {
5. Parent parent = new Parent();
6. // parent.iPrivate = 10;
7. parent.iDefault = 20;
8. parent.iProtected = 30;
9. parent.iPublic = 40;
10. }
11. }
The next example illustrates the protected access mode, which grants
access permission to all classes in the same package as the class that owns
the protected feature, as well as to subclasses of the class that owns the
feature. Here we will create a class in a second package, called packageB.
1. package packageB;
2.
3. public class InDifferentPackage
4. extends packageA.Parent {
5. void aMethod() {
6. packageA.Parent parent =
new packageA.Parent();
7. // parent.iPrivate = 10;
8. // parent.iDefault = 20;
9. // parent.iProtected = 30;
10. iProtected = 40;
11. parent.iPublic = 50;
12. }
13. }
Lines 7 and 8 have to be commented out for reasons that were illus-
trated in the previous examples. It may be surprising that line 9 does
not compile and also must be commented out. The iProtected vari-
able is protected; an instance of a subclass in a different package (such
as the current instance of packageB.InDifferentPackage here) does
not have access to the iProtected of every instance of packageA
.Parent. Rather, an instance of the subclass may access the one
instance of iProtected that the subclass instance inherits by virtue of
extending Parent. The current instance of InDifferentPackage may
access its own iProtected, as in line 10. Of course, line 11 compiles
because it represents access to a public feature.
16 Java 2 Exam Notes
The last example in this section illustrates access and inner classes.
Consider the following superclass:
1. package packageX;
2.
3. public class Parent {
4. protected class Prot { public Prot() {} }
5. }
6. package packageY;
7. import packageX.*;
8.
9. public class Child extends Parent {
10. void xxx() {
11. Prot p = new Prot();
12. }
13. }
synchronized
volatile
final
The final keyword conveys the sense that a feature may not be
altered. Classes, methods, and variables may be final. A final class
may not be subclassed, and a final method may not be overridden.
The final keyword, unlike the access modifiers, can be applied to the
automatic variables and arguments of a method. A final automatic
variable may not be written after it is initialized. A final argument
may not be written at all. The following code sample illustrates final
data in a method:
abstract
The abstract keyword conveys the sense that a feature is somehow
incomplete and cannot be used until further information is provided.
Classes and methods may be final.
When you declare a method to be abstract, the class that contains the
method has no definition for that method. Instead, the method defi-
nition is deferred to one or more subclasses. After the method name
18 Java 2 Exam Notes
static
Data and methods may be declared static. Static features belong to
the class in which they are declared, rather than belonging to individ-
ual instances of that class.
The static method may only access those variables of its owning
class that are declared static; the class’s nonstatic variables may
not be accessed.
The static method may only call those methods of its owning class
that are declared static; the class’s nonstatic methods may not be
called.
The static method has no this reference.
The static method may not be overridden.
It is legal for a class to contain static code that does not exist within
a method body. Such code is known as static initializer code; it is exe-
cuted when the owning class is loaded, after static variables are allo-
cated and initialized. Static initializer code has no this reference. The
code listed below illustrates a static initializer:
7. System.out.println(“i = “ + i);
8. }
9. }
synchronized
The synchronized modifier applies only to code. The modifier
requires a thread to acquire a lock before executing the code. This
topic is covered in Chapter 7, “Threads.”
The volatile modifier applies only to class variables. Volatile data is pro-
tected from certain kinds of corruption under multithreaded conditions.
Chapter 1 Declarations and Access Control 21
Exam Essentials
Understand the four access modes and the corresponding key-
words. You should know the significance of public, default, pro-
tected, and private access when applied to data, methods, and inner
classes.
Understand how Java classes are organized into packages, so that you
can understand the default and protected modes. A package is a
namespace containing classes. You should know how the default and
protected modes grant access to classes within the same package.
Know the effect of declaring a final class, variable, or method. A
final class cannot be subclassed; a final variable cannot be modified
after initialization; a final method cannot be overridden.
Know the effect of declaring an abstract class or method. An
abstract class cannot be instantiated; an abstract method’s definition
is deferred to a subclass.
Understand the effect of declaring a static variable or method.
Static variables belong to the class; static methods have no this
pointer and may only access static variables and methods of their
class.
Know how to reference a static variable or method. A static fea-
ture may be referenced through the class name or through a reference
to any instance of the class.
Be able to recognize static initializer code. Static initializer code
appears in curly brackets with no method declaration. Such code is
executed once, when the class is loaded.
Static method A static method may only access the static variables
and methods of its class.
Static variable Static data belongs to its class, rather than to any
instance of the class. Static variables are allocated and initialized at
class-load time.
Sample Questions
1. Which of the following are access modifiers?
A. abstract
B. final
C. private
D. protected
E. public
F. static
G. synchronized
Answer: C, D, and E. The other modifiers are not access modi-
fiers. The fourth access mode, “default,” has no corresponding
modifier keyword.
Critical Information
A default constructor is a constructor with an empty argument list.
For example, the default constructor for a class named MyClass
would have the following format:
MyClass() { ... }
Chapter 1 Declarations and Access Control 25
Every class must have at least one constructor. If you create a class
that has no explicit constructors, then a default constructor is auto-
matically generated by the compiler. In this case, the access mode of
the constructor depends on the access mode of the class. If the class is
public, the automatically generated constructor is also public. If the
class is not public, the automatically generated constructor has
default access. (Access is slightly different for inner classes, but this
level of detail is not covered on the exam.)
Exam Essentials
Know that the compiler generates a default constructor when a class
has no explicit constructors. When a class has constructor code,
no default constructor is generated.
Know the access mode of the generated constructor. Public for
public classes; default for classes with any other access mode.
Sample Questions
1. What is the prototype for the automatically generated constructor
of the following class?
public class Kat extends Mammal { }
Critical Information
Overloading is reuse of a method name within a class. Overriding is
reuse of a method name in a subclass.
Method Overloading
Overloaded methods share a common name but have different argu-
ment lists. Overloaded methods may have the same or different return
types. Thus, within a single class the following methods may appear
and are examples of legal overloading:
These three methods have the same name and different argument
lists. The access modes and return types are irrelevant.
The new method has the same name and argument list as the method
on line 3, so it is illegal even though it has a different return type.
Method Overriding
When a method is overridden, the version in the subclass must match
the name, argument list, and return type of the version in the super-
class. Compilation fails if the subclass version has the same name and
argument list as the superclass version but has a different return type.
Compilation succeeds if the subclass version has the same name as the
superclass version but has a different argument list, whether or not
the return type is different. However, this is not really method over-
riding; it is overloading of the method inherited from the superclass.
28 Java 2 Exam Notes
Exam Essentials
Know the legal return types for overloaded and overridden methods.
There are no restrictions for an overloaded method; an overriding
method must have the same return type as the overridden version.
Sample Questions
1. If two methods in a single class have the same name and different
argument lists, can they have different return types?
Answer: Yes. As long as the argument lists are different, the
overloading is legal.
2. Is it legal for two methods in a single class to have the same name
and the same argument list, but different return types?
Answer: No. Two methods in a class may not have the same
name and argument list.
3. When is it legal for a method to have the same name and argument
list as a method in the superclass?
Answer: If the two methods have the same return type, then we
have an example of legal overriding. If the return types are dif-
ferent, the code will not compile.