Home > Articles > Programming > Java

This chapter is from the book

This chapter is from the book

Statements Updated for Enumerations

Two statements have been changed to make them work better with enumerations: the switch statement, and the for statement.

Using a for statement with enums

Language designers want to make it easy to express the concept "Iterate through all the values in this enumeration type". There was much discussion about how to modify the "for" loop statement. It was done in a clever way—by adding support for iterating through all the values in any array.

Here is the new "get all elements of an array" syntax added to the "for" statement.

// for each Dog object in the dogsArray[] print out the dog's name
for (Dog dog : dogsArray ){
    dog.printName();
}

This style of "for" statement has become known as the "foreach" statement (which is really goofy, because there is no each or foreach keyword). The colon is read as "in", so the whole thing is read as "for each dog in dogsArray". The loop variable dog iterates through all the elements in the array starting at zero.

Zermelo-Fränkel set theory and you

Keywords don't have to be reserved words. So keywords don't have to be prohibited for use as identifiers. A compiler can look at the tokens around a keyword and decide whether it is being used as a keyword or an identifier. This is called context-sensitive parsing.

I would have preferred an actual keyword "in" rather than punctuation, but the colon has been used this way in Zermelo-Fränkel set theory by generations of mathematicans. It's just syntactic sugar. And if we've always done something this way, hey, don't not go for it.

Using the new foreach feature, we can now write a very brief program that echoes the arguments from the command line. The command line arguments (starting after the main class name) are passed to main() in the String array parameter. We print it out like this:

public class echo {
    public static void main( String[] args) {
        for (String i : args )
            System. out. println("arg = " + i);
    }
}

Compiling and running the program with a few arguments gives this:

javac -source 1.5 -target 1.5 echo. java

java echo test data here
arg = test
arg = data
arg = here

Note: The final decision on whether to have a "-source 1.5" compiler option and what it should look like had not been made when this book went to press. See the website www.afu.com/jj6 for the latest information. You can set it up in a batch file so you don't have to keep typing it.

The same for loop syntax can be used for enums if you can somehow get the enum constants into an array. And that's exactly how it was done. Every enum type that you define automatically brings into existence a class method called values().

The values() method for enums

The values() method is created on your behalf in every enum you define. It has a return value of an array, with successive elements containing the enum values. That can be used in for loops as the example shows:

for (Bread b : Bread.values() ) {

    // b iterates through all the Bread enum constants
    System.out.println("bread type = " + b);
}

In addition to the enum constants that you write, the enum type can contain other fields. The values() method is one of them. Bread.values() is a call to a class method belonging to the Bread enum. The method is invoked on the enum class type Bread, not on an instance, so we can conclude it must be a class method.

You can even iterate through a subrange of an enum type. The class java.util. EnumSet has a method called range() that takes various arguments, and returns a value suitable for use in the expanded for statement.

You would use it like this:

public class Example {
   enum Month {Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }
   public static void main(String[] args) {

      for (Month m : java.util.EnumSet.range(Month.Jun, Month.Aug) )
                 System.out.println("summer includes: " + m );
   }
}

When compiled and run, that prints:

summer includes: Jun
summer includes: Jul
summer includes: Aug

The method range() belonging to class EnumSet returns, not an array (as you might guess), but an object of type EnumSet. The "for" statement has been modified to accept an array or an EnumSet in this kind of loop (it can accept a Collection class too).

Modifying the "for" loopto allow a special type here was done as a concession to performance improvement. An EnumSet is a collection class that can hold multiple enum constants from any one enum type. They don't have to be a consecutive range of enum constants. If there are 64 or fewer enum constants in the set, it will store the set as a long word of bits, and not as an array of references. This makes it very fast to tell if an enum constant is in or out of the set, and very fast to iterate through a range of enum constants.

Using a switch statement with enums

You can now use an enum type in a "switch" statement (Java's name for the case statement used in other languages). Formerly, the switch expression had to be an int type. Here's an example that uses an enum in a switch statement.

Bread myLoaf = Bread.rye;
int price = 0;

switch (myLoaf) {
    case wholewheat: price = 190;
                     break;

    case     french: price = 200;
                     break;

     case ninegrain: price = 250;
                     break;

           case rye: price = 275;
                     break;
}

System.out.println( myLoaf + " costs " + price);

The "break" statement causes the flow of control to transfer to the end of the switch. Without that, program execution drops through into the next case clause. Running the program gives the output:

rye costs 275

The enum value in the case switch label must be an unqualified name. That is, you must write "rye" and not "Bread. rye". That (unfortunately) contrasts with an assignment to an enum variable. In an assignment:

myLoaf = Bread.rye;

you must use the qualified name Bread.rye, unless you import the type name.

Dropping the need to qualify names—import

We mentioned above that you must use the qualified name, such as Bread.rye, unless you import the type name. This section explains how to do that, using a wordy example from the digital clock in Chapter 2. That program had a statement saying:

this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

The statement is setting how the window should behave when the user clicks on the close icon on the title bar. There's a choice of four alternatives, ranging from "ignore it" to "terminate the program". The alternatives are represented by integer constants in class WindowConstants, which is part of package javax.swing. Here is the source code from the Java run-time library, defining those constants:

public static final int DO_NOTHING_ON_CLOSE = 0;
public static final int HIDE_ON_CLOSE = 1;
public static final int DISPOSE_ON_CLOSE = 2;
public static final int EXIT_ON_CLOSE = 3;

Those could be better expressed as an enum type, but this code was written long before Java supported enum types. It would be nice if the programmer using those constants didn't have to mention the lengthy names of the package and subpackage they come from.

That's exactly what the "import" statement gives you. The import statement has been part of Java from the beginning. It lets a programmer write this:

import java.swingx.*;   // import all classes in package java.swingx

or

import java.swingx.WindowConstants;  // import this class

The "import" statements (if any) appear at the top of the source file, right after the optional line that says what package this file belongs to. The imports apply to all the rest of the file. The import statement brings into your namespace one or more classes from a package. The import with the asterisk is meant to be like a wildcard in a file name. It means "import all classes from the package". So "import javax.swing.*;" means you can drop the "javax.swing" qualifier from class names from the javax.swing package.

The second version, importing a single class, means that you do not have to qualify that one class with its package name at each point you mention it.

Import is purely a compile time convenience feature. It does not make a class visible that was not visible before. It does not make any change to the amount of code that is linked into your executable. It just lets you refer to a class without qualifying it with the full name of the package it is in.

Either of these imports would allow us to cut down our "close window" statement to:

this.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );

Using "import static"

We are still required to mention the class name, and this is where the new feature of static import comes in. JDK 1.5 adds the ability to import the static members from a class, or the enum values from an enum type. It is analogous to the ordinary import statement, and it looks like this:

import static qualified_class_name.*;
   

or

import static qualified_enum_name.*;
   

So you can now write

import static javax.swing.WindowConstants.*;
   /* more code */
  this.setDefaultCloseOperation(EXIT_ON_CLOSE);

The this can be implicit, so what started out as

this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

can now be written as

import static javax.swing.WindowConstants.*;
  //  lots more code here
setDefaultCloseOperation(EXIT_ON_CLOSE);

Similarly, using enums and static import we can write:

import static mypackage.Bread.* ;
      // more code here

       Bread myLoaf = rye;

You can import just one enum value or static member, by appending its name instead of using the "*" to get all of them. Don't forget that to compile anything with the new JDK 1.5 features, you need to use these options on the command line:

javac -source 1.5 -target 1.5 sourcefiles.java
   

You can use import static on the System class to shorten the name of the utility that does console I/O. Before import static, I used to create an alias like this:

java.io.PrintStream o = System.out;
o.println("hello Bob");

Now you can "import static" instead.

import static java.lang.System.out; /* more code omitted */
out.println("hello Bob");

The compiler is quite capable of figuring out whether you are importing a static member or a classname within a package, so the "import static" keywords could have been left as just the old "import" keyword. It was considered better to remind the programmer that only static members can be imported, not instance members.

What if you import static WarmColors and Fruits? You can do this (they will need to be in a named package, not the default anonymous package used in the examples). But any place where you use one of the named constants whose name is duplicated, you will have to provide the full qualified name:

Fruit f = Fruit.peach;
Fruit f2 =      apple;  // unique name, so no qualifier needed.

At this point we've covered everything relating to enums that you'll see 99% of the time. There is some more material, but you can safely skip the rest of the chapter, and return when you have some specific enum construct to decode.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020