You are receiving this e-mail {e-mail address} because you elected to receive e-mail from Sun Microsystems, Inc. To update your communications preferences, please see the link at the bottom of this message. We respect your privacy and post our privacy policy prominently on our Web site http://sun.com/privacy/
  Welcome to the Java Technology Fundamentals Newsletter.
Java Technology Fundamentals
NEWSLETTER
June 2005
  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.

You can receive future issues of this newsletter in HTML or text:
http://developer.java.sun.com/subscription/

Note: For the code to compile in this issue of Fundamentals, you need to use the JDK 5.0 software.
http://java.sun.com/j2se/1.5.0/download.jsp

Contents
 
» Java Programming Language Basics: Copying and Cloning Arrays
» Making Sense of the Java Classes & Tools: Java Web Start Software
» Java Bits: What Is the JDBC API?
» JAR File Overview
» What's New on java.net: Java Tech: Language Lessons by Jeff Friesen
» What's New in the New to Java Center: Getting Started With NetBeans Tutorial, Part 1
» Sun's Java Technology Instructor-Led Courses: Java Programming Language Workshop (VC-SL-285)
» Sun's Java Technology Courses: J2SE Internals and Troubleshooting (WJO-3250)
» Books for Learning
» 2005 JavaOne Conference Ask the Experts
» For More Information

Java Programming Language Basics
 
Copying and Cloning Arrays


You can do many things when working with arrays. If you've outgrown the initial size of the array, you need to create a new larger one and copy the original elements into the same location of the larger array. But if you don't need to make the array larger, and instead you want to modify the array's elements while keeping the original array intact, you must create a copy or clone of the array.

The arrayCopy() method of the System class allows you to copy elements from one array to another. When making this copy, the destination array can be larger. But if the destination is smaller, an ArrayIndexOutOfBoundsException will be thrown at runtime. The arrayCopy() method takes five arguments (two for each array and starting position, and one for the number of elements to copy):
public static void arraycopy (Object sourceArray, int sourceOffset,
  Object destinationArray, int destinationOffset,
    int numberOfElementsToCopy).
Besides type compatibility, the only requirement here is that the destination array's memory is already allocated.

To demonstrate, the DoubleArray program takes an integer array and creates a new array that is twice as large. The doubleArray() method in the following example creates the new allocation and copy for you:
import java.util.Arrays;

public class DoubleArray {
  public static void main (String args[]) {
    int array1[] = {1, 2, 3, 4, 5};
    int array2[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    System.out.println("Original size: " + array1.length);
    System.out.println("New size: " + doubleArray(array1).length);
    System.out.println("New array: " 
                          + Arrays.toString(doubleArray(array1)));
    System.out.println("Original size: " + array2.length);
    System.out.println("New size: " + doubleArray(array2).length);
    System.out.println("New array: " 
                          + Arrays.toString(doubleArray(array2)));
  }

  private static int[] doubleArray(int original[]) {
    int length = original.length;
    int newArray[] = new int[length*2];
    System.arraycopy(original, 0, newArray, 0, length);
    return newArray;
  }
}
After getting the length of the original array, a new array of the right size is created before the old elements are copied into their original positions in the new array. New positions are filled with zeros.

When executed, the program generates the following output:
  Original size: 5
  New size: 10
  New array: [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
  Original size: 9
  New size: 18
  New array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0]
When copying arrays with arrayCopy(), the source and destination arrays can be the same if you want to copy a subset of the array to another area within that array. This works even if there is some overlap.

Because arrays implement the Cloneable interface, besides copying regions of arrays, you can also clone them. Cloning involves creating a new array of the same size and type and copying all the old elements into the new array. This is unlike copying, which requires you to create and size the destination array yourself. In the case of primitive elements, the new array has copies of the old elements, so changes to the elements of the original are not reflected in the copy. However, in the case of object references, only the reference is copied. Thus, both copies of the array would point to the same object. Changes to that object would be reflected in both arrays. This is called a shallow copy or shallow clone.

To demonstrate, the following method takes one integer array and returns a clone of said array.
int[] cloneArray(int original[]) {
  return (int[])original.clone();
}
Array cloning overrides the protected Object method that would normally throw a CloneNotSupportedException with a public one that actually works.

Do this program challenge:

Create a single method that duplicates the doubleArray() method functionality from the DoubleArray class but works for all array types. Given any array, have it return an array of twice the size, with the first half filled with the original elements. You'll need to use reflection. Fill in the "..." part from the following class with your solution.
import java.lang.reflect.Array;
import java.util.Arrays;

public class DoubleArray2 {
  public static void main (String args[]) {
    int array[] = {1, 2, 3, 4, 5};
    System.out.println("Original size: " + array.length);
    System.out.println("New size: " + 
	    ((int[])doubleArray(array)).length);
    System.out.println("New array: " +
      Arrays.toString((int[])doubleArray(array)));
    System.out.println("Original size: " + args.length);
    System.out.println("New size: " + 
	    ((String[])doubleArray(args)).length);
    System.out.println("New array: " +
      Arrays.toString((String[])doubleArray(args)));
  }
  private static Object doubleArray(Object original) {
    Object returnValue = null;
    ...
    return returnValue;
  }
}
When run with the following command line:
> java DoubleArray2 one two three 
See what your results should be

Take a quiz about arrays

Making Sense of the Java Classes & Tools
 
Java Web Start Software


Java Web Start software is a helper application that gets associated with a web browser. When a user clicks on a link that points to a special launch file (Java Network Launching Protocol, JNLP, file), it causes the browser to launch the Java Web Start software, which then automatically downloads, caches, and runs the given Java technology-based application.

The entire process typically requires no user interaction, except for the initial single click.

Java Web Start technology has a number of key benefits that make it an attractive platform to use for deploying applications:
  • It is built exclusively to launch applications written to the Java 2 Platform, Standard Edition (J2SE). Thus, a single application can be made available on a web server and then deployed on a wide variety of platforms, including Windows 98/NT/2000/ME/XP, Linux, and the Solaris Operating System.
  • It supports multiple revisions of J2SE. An application can request a particular version of the platform it requires. Several applications can run at the same time on different platform revisions without causing conflicts, and the Java Web Start software can automatically download and install a revision of the platform if an application requests a version that is not installed on the client system.
  • It allows applications to be launched independently of a web browser. This can be used for offline operation of an application, in which launching through the browser is often inconvenient or impossible. The application can also be launched through desktop shortcuts, making launching the web-deployed application similar to launching a native application.
  • It takes advantage of the inherent security of the Java platform. Applications are by default run in a protective environment (sandbox) with restricted access to local disk and network resources. Java Web Start technology allows the user to run applications safely from sources that are not trusted.
  • It caches launched applications locally. Thus, an already downloaded application is launched on par with a traditionally installed application.
The technology underlying the Java Web Start software is the Java Network Launching Protocol (JNLP) and API. This technology was developed through the Java Community Process (JCP). Java Web Start software is the reference implementation (RI) for the JNLP specification. The JNLP technology defines, among other things, a standard file format that describes how to launch an application called a JNLP file.

Security

Java Web Start software is built on top of the Java 2 platform, which provides a comprehensive security architecture. Applications launched with Java Web Start technology will, by default, run in a restricted environment (sandbox) with limited access to files and network. Thus, launching applications using Java Web Start software maintains system security and integrity.

An application can request unrestricted access to your system. In this case, Java Web Start displays a Security Warning dialog box when the application is launched for the first time. The security warning shows information about the vendor that developed the application. If you choose to trust the vendor, then the application will be launched. The information about the application's origin is based on digital code signing.

Java Web Start software allows you to launch Java technology-based applications directly from the web. An application can be launched in three different ways:
  • From a web browser by clicking on a link
  • From desktop icons or the Start menu (Microsoft Windows only)
  • From the Java Web Start Cache Viewer
Regardless of which way it is used, Java Web Start software connects back to the web server each time an application is launched to check whether an updated version of the application is available.

Read more

Java Bits
 
What Is the JDBC API?


The JDBC API provides universal data access for the Java programming language. It includes the JDBC 1.0 API, which provides the basic functionality for data access. The JDBC 2.0 API supplements the basic API with more advanced features and provides a standard way to access the latest object-relational features being supported by today's relational database management systems. In addition, the new API includes features such as scrollable and updatable result sets and improved performance. It also extends JDBC technology beyond the client to the server, with connection pooling and distributed transactions.

The JDBC API is a Java technology API for accessing virtually any kind of tabular data. The JDBC API consists of a set of classes and interfaces written in the Java programming language that provide a standard API for developers of tools and databases, making it possible for them to write industrial strength database applications using an API entirely based on Java technology.

The JDBC API makes it easy to send SQL statements to relational database systems and supports all dialects of SQL. But the JDBC 2.0 API goes beyond SQL, also making it possible to interact with other kinds of data sources, such as files containing tabular data.

The value of the JDBC API is that an application can access virtually any data source and run on any platform with a Java Virtual Machine*. In other words, with the JDBC API, it isn't necessary to write one program to access a Sybase database, another program to access an Oracle database, a third program to access an IBM DB2 database, and so on. Write a single program using the JDBC API, and the program will be able to send SQL or other statements to the appropriate data source. And with an application written in the Java programming language, you don't have to worry about writing different applications to run on different platforms. The combination of the Java platform and the JDBC API lets a programmer "Write Once, Run Anywhere."

The Java programming language, which is robust, secure, easy to use, easy to understand, and automatically downloadable on a network, is an excellent language basis for database applications. What is needed is a way for Java technology applications to talk to a variety of different data sources. JDBC is the mechanism for doing this.

The JDBC 2.0 API extends what you can do with the Java platform. For example, the JDBC API makes it possible to publish a web page containing an applet that uses information obtained from a remote data source. Or an enterprise can use the JDBC API to connect all its employees (even if they are using a conglomeration of Windows, Macintosh, and UNIX machines) to one or more internal databases through an intranet. With more and more programmers using the Java programming language, the need for easy and universal data access from Java technology is continuing to grow.

MIS managers like the combination of the Java platform and JDBC technology because it makes disseminating information easy and economical. Businesses can continue to use their installed databases and access information easily even if it is stored on different database management systems or other data sources. Development time for new applications is short. Installation and version control are greatly simplified. A programmer can write an application or an update once, put it on the server, and give everybody access to the latest version. And for businesses selling information services, the combination of the Java and JDBC technologies offers a better way of getting out information updates to external customers.

What Does the JDBC API Do?

In simplest terms, a JDBC technology-based driver (JDBC driver) makes it possible to do three things:
  1. Establish a connection with a data source
  2. Send queries and update statements to the data source
  3. Process the results
The following code fragment gives a simple example of these three steps:
Connection con = DriverManager.getConnection(
		"jdbc:myDriver:wombat", "myLogin", "myPassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
while (rs.next()) {
	int x = rs.getInt("a");
	String s = rs.getString("b");
	float f = rs.getFloat("c");

	}
Read more

Jar File Overview
 
Jar stands for Java ARchive. It's a file format based on the popular ZIP file format and is used for aggregating many files into one. Although Jar can be used as a general archiving tool, the primary motivation for its development was to allow Java applets and their requisite components (.class files, images, and sounds) to be downloaded to a browser in a single HTTP transaction, rather than opening a new connection for each piece. This greatly improves the speed with which an applet can be loaded onto a web page and begin functioning. The Jar format also supports compression, which reduces the size of the file and improves download time still further. Additionally, individual entries in a Jar file may be digitally signed by the applet author to authenticate their origin.

A Jar file is
  • The only archive format that is cross-platform
  • The only format that handles audio and image files as well as class files
  • Backward-compatible with existing applet code
  • An open standard, fully extendable, and written in Java programming language
  • The preferred way to bundle the pieces of a java applet
Jar consists of a ZIP archive, as defined by PKWARE, containing a manifest file and potentially signature files, as defined in the Jar File Specification.

The Applet Tag

Changing the applet tag in your HTML page to accommodate a JAR file is simple. The JAR file on the server is identified by the archive parameter, where the directory location of the JAR file should be relative to the location of the HTML page:
    <applet code=Animator.class 
      archive="jars/animator.jar"
      width=460 height=160>
      <param name=foo value="bar">
    </applet>
Note that the familiar CODE=myApplet.class parameter must still be present. The code parameter, as always, identifies the name of the applet where execution begins. However, the class file for the applet and all of its helper classes are loaded from the JAR file.

The archive attribute describes one or more Jar files containing classes and other resources that will be "preloaded." The classes are loaded using an instance of an AppletClassLoader with the given codebase. It takes the form archive = archiveList. The archives in archiveList are separated by "," (a comma).

Once the archive file is identified, it is downloaded and separated into its components. During the execution of the applet, when the applet requests a new class, image, or audio clip, it is searched for first in the archives associated with the applet. If the file is not found among the archives that were downloaded, it is searched for on the applet's server, relative to the codebase (that is, it is searched for as in JDK 1.0.2).

The archive tag may specify multiple JAR files. Each JAR file must be separated by "," (a comma). Each file is downloaded in turn:
    <applet code=Animator.class 
      archive="classes.jar ,  images.jar ,  sounds.jar"
      width=460 height=160>
      <param name=foo value="bar">
    </applet>
There can be any amount of white space between entries within the archive parameter. In addition, the archive tag itself is case-insensitive; it can be lowercase, uppercase, or any combination of lower- and uppercase letters, such as ArCHiVe.

Executable Jar Files

On Microsoft Windows systems, the installation program for the Java 2 runtime environment software will register a default association for Jar files so that double-clicking a Jar file on the desktop automatically runs it with javaw -jar. Dependent extensions bundled with the application also load automatically. This feature makes the end-user runtime environment easier to use on Microsoft Windows systems.

The Solaris 2.6 kernel has already been extended to recognize the special "magic" number that identifies a Jar file and to invoke java -jar on such a Jar file as if it were a native Solaris executable. An application packaged in a Jar file can thus be executed directly from the command line or by clicking an icon on the desktop.

What's New on java.net
 
Java Tech: Language Lessons by Jeff Friesen


I first encountered Java technology in 1995. That language soon became my favorite because of its elegance, its interesting language features (that is, interfaces, garbage collector, and threads), and its similarity to C and C++ (I come from a C/C++ background).

This article shares with you some of the lessons I've learned while working with the Java platform. Several lessons point out problem areas to avoid; all lessons offer advice on writing better code. I hope you'll come away from this article with a greater understanding of the Java programming language, an awareness of these problem areas, and stronger coding skills.

Lesson 1: The Poor Performance of the String Concatenation Operator

Java technology programs should perform as well as is possible. But achieving that goal is not always easy, especially if your source codes contain frequent occurrences of the string concatenation operator. Concatenating strings through Java technology's string concatenation operator, especially within loops, can significantly affect the performance of your programs. Check out the following code fragment:
String s = "";

for (int i = 32; i < 128; i++)
     s = s + (char) i;
The code fragment employs a loop to initialize a string to those characters with Unicode values ranging from 32 to 127 inclusive. Each loop iteration uses the string concatenation and cast operators to append the next character to the string. Using the string concatenation operator in a loop to build a string is something one often sees in C++. As with C++, the single loop looks OK from a performance perspective: It seems to ensure that the runtime performance is linear.

But is that performance linear? Before you answer that question, examine the equivalent sequence of JVM bytecodes:
 0 ldc ""
 2 astore_1
 3 bipush 32
 5 istore_2
 6 iload_2
 7 sipush 128
10 if_icmpge 39
13 new java/lang/StringBuilder
16 dup
17 invokespecial java/lang/StringBuilder/<init>()V
20 aload_1
21 invokevirtual
   java/lang/StringBuilder/append(Ljava/lang/String;)
   Ljava/lang/StringBuilder;
24 iload_2
25 i2c
26 invokevirtual
   java/lang/StringBuilder/append(C)
   Ljava/lang/StringBuilder;
29 invokevirtual
   java/lang/StringBuilder/toString()
   Ljava/lang/String;
32 astore_1
33 iinc 2 1
36 goto 6
39 ...
The instructions at offsets 0 and 2 correspond to String s = "";. The for loop begins at offset 3 and continues through offset 36. Each for loop iteration creates a StringBuilder object and invokes two of that object's append() methods, to first append the characters in the String to the StringBuilder and then to append the next character to the StringBuilder. Finally, the toString() method is called to convert the StringBuilder back to a string. The following code fragment shows what these instructions look like from a source code perspective:
String s = "";

for (int i = 32; i < 128; i++)
     s = new StringBuilder ().append (s)
         .append ((char) i).toString ();
This code fragment is what is really being generated when you employ the string concatenation operator. Each loop iteration creates a throwaway StringBuilder object and explicitly invokes three of that object's methods. The toString() method call creates a new String object to hold the result. The original String object is not used because String is immutable.

You end up creating two objects and making three explicit method calls for each string concatenation. Furthermore, additional method calls happen behind the scenes. One of those method calls, which occurs when we append the string to the StringBuilder, results in a call to System.arraycopy(), to copy the String's characters into the StringBuilder's memory. This is tantamount to embedding another for loop within the outer for loop. Hence, our performance changes from linear to quadratic.

You can restore the performance to linear by eliminating the method call that first appends the String to the StringBuilder. You can also avoid creating the String and StringBuilder objects during each loop iteration (which reduces the probability of intermittent garbage collections). The following code fragment reveals these changes:
StringBuilder sb = new StringBuilder ();

for (int i = 32; i < 128; i++)
     sb.append ((char) i);;

String s = sb.toString ();
Lesson: Do not use the string concatenation operator in lengthy loops or other places where performance could suffer.

Lesson 2: Superclass Constructors Invoking Overridable Methods

Java technology's class inheritance mechanism is a powerful tool for developing reusable code. If used incorrectly, however, this tool leads to fragile software. An example of incorrect use: superclass constructors invoking overridable methods.

The problem with a superclass constructor invoking an overridable method, either directly or indirectly, is that the superclass constructor runs before the subclass constructor. The subclass's version of the overridable method will be invoked before the subclass's constructor has been invoked. If the subclass's overridable method depends on the proper initialization of the subclass (through the subclass constructor), the method will most likely fail.

Read the rest of this article

What's New in the New to Java Center
 
Getting Started With NetBeans Tutorial, Part 1


Using an Integrated Development Environment (IDE) for developing applications saves you time by managing windows, settings, and data. In addition, an IDE can store repetitive tasks through macros and abbreviations. Drag-and-drop features make creating graphical user interface (GUI) components or accessing databases easy, and highlighted code and debugging features alert you to errors in your code.

The NetBeans IDE is open source and is written in the Java programming language. It provides the services common to creating desktop applications -- such as window and menu management and settings storage -- and is also the first IDE to fully support JDK 5.0 features. The NetBeans platform and IDE are free for commercial and noncommercial use, and they are supported by Sun Microsystems.

This tutorial is aimed at those who are new to using IDEs, fairly new to programming, and new to the Java platform. You'll learn to create a simple desktop application with a GUI interface and functionality that calculates overtime pay using basic features of the NetBeans IDE.

This tutorial provides explanations for the code where appropriate, as well as links to the Java technology API and information about objects as they are introduced. Although the NetBeans environment also provides many rich features for the various Java platforms, such as Java 2 Platform, Enterprise Edition (J2EE) and Java 2 Platform, Micro Edition (J2ME), this article covers only Java 2 Platform, Standard Edition (J2SE) technology, which is generally the entry point for new developers and programmers. Future tutorials will discuss more advanced features.

To follow this tutorial, you need to have downloaded and installed JDK 5.0 and the NetBeans IDE. Or you can download JDK 5.0 and NetBeans 4.1 separately to ensure that you have the latest versions.

Read the tutorial

Sun's Java Technology Instructor-Led Courses
 
Java Programming Language Workshop (VC-SL-285)


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 technology-based application that interacts with a networked database server. The significant amount of lab time emphasizes the workshop nature of this course.

Format: This course is presented using Sun's web-based Live Virtual Classroom (LVC). The LVC is a dynamic and fully interactive online learning environment that features live teaching, collaboration, and instructor-assisted activities.

Course Features and Services
  • Live audio by an expert instructor
  • Lab reviews, simulations, demonstrations, or lab exercises
  • Printable study guide
Learn more about this course

Sun's Java Technology Web Courses
 
J2SE Internals and Troubleshooting (WJO-3250)


The J2SE Internals and Troubleshooting course provides technical information on the internal functioning and operation of the J2SE platform. The course addresses debugging, gathering of crash-related data, the nature of the Just In Time compiler, garbage collection, Java Native Interface (JNI), threads, and handling signals in native code.

Learn more

Books for Learning
 
Core Java 2, Volume I: Fundamentals
The seventh edition of Core Java 2, Volume I, covers the fundamentals of the Java 2 Platform, Standard Edition (J2SE). A no-nonsense tutorial and reliable reference, this book features thoroughly tested real-world examples. The most important language and library features are demonstrated with deliberately simple sample programs, but they aren't fake and don't cut corners.

NetBeans IDE Field Guide
NetBeans 4.1 is today's state-of-the-art Java technology IDE and the first free, open source IDE to support J2SE 5.0. The newest NetBeans delivers exceptional performance, while integrating everything from version control to Javadoc generation through a remarkably productive new interface.

2005 JavaOne Conference Ask the Experts
 
Meet the experts and ask those burning Java technology questions you've always wanted to ask. On Monday, June 27, from 6:30 to 8:00 PM in the JavaOne Pavilion, experts from Sun's 2005 JavaOne Conference sessions will be on hand to chat and answer your questions.

For More Information
  The terms "Java Virtual Machine" and "JVM" mean a virtual machine for the Java platform.


Downloading the Java 2 Platform, Standard Edition (J2SE)
 
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.
Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: fundamentals_newsletter@sun.com

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

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

© 2005 Sun Microsystems, Inc. All Rights Reserved. For information on Sun's trademarks see: http://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.

To update your Sun subscription preferences or unsubscribe to Sun news services, click here or use this link https://softwarereg.sun.com/registration/developer/en_US/subscriptions

Sun Microsystems, Inc. 10 Network Circle, MPK10-209 Menlo Park, CA 94025 US