.
.
developers.sun.com java.sun.com
.
    November 1, 2004    

In this Issue

 

Welcome to the Java Technology Fundamentals Newsletter.

This monthly newsletter provides a way for you to learn the basics of the Java programming language, discover new resources, and keep up-to-date on the latest additions to Sun Developer Network's New to Java Programming Center.

- Java Programming Language Basics: Using the Enhanced For-Each Loop
- Making Sense of the Java Class: Class Formatter and Class StringBuilder (JDK 5.0 only)
- Java Bits: Java Tech: The ABCs of Synchronization, Part 1
- Program Challenge
- What's New on Java.net: The new2java Project
- Sun's Online Courses: Designing Graphical User Interfaces in Java Technology
- Sun's Instructor Led Courses: Java Programming Language Workshop
- For More Information: Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

You can receive future issues of this newsletter in HTML or text: https://softwarereg.sun.com/registration/developer/en_US/subscriptions

For more Java technology content, visit these sites:

java.sun.com - The latest Java platform releases, tutorials, and newsletters.

java.net - A web forum for collaborating and building solutions together.

java.com - The marketplace for Java technology, applications and services.

.

Java Programming Language Basics

Using the Enhanced For-Each Loop

A new language construct for the JDK 5.0 platform is the for-each loop. This enhanced for-loop allows you to automatically iterate through the elements of an array or collection. Instead of manually advancing a looping variable yourself, the for-each construct manages this itself. Instead, all you do is specify the collection to iterate through, and a variable to access each element, as shown here:

  for (variable: collection)
    statement

To demonstrate, the following program prints out each element passed in along the command line:

public class Args {
  public static void main(String args[]) {
    for (String element: args) {
      System.out.println(element);
    }
  }
}

Compile it with the JDK 5.0 compiler, and pass in some random set of command-line arguments:

  javac Args.java
  java Args one two three

And... you'll get the provided arguments printed out to standard output, one per line:

  one
  two
  three

While none of this is rocket science, it avoids the more manual code block where you have to update the index variable yourself:

  for (int i=0; i < args.length; i++) {
    System.out.println(args[i]);
  }

The construct "for (variable: collection)" doesn't add any new keywords to the language. Instead, it extends the meaning of the basic for loop. This for-each loop says, for each element in "collection", assign it to the variable "element", and execute the following statement.

The construct works for both arrays and implementations of the Collection interface, like ArrayList, HashSet, and the keys from a Map like a Properties object. To demonstrate, the following program iterates through the System property map [available through System.getProperties()], and displays each key-value pair:

import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class SysProps {
  public static void main(String args[]) {
    Properties props = System.getProperties();
    Set<Map.Entry<Object,Object>> entrySet = props.entrySet();
    for (Map.Entry entry: entrySet) {
      System.out.println(entry.getKey() + " : " +
        entry.getValue());
    }
  }
}

Notice the following line:

    Set<Map.Entry<Object,Object>> entrySet = props.entrySet();

By explicitly saying that the entrySet method of the Properties object returns a Set of Map.Entry objects, the for-each construct doesn't require any casting operations.

    for (Map.Entry entry: entrySet) {

That's the beauty of the Generics capabilities, also added to the J2SE 2, version 5.0 platform.

In the case of using the for-each construct with a Collection, this maps to using the Iterator interface:

  Iterator iter = ...;
  while (iter.hasNext()) {
    Object element = iter.next();
    // process element
  }

The way for-each works is it takes anything that has an iterator() method, and iterates through the elements provided. How does it know to look for an iterator() method?

The new Iterable interface tells it so. In fact, anything that implements the Iterable interface can be used in a for-each loop, including your own classes.

Review what you learned with this online quiz.

.
.

Making Sense of the Java Classes

Class Formatter and Class StringBuilder (JDK 5.0 only)

The Formatter class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such as byte, BigDecimal, and Calendar are supported. Limited formatting customization for arbitrary user types is provided through the Formattable interface.

Formatted printing for the Java programming language is inspired by C's printf. Although the format strings are similar to C, some customizations have been made to accommodate the Java programming language and exploit some of its features. Also, Java's formatting is more strict than C's. For example, if a conversion is incompatible with a flag, an exception isq thrown. In C inapplicable flags are silently ignored. The format strings are thus intended to be recognizable to C programmers, but not necessarily completely compatible with those in C.

Class StringBuilder is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it is faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used instead.

Examples of expected usage:

   StringBuilder sb = new StringBuilder();
   // Send all output to the Appendable object sb
   Formatter formatter = new Formatter(sb, Locale.US);

   // Explicit argument indices may be used to re-order output.
   formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
   // -> " d  c  b  a"

   // Optional locale as the first argument can be used to get
   // locale-specific formatting of numbers.  The precision and 
   // width can be given to round and align the value.
   formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);
   // -> "e =    +2,7183"

   // The '(' numeric flag may be used to format negative numbers 
   // with parentheses rather than a minus sign.  Group separators 
   // are automatically inserted.
   formatter.format("Amount gained or lost since last statement: 
                                       $ %(,.2f", balanceDelta);
   // -> "Amount gained or lost since last statement: 
                                                  $ (6,217.58)"
 

Convenience methods for common formatting requests exist as illustrated by the following invocations:

   // Writes a formatted string to System.out.
   System.out.format("Local time: %tT", Calendar.getInstance());
   // -> "Local time: 13:34:18"

   // Writes formatted output to System.err.
   System.err.printf("Unable to open file '%1$s': %2$s",
                     fileName, exception.getMessage());
   // -> "Unable to open file 'food': No such file or directory"
 

Like C's sprintf(3), Strings may be formatted using the static method String.format:

   // Format a string containing a date.
   import java.util.Calendar;
   import java.util.GregorianCalendar;
   import static java.util.Calendar.*;

   Calendar c = new GregorianCalendar(1995, MAY, 23);
   String s = String.format(
                "Duke's Birthday: %1$tm %1$te,%1$tY", c);
   // -> s == "Duke's Birthday: May 23, 1995"
.
.

Java Bits

Java Tech: The ABCs of Synchronization, Part 1
by Jeff Friesen

Threads may execute in a manner where their paths of execution are completely independent of each other. Neither thread depends upon the other for assistance. For example, one thread might execute a print job, while a second thread repaints a window. And then there are threads that require synchronization, the act of serializing access to critical sections of code, at various moments during their executions. For example, say that two threads need to send data packets over a single network connection. Each thread must be able to send its entire data packet before the other thread starts sending its data packet; otherwise, the data is scrambled. This scenario requires each thread to synchronize its access to the code that does the actual data-packet sending.

Correctly synchronizing threads is one of the more challenging thread-related skills for Java developers to master. This article begins a two-part series that attempts to meet that challenge by exploring the fundamentals of Java's synchronization capabilities. It begins by introducing you to the concepts of monitors and locks. You next will learn how synchronized methods and synchronized statements implement those concepts at the language level. Finally, you will learn about deadlock, a nasty problem that often occurs when synchronizing threads.

Note: This series assumes that you have a basic understanding of threads and the java.lang.Thread class, such as how to start a thread. Also, keep in mind that the idea of multiple threads simultaneously executing code has slightly different meanings on uniprocessor and multiprocessor machines. On a uniprocessor machine, threads don't actually run at the same time. The thread scheduler gives the illusion that this is the case. In contrast, where enough processors exist to run all eligible threads, a multiprocessor machine is capable of actually running threads simultaneously.

Read more

.
.

Program Challenge

Create a custom class of your own that doesn't implement Collection, that can be used in a for-each loop. Consider something like an album of songs or a deck of cards.

See possible solution

.
.

What's New on Java.net

The new2java Project

While the New to Java Center on java.sun.com is the information hub for developers/programmers new to the Java platform, the new new2java project on Java.net is the communications center for these same people. By joining the new2java project, you can talk coding techniques, work on a mutual application project, and share your favorite learning resources.

In addition, the new2java project provides articles, sample code, online quizzes, and tutorials. As you and your fellow developers participate, add your own content, and share information, the project will become more helpful to everyone as it grows.

To join the new2java project, you must be a registered java.net member. Registration is free. Join to communicate with other developers, share information, and work on mutual projects.

Not sure what the java.net site has to offer developers new to the Java platform? Read the Java.net: A Community for Everyone, which is listed in More Information below.

Register and join the new2java project

.
.

Sun's Online Courses

Designing Graphical User Interfaces in Java Technology

The Designing Graphical User Interfaces in Java Technology course provides students with an overview of the Abstract Windowing Toolkit (AWT) from the Java platform to enable the student to create programs with graphical user interface (GUI) components (buttons, checkboxes, textfields, and so forth). In addition, the mechanics for handling events generated by GUI components are presented.

Read more

.
.

Sun's Instructor Led Courses

Java Programming Language Workshop

The Java Programming Language Workshop course provides students with practical experience in designing a vertical solution for a distributed, multitier application. Students use graphical user interface (GUI) design principles and network-communications capabilities to code a functional Java application that interacts with a networked database server.

Read more

.
.

For More Information

.
.

Downloading the Java 2 Platform

For most Java development, you need the class libraries, compiler, tools, and runtime environment provided with the J2SE development kit.

.
.
Rate and Review
Tell us what you think of the content of this page.
Excellent   Good   Fair   Poor  
Comments:
If you would like a reply to your comment, please submit your email address:
Note: We may not respond to all submitted comments.
.
.

Find archived issues of the following Java technology developer newsletters or manage your current newsletter subscriptions: https://softwarereg.sun.com/registration/developer/en_US/subscriptions

Subscribe to the following newsletters for the latest information about technologies and products in other Java platforms:

- Core Java Technologies Newsletter. Learn about new products, tools, resources, and events of interest to developers working with core Java technologies.
- Mobility Developer Newsletter. Learn about the latest releases, tools, and resources for developers working on wireless and Java Card technologies and applications.
- Core Java Technologies Tech Tips (formerly JDC Tech Tips) Get expert tips, sample code solutions, and techniques for developing in the Java 2 Platform, Standard Edition (J2SE)


You can subscribe to these and other JDC publications on the JDC Newsletters and Publications page

PRIVACY STATEMENT:
Sun respects your online time and privacy. You have received this based on your e-mail preferences. If you would prefer not to receive this information, please follow the steps at the bottom of this message to unsubscribe.


IMPORTANT: Please read our Terms of Use, Privacy, and Licensing policies:
http://www.sun.com/share/text/termsofuse.html
http://www.sun.com/privacy/
http://developer.java.sun.com/berkeley_license.html


Copyright 2004 Sun Microsystems, Inc. All rights reserved. Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US

FEEDBACK
Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com


SUBSCRIBE/UNSUBSCRIBE
- To subscribe, go to the subscriptions page, choose the newsletters you want to subscribe to and click Update
- To unsubscribe, go to the subscriptions page, uncheck the appropriate check box, and click Update


Trademark Information: http://www.sun.com/suntrademarks/
Java, J2EE, J2SE, J2ME, and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries.


Sun Microsystems, Inc.
image
image