Book Image

Oracle Certified Associate, Java SE 7 Programmer Study Guide

By : Richard M. Reese
Book Image

Oracle Certified Associate, Java SE 7 Programmer Study Guide

By: Richard M. Reese

Overview of this book

<p>Java SE 7 Associate Programmer certification adds to your qualification as a Java developer. Knowledge of Java is important, but knowing how to write an efficient and productive code adds to your skills and gives you an edge when you are planning to give the certification exam. Coverage of the objectives goes beyond a simple review of certification objectives.</p> <p>"Oracle Certified Associate, Java SE 7 Programmer Study Guide" addresses certification exam objectives and provides discussion and examples to show the best ways of applying Java language features in real world programming. You will gain in-depth understanding of Java by examining how objects are allocated in the heap and how methods are managed in the program stack.<br /><br />"Oracle Certified Associate, Java SE 7 Programmer Study Guide" covers all of the Java SE 7 Associate Programmer certification objectives. It starts with a high level overview of an application’s structure to provide a framework for subsequent chapters. Chapters are organized around common themes with emphasis on memory usage. You will get an in-depth and complete understanding of the run-time Java environment using the illustrations that show the impact of class and method usage on the program stack and heap. <br /><br />Augmenting the coverage of certification objectives are examples of how you can use the classes, methods, and techniques in a productive and sound manner. In addition, sample exam questions are given in each chapter.</p>
Table of Contents (16 chapters)
Oracle Certified Associate, Java SE 7 Programmer Study Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface

Exploring the structure of a class


Programming can be thought of as code manipulating data. In Java, code is organized around the following:

  • Packages

  • Classes

  • Methods

Packages are collections of classes with similar functionality. Classes are composed of methods that support the functionality of the class. This organization provides structure to applications. Classes will always be in a package and methods will always be in a class.

Note

If the package statement is not included in a class definition, the class becomes part of a default package which consists of all of the classes in the same directory that doesn't have a package statement.

Classes, interfaces, and objects

A class is the fundamental building block of object-oriented programs. It generally represents a real-world object. A class definition in Java consists of member variable declarations and method declarations. It begins with the class keyword. The body of the class is enclosed with brackets and contains all instance variables and methods:

  class classname {
    // define class level variables
    // define methods
  }

Note

A pair of open and close curly braces constitutes a block statement. This is used in many other parts of Java.

Classes and objects

A class is a pattern or template for creating multiple objects with similar features. It defines the variables and methods of the class. It declares the capabilities of the class. However, before these capabilities can be used, an object must be created. An object is an instantiation of a class. That is, an object is composed of the memory allocated for the member variables of the class. Each object has its own set of member variables.

Note

The following occurs when a new object is created:

  • The new keyword is used to create an instance of a class

  • Memory is physically allocated for the new instance of the class

  • Any static initializers are executed (as detailed in the Java initialization sequence section in Chapter 6, Classes, Constructors, and Methods)

  • A constructor is called to do initialization

  • A reference to the object is returned

The state of an object is typically hidden from the users of the object and is reflected in the value of its instance variables. The behavior of an object is determined by the methods it possesses. This is an example of data encapsulation.

Note

An object is the instantiation of a class. Each instance of a class has its own unique set of instance variables.

Objects in Java are always allocated on the heap. The heap is an area of memory that is used for dynamically allocated memory, such as objects. In Java, objects are allocated in a program and then released by the JVM. This release of memory is called garbage collection and performed automatically by the JVM. An application has little control over this process. The primary benefit of this technique is the minimization of memory leaks.

Note

A memory leak occurs when memory is dynamically allocated but is never released. This has been a common problem with languages such as C and C++, where it is the responsibility of the programmer to manage the heap.

A memory leak can still occur in Java if an object is allocated but the reference to the object is never released when the object is no longer needed.

Constructors

Constructors are used to initialize an object. Whenever an object is created, a constructor executes. A default constructor is the one that has no arguments and is provided automatically for all classes. This constructor will initialize all instance variables to default values.

However, if the developer provides a constructor, the compiler's default constructor is no longer added. The developer will need to explicitly add a default constructor. It is a good practice to always have a default, no-argument constructor.

Interfaces

An interface is similar to an abstract class. It is declared using the interface keyword and consists of only abstract methods and final variables. An abstract class normally has one or more abstract methods. An abstract method is the one that does not have an implementation. It is intended to support polymorphic behavior, as discussed in Chapter 7, Inheritance and Polymorphism. The following code defines an interface used to designate a class as capable of being drawn:

  interface Drawable {
    final int unit = 1;
    public void draw();
  }

Methods

All executable code executes either within an initializer list or a method. Here, we will examine the definition and use of methods. The initializer list is discussed in Chapter 6, Classes, Constructors, and Methods. Methods will always be contained within a class. The visibility of a method is controlled by its access modifiers as detailed in the Access modifiers section. Methods may be either static or instance. Here, we will consider instance methods. As we will see in Chapter 6, Classes, Constructors, and Methods, static methods typically access static variables that are shared between objects of a class.

Regardless of the type of method, there is only a single copy of a method. That is, while a class may have zero, one, or more methods, each instance of the class (an object) uses the same definition of the method.

Method declaration

A typical method consists of:

  • An option modifier

  • A return type

  • The method name

  • A parameter list enclosed in parentheses

  • An optional throws clause

  • A block statement containing the method's statements

The following setName method illustrates these parts of a method:

  public void setName(String name) throws Exception {
    if(name == null) {
      throw new Exception("Names must not be null");
    } else {
      this.name = name;
    }
  }

While the else clause in this example is technically not required, it is a good practice to always use else clauses as it represents a possible execution sequence. In this example, if the if statement's logical expression evaluates to true, then the exception will be thrown and the rest of the method is skipped. Exception handling is covered in detail in Chapter 8, Handling Exceptions in an Application.

Methods frequently manipulate instance variables to define the new state of an object. In a well designed class, the instance variables can typically only be changed by the class' methods. They are private to the class. Thus, data encapsulation is achieved.

Methods are normally visible and allow the user of the object to manipulate that object. There are two ways to classify methods:

  • Getter methods: These methods return the state of an object (also called accessor methods )

  • Setter methods: These are methods that can change the state of an object (also called mutator methods )

In the Customer class, setter and getter methods were provided for all of the instance variables, except for the locale variable. We could have easily included a get and set method for this variable but did not, to conserve space.

Note

A variable that has a get method but not an otherwise visible set method is referred to as a read-only member variable . The designer of the class decided to restrict direct access to the variable.

A variable that has a set method but not an otherwise visible get method is referred to as a write-only member variable . While you may encounter such a variable, they are rare.

Method signature

The signature of a method consists of:

  • The name of the method

  • The number of arguments

  • The types of the arguments

  • The order of the arguments

The signature is an important concept to remember and is used in overloading/overriding methods and constructors as discussed in Chapter 7, Inheritance and Polymorphism. A constructor will also have a signature. Notice that the definition of a signature does not include the return type.

The main method

The examples used in the book will be console program applications. These programs typically read from the keyboard and display the output on the console. When a console application is executed by the operating system, the main method is executed first. It may then execute other methods.

The main method can be used to pass information from the command line. This information is passed to the arguments of the main method. It consists of an array of strings representing the program's parameters. We will see this in action in Chapter 4, Using Arrays and Collections.

There is only one form of the main method in Java, shown as follows:

    public static void main(String[] args) {
       // Body of method
    }

The following table shows elements of the main method:

Elements

Meaning

public

The method is visible outside the class.

static

The method can be invoked without creating an object of the class type.

void

The method does not return anything.

args

An array of strings representing the arguments passed.

Returning a value from an application

The main method returns void, meaning that it is not possible to return a value back to the operating system as part of the normal method invocation sequence. However, it is sometimes useful to return a value to indicate whether the program terminated successfully or not. This is useful when the program is used in a batch type operation where multiple programs are being executed. If one program fails in this execution sequence, then the sequence may be altered. Information can be returned from an application using the System.exit method. The following use of the methods will terminate the application and return a zero to the operating system:

    System.exit(0);

Note

The exit method:

  • Forces the termination of all of the application's threads

  • Is extreme and should be avoided

  • Does not provide an opportunity to gracefully terminate the program

Access modifiers

Variables and methods can be declared as one of four types, shown in the following table:

Access type

Keyword

Meaning

Public

public

Access is provided to users outside the class.

Private

private

Restricts access to members of the class.

Protected

protected

Access is provided to classes that inherit the class or are members of the same package.

Package scoped

none

Access is provided to members of the same package.

Most of the time, a member variable is declared as private and a method is declared as public. However, the existence of the other access types implies other potential ways of controlling the visibility of a member. These usages will be examined in Chapter 7, Inheritance and Polymorphism.

In the Customer class, all of the class variables were declared as private and all of the methods were made public. In the CustomerDriver class, we saw the use of the setBalance and toString methods:

    customer.setBalance(12506.45f);
    System.out.println(customer.toString());

As these methods were declared as public, they can be used with the Customer object. It is not possible to directly access the balance instance variable. The following statement attempts this:

    customer.balance = new BigDecimal(12506.45f);

The compiler will issue a compile-time error similar to the following:

balance has private access in com.company.customer.Customer

Note

Access modifiers are used to control the visibility of application elements.

Documentation

The documentation of a program is an important part of the software development process. It explains the code to other developers and provides reminders to the developers of what and why they did what they did.

Documentation is achieved through several techniques. Here, we will address three common techniques:

  • Comment: This is the documentation embedded in the application

  • Naming conventions: Following the standard Java naming conventions makes an application more readable

  • Javadoc: This is a tool used to generate documentation about an application in the form of HTML files

Comments

Comments are used to document a program. They are not executable and are ignored by a compiler. Good comments can go a long way to make a program more readable and maintainable. Comments can be grouped into three types—C style, C++ style, and Java style, as summarized in the following table:

Type of Comment

Description

Example

C style

The C style comment uses a two character sequence at the beginning and the end of a comment. This type of comment can extend across multiple lines. The beginning character sequence is a /* while the ending sequence consists of */.

  /* A multi-line comment
     …
  */

  /* A single line comment */

C++ style

The C++ style comment begins with two forward slashes and the comment continues until the end of the line. Essentially everything from the // to the end of the line is treated as a comment.

  // The entire line is a comment
  int total;	// Comment used to clarify variable
  area = height*width; 	// This computes the area of a rectangle

Java Style

The Java style is identical in syntax to the C style comment, except that it starts with /** instead of /*. In addition, special tags can be added within a Java-style comment for documentation purposes. A program called javadoc will read in the source file, which uses these types of comments, and generate a series of HTML files documenting the program. See the Using Javadocs section for more detail.

    /**
     * This method computes the area of a rectangle
     *
     * @param height	The height of the rectangle
     * @param width	The width of the rectangle
     * @return		The method returns the area of a rectangle
     *
     */
   public int computeArea(int height, int width)  {
      return height * width;
   }

Java naming conventions

Java uses a series of naming conventions to make the programs more readable. It is recommended that you always follow this naming convention. By doing so:

The Java naming conventions' rules and examples are shown in the following table:

Element

Convention

Example

Package

All letters in lowercase.

com.company.customer

Class

First letter of each word is capitalized.

CustomerDriver

Interface

First letter of each word is capitalized.

Drawable

Variable

First word is not capitalized but the subsequent words are capitalized

grandTotal

Method

First word is not capitalized but subsequent words are capitalized. Methods should be verbs.

computePay

Constant

Every letter is uppercase.

LIMIT

Note

Following the Java naming conventions is important in maintaining program readability and to support JavaBeans.

Using Javadocs

The Javadoc tool produces a series of HTML files based on the source code and Javadoc tags embedded in the source code. This tool is also distributed with the JDK. While the following example is not an attempt to provide a complete treatment of Javadocs, it should give you a good idea of what Javadocs can do for you:

public class SuperMath {
   /**
    * Compute PI - Returns a value for PI.
    *    Able to compute pi to an infinite number of decimal 
    *    places in a single machine cycle.
    * @return A double number representing PI
   */

   public static double computePI() {
      //
   }
}

The javadoc command, when used with this class, results in the generation of several HTML files. A part of the index.html file is shown in the following screenshot:

Note

More information on the use and creation of Javadoc files can be found at http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html.