Home Application-development Oracle Certified Associate, Java SE 7 Programmer Study Guide

Oracle Certified Associate, Java SE 7 Programmer Study Guide

By Richard M. Reese
books-svg-icon Book
Subscription
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
Subscription
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Getting Started with Java
About this book

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.

"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.

"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.

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.

Publication date:
August 2012
Publisher
Packt
Pages
332
ISBN
9781849687324

 

Chapter 1. Getting Started with Java

This chapter familiarizes you with basic elements of Java and how to write a simple Java program. A comprehensive understanding of the Java development environment is achieved through simple explanations of the application development process. A Java console program is provided that serves as a starting point and a reference point for this discussion.

In this chapter we will examine:

  • What Java is

  • The object-oriented development process

  • Types of Java applications

  • The creation of a simple program

  • The definition of classes and interfaces

  • Java Application Development

  • Java environment

  • Java documentation techniques

  • The use of annotations in Java

  • The core Java packages

 

Understanding Java as a technology


Sun Microsystems developed the original specifications for the language in the mid 1990s. Patrick Naughton, Mike Sheridan, and James Gosling were the original inventors of Java and the language was called Oak at the beginning.

Java is a full-fledged object-oriented programming language. It is platform independent and is normally interpreted rather than compiled like C/C++. It is syntactically and structurally modeled after C/C++ and performs various compile-time and run-time checking operations. Java performs automatic memory management that helps to greatly reduce the problem of memory leaks found in other languages and libraries that dynamically allocate memory.

Java supports many features that, at its time of conception, were not found directly in other languages. These features include threading, networking, security, and Graphical User Interface (GUI) development. Other languages could be used to support these capabilities, but they were not integrated in the language to the extent that it was done with Java.

Java uses an independent bytecode that is architecture neutral. That is, it is designed to be machine independent. The byte codes are interpreted and executed by a Java Virtual Machine (JVM). All of its primitive data types are fully specified, as we will see in Chapter 3, Decision Constructs. The various releases of the Java Development Kit (JDK) and other significant moments are depicted in the following timeline diagram:

Object-oriented software development

Let's digress for a moment and consider why we are using Java at all. One of the most significant aspects of Java is that it is an object-oriented (OO) language. OO technologies are a popular paradigm for developing applications. This approach models an application around a series of real world objects, such as an employee or a ship. In order to solve a problem, it is useful to think of the real world objects that make up the problem domain.

The OO approach is based on three distinct activities:

  • Object Oriented Analysis (OOA ): This is concerned with determining the functionality of the system, that is, what should the application do

  • Object Oriented Design (OOD): This is concerned with how the architecture supports the functionality of the application

  • Object Oriented Programming (OOP): This is concerned with the actual implementation of the application

The products of the analysis and design steps are often referred to as analysis and design artifacts. While there may be several different types produced, the one of most interest to the OOP step is called the class diagram . The following diagram shows a partial class UML diagram depicting two classes: Customer and CustomerDriver. In the A simple Java application section, we will examine the code for these classes. The Unified Modeling Language (UML) is a widely used OO technique used to design and document an application. A class diagram is one of the end products of the technique and is used by programmers to create the application:

Each box represents a class and is divided into three sections:

  • The first section at the top of the box is the name of the class

  • The second section lists the variables that make up the class

  • The last section lists the class methods

The symbols preceding the variable and method names specify the visibility of these class members. The following are the class diagram symbols used:

  • -: Private

  • +: Public

  • #: Protected (used with inheritance)

Normally, a class diagram consists of many classes and is interconnected with annotated lines showing the relationship between the classes.

The class diagram is intended to clearly show what objects make up the system and how they interact. Once a class diagram is complete it can be implemented using an OOP language such as Java.

Note

The object-oriented approach is typically used for medium-scale to large-scale projects, where many developers must communicate, and work together, to create an application. For smaller projects involving only a few programmers, such as the one dealt with in most programming classes, the object-oriented approach is not normally used.

OOP principles

While there is some disagreement in what actually makes a programming language an OOP programming language, there are generally three underlying principles that must be supported by an OOP language:

  • Data encapsulation

  • Inheritance

  • Polymorphism

Data encapsulation is concerned with hiding irrelevant information from the users of a class and exposing the relevant. The primary purpose of data encapsulation is to reduce the level of software development complexity. By hiding the details of what is needed to perform an operation, the use of that operation is simpler. How to achieve data encapsulation in Java is explained in the Access modifiers section, later in this chapter.

Data encapsulation is also used to protect the internal state of an object. By hiding the variables that represent the state of an object, modifications to the object are controlled through the methods. Any changes to the state are verified by the code in the methods. Also, by hiding variables, sharing of information between classes is eliminated. This reduces the amount of coupling possible in an application.

Inheritance describes the relationship between two classes such that one class re-uses the capabilities of another class. This enables the re-use of software resulting in a more productive developer. Inheritance is covered in detail in Chapter 7, Inheritance and Polymorphism.

The third principle is polymorphism and its primary concern is to make the application more maintainable and extendable polymorphism behavior is where the behavior of one or identical methods is dependent upon the object it is executing against. For example, a person object and a square object can both have a draw method. What it draws depends on the object the method is executed against. Polymorphism is discussed in Chapter 7, Inheritance and Polymorphism.

These principles are summarized in the following table:

Principle

What it is

Why we use it

How to do it

Data encapsulation

Technique that hides information from the users of that class

To reduce the level of software development complexity

Use access modifiers such as public, private, and protected

Inheritance

Technique to allow a derived or child class to use parts of a base or parent class

To promote the re-use of the software

Use the extends keyword

Polymorphism

Technique which supports different behavior of methods that is dependent on the object the method is executing against

To make an application more maintainable

Inherent to the Java language

The implements keyword is used in support of polymorphic behavior as is explained in Chapter 7, Inheritance and Polymorphism.

Examining the types of Java applications

There are several types of Java applications. These types have allowed Java to flourish in a number of different areas and contributed to Java becoming a very popular programming language. Java is used to develop the following:

  • Console and window applications

  • Server-based web applications supported by Servlets, JSPs, JSF, and other JEE standards

  • Applets that execute within a browser

  • Embedded applications

  • Componentized building blocks using JavaBeans

While a basic understanding of the types of Java applications is useful in putting Java into context, it also helps to be able to recognize the basic code for these applications. You may not completely understand all of the ins and outs of these application types, but it is useful to see simple code examples.

Reading the code goes a long way towards understanding a language and a specific program. Throughout the book we will use numerous examples to illustrate and explain various aspects of Java. The basic types of Java applications are shown below by presenting short code snippets that are central to that application type.

A simple console application consists of a single class with a main method, as shown in the following code snippet:

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

We will examine this type of application in more depth.

Applets are normally embedded within an HTML page and offer a means of achieving client-side execution of a code. It does not have a main method but uses a series of callback methods used by the browser to manage the application. The following code provides an idea of the general appearance of an applet:

import java.applet.*;
import java.awt.Graphics;

public class SimpleApplet extends Applet {

   @Override
   public void init() {
      // Initialization code
   }

   @Override
   public void paint( Graphics g ) {
      // Display graphics
   }
}

The @Override annotation is used to ensure that the method that follows is actually overridden. This is discussed in more detail in the Annotations section of this chapter.

A servlet is a server-side application which renders an HTML page sent to a client. A doGet or doPut method responds to client-side request. The out variable in the following example represents the HTML page. The println methods are used to write the HTML code, as shown in the following code snippet:

class Application extends HttpServlet {
   public void doGet(HttpServletRequest req,
            HttpServletResponse res)
            throws ServletException, IOException {
      res.setContentType("text/html");

      // then get the writer and write the response data
      PrintWriter out = res.getWriter();
      out.println(
         "<HEAD><TITLE> Simple Servlet</TITLE></HEAD><BODY>");
      out.println("<h1> Hello World! </h1>");
      out.println(
         "<P>This is output is from a Simple Servlet.");
      out.println("</BODY>");
      out.close();
   }
}

A JavaServer Page (JSP) is actually a disguised Servlet. It provides a more convenient way of developing web pages. The following example uses a JavaBean to display "Hello World" on the web page. The JavaBean is detailed in the following example:

<html>
<head>
   <title>A Simple JSP Page</title>
</head>
<body>
Hello World!<br/>
    
<%
   // This is a scriptlet that can contain Java code
%>
<hr>
<jsp:useBean id="namebean" class="packt.NameBean" scope="session" >
<jsp:setProperty name="namebean" property="name" value=" Hello world"" />
</jsp:useBean>
<h1> <jsp:getProperty name="namebean" property="name" /></h1>
</body>
</html>

JavaBeans are building blocks for shared application functionality. They are frequently designed to be used in multiple applications and follow a standard naming convention. The following is a simple JavaBean designed to hold a name (it was used in the previous JSP page):

package packt;
public class NameBean {
  
  private String name= "Default Name"";
  
  public String getName() {
     return this.name;
  }
  public void setName(String name) {
     this.name = name;
  }
}

Enterprise Java Beans (EJB) are components designed to be used in a client/server configuration from a web server. This is a fairly specialized topic that is not relevant to the associate level of certification.

There are several other types of Java technologies such as JSF and Facelets that are a part of JEE. These are improvements over the older Servlet and JSP technologies used to develop web pages.

In this book we will only use simple Java console applications. This type of application is more than sufficient to explain the essence of Java.

 

Exploring the structure of a Java console program


Let's start with a simple Java program and then use it to explore many of the basic facets of Java. First, a Java application consists of one or more files located somewhere within a filesystem. The name of the files and their locations are both important, as we will see shortly.

Note

You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

A simple Java application

Our simple program defines a Customer class and then uses it in the CustomerDriver class as follows:

package com.company.customer;

import java.math.BigDecimal;
import java.util.Locale;

public class Customer {
  private String name;
  private int accountNumber;
  private Locale locale;
  private BigDecimal balance;
  
  public Customer() {
    this.name = "Default Customer";
    this.accountNumber = 12345;
    this.locale = Locale.ITALY;
    this.balance = new BigDecimal("0");
  }
  
  public String getName() {
    return name;
  }
  public void setName(String name) throws Exception {
    if(name == null) {
         throw new IllegalArgumentException(
            "Names must not be null");
    } else {
      this.name = name;
    }
  }
  public int getAccountNumber() {
    return accountNumber;
  }

  public void setAccountNumber(int accountNumber) {
    this.accountNumber = accountNumber;
  }
  
  public BigDecimal getBalance() {
    return balance;
  }

  public void setBalance(float balance) {
    this.balance = new BigDecimal(balance);
  }
  
   public String toString() {
      java.text.NumberFormat format =
         java.text.NumberFormat.getCurrencyInstance(locale);
      StringBuilder value = new StringBuilder();
      value.append(String.format("Name: %s%n", this.name));
      value.append(String.format("Account Number: %d%n", 
            this.accountNumber));
      value.append(String.format("Balance: %s%n",
            format.format(this.balance)));
      return value.toString();
    }  
}


package com.company.customer;

public class CustomerDriver {

  public static void main(String[] args) {
      // Define a reference and creates a new Customer object
    Customer customer;      
    customer = new Customer();
    customer.setBalance(12506.45f);
    System.out.println(customer.toString());
  }

The details of how to compile and execute this application are provided in the Developing Java applications without an IDE section. When this application is executed you will get the following output:

Name: Default Customer
Account number: 12345
Balance: € 12.506,45

Understanding the application in detail The following sections detail the significant aspects of the example program. These will be elaborated upon later in more detail in the chapters that follow. Notice, that there are two classes in this application. The CustomerDriver class contains the main method and is executed first. An instance of the Customer class is created and used within the main method.

Package

The package statement specifies the class' com.company.customer package. Packages provide a means of grouping similar classes, interfaces, enumerations, and exceptions together. They are discussed in more depth in the Packages section in Chapter 9, The Java Application.

Import

The import statement indicates which packages and classes are used by the class. This allows the compiler to determine whether the package's members are used correctly. Packages need to be imported for all classes, with the exception of the following classes:

  • Found in the java.lang package

  • Located in the current package (com.company.customer, in this case)

  • Explicitly marked such as java.text.NumberFormat as used in the Customer class' toString method

    Note

    The import statement informs the compiler of which packages and classes are used by an application and how they can be used.

The Customer class

The first word of the class definition was the keyword, public, which is a part of the support Java provides for object-oriented software development. In this context, it specifies that the class is visible outside the package. While not required, it is frequently used for most classes and brings us to the second keyword, class, which identifies a Java class.

Instance variables

Four private instance variables were declared next. The use of the private keyword hides them from users of the class. The Locale class supports applications that can work transparently internationally. BigDecimal is the best way of representing currency in Java.

Methods

By making these instance variables private, the designer restricts access to the variables. They are then only accessible through public methods. The combination of private variables and public methods is an example of data encapsulation. If the instance variables are made public instead, other users can directly access the variables. This would improve the efficiency of the program, but may hinder future maintenance efforts. It would be more difficult to change these variables and enforce any sort of validation checks on the changes to the variables.

A series of getter and setter methods were present to return and set the values associated with the private instance variables. This exposes them in a controlled manner. The use of getter and setter methods is a standard approach to achieve encapsulation. For example, trying to assign a null value to a name would throw a IllegalArmumentException exception. These types of methods are discussed in the Method declaration section.

The toString method returns a string representing an instance of a customer. In this case the name, account number, and a localized version of the balance is returned. The use of the StringBuilder class is discussed in Chapter 2, Java Data Types and Their Usage.

Note

Methods are found within classes and classes are found within packages.

The CustomerDriver class' main method

The CustomerDriver class is referred to as the driver or controller class. Its purpose is to have a main method that will create and use other classes.

In a Java application the main method is the first method to be executed. If the application consists of multiple classes, normally only one class has a main method. A Java application typically needs only one main method.

In the main method, a new customer is created, a balance is set and then the customer is displayed. A C++ style comment was added to statements to document the declaration and creation of a customer. This was the line beginning with the double forward slashes (//). Comments are explained in detail in the Comments section.

Note

The first method that executes in a Java console application is the main method.

 

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.

 

Investigating the Java application development process


Java source code is compiled to intermediate bytecode. The bytecode is then interpreted at runtime on any platform that has a Java Virtual Machine (JVM). However, this statement is somewhat misleading as Java technology will often compile bytecode directly to machine code. There have been numerous Just-In-Time compiler improvements that speed up the execution of Java applications that often will run nearly as fast as, or sometimes even faster than, natively-compiled C or C++ applications.

Java source code is found in files that end with a .java extension. The Java compiler will compile the source code to a bytecode representation and store these bytecodes in a file with a .class extension.

There are several Integrated Development Environments (IDE) used to support the development of Java applications. A Java application can also be developed from the command line using basic tools from the Java Development Kit (JDK).

A production Java application is normally developed on one platform and then deployed to another. The target platform needs to have a Java Runtime Environment (JRE) installed on it in order for the Java application to execute. There are several tools that assist in this deployment process. Typically, a Java application is compressed in a Java Archive (JAR) file and then deployed. A JAR file is simply a ZIP file with a manifest document embedded within the JAR file. The manifest document often details the content and the type of JAR file being created.

Compiling a Java application

The general steps used to develop a Java application include:

  • Create the application using an editor

  • Compile it using the Java compiler (javac)

  • Execute it using the Java interpreter (java)

  • Optionally debug the application as required using a Java debugger

This process is summarized in the following diagram:

Java source code files are compiled to bytecode files. These bytecode files have a .class extension. When a Java package is distributed, the source code files are not normally stored in the same location as the .class files.

SDK file structure

The Java Software Development Kit (SDK) can be downloaded and used to create and execute many types of Java applications. The Java Enterprise Edition (JEE) is a different SDK and is used to develop enterprise applications typified by web-based applications. The SDK also known as the Java 2 Enterprise Edition (J2EE) and you may see it referenced as J2EE. Here, we will only deal with the Java SDK.

While the actual structure of the SDK distribution will vary by release, the typical SDK consists of a series of directories, listed as follows:

  • bin: This contains the tools used for developing a Java application including the compiler and JVM

  • db: This is the Apache Derby relational database

  • demo: This contains a series of demonstration applications

  • include: This contains header files used to interact with C applications

  • jre: This is a JRE used by the JDK

  • sample: This contains sample code for various features of Java

The SDK may include the actual source code for the core classes. This is usually found in the src.zip file located under the JAVA_HOME root directory.

IDE file structure

Each IDE has a preferred way of organizing the files that make up an application. These organization schemes are not always hard and fast but those presented here are the common ways of arranging the files.

For example, a simple application in the Eclipse IDE consists of two project files and three sub-directories. These files and directories are listed as follows:

  • .classpath: This is an XML file containing the classpath-related information

  • .project: This is an XML document describing the project

  • .settings: This is a directory containing the org.eclipse.jdt.core.prefs file which specifies compiler preferences

  • bin: This is used to contain the package file structure and the application's class files

  • src: This is used to contain the package file structure and the application's source files

This organization scheme is used by the development tools. The tools often include editors, compilers, linkers, debuggers, and others. These languages frequently use a Make tool to determine which files need to be compiled or otherwise manipulated.

Developing Java applications without an IDE

In this section we will demonstrate how to compile and execute a Java application on a Windows platform using Java 7. The approach is very similar to that used for other operating systems.

Before we can compile and execute the sample program we need to:

  • Install the JDK

  • Create the appropriate file structure for the application

  • Create the files to hold our classes

The latest version of the JDK can be found at http://www.oracle.com/technetwork/java/javase/downloads/index.html. Download and install the version that meets your needs. Note the location of the installation, as we will use this information shortly.

As explained earlier, the Java classes must be located in a specific file structure as mirrored in its package name. Create a file structure somewhere in your filesystem that has a top-level directory called com under which is a directory called company and then under the company directory, a directory called customer.

In the customer directory create two files called Customer.java and CustomerDriver.java. Use the corresponding classes as found earlier in the A simple Java application section.

The JDK tools are found in the JDK directory. When the JDK is installed, the environmental variables are normally set up to allow the successful execution of the JDK tools. However, it is necessary to specify the location of these tools. This is accomplished using the set command. In the following command, we set the path environmental variable to reference C:\Program Files\Java\jdk1.7.0_02\bin directory, which was the most recent release at the time this chapter was written:

set path= C:\Program Files\Java\jdk1.7.0_02\bin;%path%

This command prefixes the path to the bin directory in front of any previously assigned paths. The path environmental variable is used by the operating system to look for the command that is executed at the command prompt. Without this information, the operating system is not aware of the location of the JDK commands.

To compile the program using the JDK, navigate to the directory above the com directory. As the classes used as part of this application are part of the com.company.customer package we need to:

  • Specify the path in the javac command

  • Execute the command from the directory above the com directory

As there are two files that make up this application we need to compile both of them. This can be done using two separate commands as follows:

javac com.company.customer.Customer.java
javac com.company.customer.CustomerDriver.java

Or, it can be done using a single command and the asterisk wild card character as follows:

javac com.company.customer.*.java

The output of the compiler is a bytecode file with the name CustomerDriver.class. To execute the program, invoke the Java interpreter with your class file, as shown in the following command. The class extension is not included and its inclusion as part of the filename will result in an error:

java com.company.customer.CustomerDriver

The output of your program should be as follows:

Name: Default Customer
Account number: 12345
Balance: € 12.506,45

Java environment

The Java environment is the operating system and file structure used to develop and execute Java applications. Earlier, we examined the structure of the JDK which are part of the Java environment. Associated with this environment are a series of environmental variables that are used from time-to-time to facilitate various operations. Here, we will examine a few of them in more detail:

  • CLASSPATH

  • PATH

  • JAVA_VERSION

  • JAVA_HOME

  • OS_NAME

  • OS_VERSION

  • OS_ARCH

These variables are summarized in the following table:

Name

Purpose

Example

CLASSPATH

Specifies the root directory for classes.

.;C:\Program Files (x86)\Java\jre7\lib\ext\QTJava.zip

PATH

The location of the commands.

 

JAVA_VERSION

The version of Java to use.

<param name="java_version" value="1.5.0_11">

JAVA_HOME

The location of the Java directory.

C:\Program Files (x86)\Java\jre6\bin

OS_NAME

The name of the operating system.

Windows 7

OS_VERSION

The version of the operating system

6.1

OS_ARCH

The operating system architecture

AMD64

The CLASSPATH environmental variable is used to identify the root directory of the packages. It is set as follows:

  c:>set CLASSPATH=d:\development\increment1;%CLASSPATH%

The CLASSPATH variable only needs to be set for non-standard packages. The Java compiler will always implicitly append the system's class directories to CLASSPATH. The default CLASSPATH is the current directory and the system's class directories.

There are many other environmental variables associated with an application. The following code sequence can be used to display a list of these variables:

    java.util.Properties properties = System.getProperties();
    properties.list(System.out);

A partial display of the output of this code sequence is as follows:

-- listing properties --
java.runtime.name=Java(TM) SE Runtime Environment
sun.boot.library.path=C:\Program Files\Java\jre7\bin
java.vm.version=22.0-b10
java.vm.vendor=Oracle Corporation
java.vendor.url=http://java.oracle.com/
path.separator=;
java.vm.name=Java HotSpot(TM) 64-Bit Server VM

Annotations

Annotations provide information about a program. This information does not reside in the program and does not affect its execution. Annotations are used to support tools such as the compiler and during the execution of the program. For example, the @Override annotation informs the compiler that a method is overriding a base class method. If the method does not actually override the base class method because it is misspelled, the compiler will generate an error.

Annotations are applied to elements of the application such as a class, method, or field. It begins with the at sign, @, is followed by the name of the annotation, and optionally a list of values enclosed in a set of parentheses.

Common compiler annotations are detailed in the following table:

Annotation

Usage

@Deprecated

Used by the compiler to indicate that the element should not be used

@Override

The method overrides the base class method

@SuppressWarnings

Used to suppress specific compiler warnings

Annotations can be added to an application and used by the third-party tools for specific purposes. It is also possible to write your own annotations when needed.

Note

Annotations are useful in conveying information about an application to tools and the run-time environment

Java class libraries

Java includes a number of libraries of classes that support the development of applications. These include the following, among others:

  • java.lang

  • java.io

  • java.net

  • java.util

  • java.awt

These libraries are organized in packages. Each package holds a set of classes. The structure of a package is reflected in its underlying file system. The CLASSPATH environmental variable holds the location of packages.

There are a core set of packages that are part of the JDK. These packages provide a crucial element in the success of Java by providing easy access to a standard set of capabilities that were otherwise not readily available with other languages.

The following table shows a list of some of the more commonly used packages:

Package

Usage

java.lang

This is the collection of the basic language types. It includes the root classes, Object and Class, and other items such as threads, exceptions, wrapper, and other fundamental classes.

java.io

Includes streams and random access files.

java.net

Supports sockets, telnet interfaces, and URLs.

java.util

Supports container and utility classes such as Dictionary, HashTable, and Stack. Encoder and decoder techniques such as Date and Time can also be found in this library.

java.awt

Contains the Abstract Windowing Toolkit (AWT) that contains classes and methods that support a Graphical User Interface (GUI). It includes classes for events, colors, fonts, and controls.

 

Summary


In this chapter we examined the essential aspects of Java and a simple Java console application. From a certification standpoint we looked at the structure of a class and a Java application that uses the main method.

We also introduced a number of additional topics that will be covered in more detail in later chapters. This includes the creation of objects and their manipulation, the use of strings and the StringBuilder class, instance and static members of a class, and the use of signatures in the overloading and overriding of a method.

With this foundation we are ready to move on to Chapter 2, Java Data Types and Their Usage, where we will examine the nature of variables and how they can be used.

 

Certification objectives covered


In this chapter we introduced a number of certification topics that will be discussed in more detail in subsequent chapters. Here we covered the following topics in depth:

  • Define the structure of a Java class (in the Exploring the structure of a class section)

  • Create an executable Java application with a main method (in the Exploring the structure of a Java console program section)

 

Test your knowledge


  1. 1. What will be printed out if the following code is run with the java SomeClass hello world command?

    public class SomeClass{
        public static void main(String argv[])
        {
      System.out.println(argv[1]);
        }
    }

    a. world

    b. hello

    c. hello world

    d. ArrayIndexOutOfBoundsException is thrown

  2. 2. Consider the following code sequence:

    public class SomeClass{
       public int i;
       public static void main(String argv[]){
          SomeClass sc = new SomeClass();
          // Comment line
       }
    }

    Which of the following statements will compile without syntax or runtime errors if they replace the comment line?

    a. sc.i = 5;

    b. int j = sc.i;

    c. sc.i = 5.0;

    d. System.out.println(sc.i);

About the Author
  • Richard M. Reese

    Richard M. Reese has worked in both industry and academia. For 17 years, he worked in the telephone and aerospace industries, serving in several capacities, including research and development, software development, supervision, and training. He currently teaches at Tarleton State University, where he has the opportunity to apply his years of industry experience to enhance his teaching. Richard has written several Java books and a C pointer book. He uses a concise and easy-to-follow approach to the topics at hand. His Java books have addressed EJB 3.1, updates to Java 7 and 8, certification, jMonkeyEngine, natural language processing, functional programming, networks, and data science.

    Browse publications by this author
Oracle Certified Associate, Java SE 7 Programmer Study Guide
Unlock this book and the full library FREE for 7 days
Start now