Zamples, Inc. logo
 Home   Search   Solutions   My Zamples   FAQ   News   Contact 
Zamples ID:
Password:
   
0 anonymous users;
30 users logged in.

Live Samples
Live APIs

HTML or JSP Frag
Java Servlet Frag
HTML & Applet
Bash
C# (Mono)
C++ (gcc)
Groovy
Haskell (Hugs98)
J2SE 1.4 Class
J2SE 1.4 Fragment
J2SE 5.0 Class
J2SE 5.0 Fragment
J2SE 6.0 Class
J2SE 6.0 Fragment
Perl
Python
Ruby
 

J2SE 5.0 Sample Code

J2SE 5.0 (formerly known as J2SE 1.5) has some very useful enhancements.  Thanks to Josh Bloch of Sun Microsystems for helpful hints.

These community postings allow you to create new discussion threads, or reply to an existing posting.  After you click on a 'Try It!' button in a community posting, or after you press a 'New' button to start a new discussion thread, edit your code, select the type of program (J2SE 5.0 Fragment or J2SE 5.0 Class), and then 'Run It!' until it works (or you give up).  When you click on the 'Save' button, the New Posting Wizard will appear.  The wizard will prompt you for information about your code example, and then save it to the database.  Each posting contains a code example, plus comments about the code.  Next time you refresh this page your new posting will appear.

Learn more about Zamples and play with samples for other APIs. Our Amazon Web Services examples are very popular!

We would love to hear your feedback.

J2SE 5 has both language syntax and keyword changes and API changes.

J2SE 5 Language Changes

Autoboxing

Java's distinction between primitive types and their equivalent Object types was painful.  Fortunately, with the advent of autoboxing, that will become a fading memory.

2/10/04
12:00 AM
Autoboxing is easy
Purpose: Autoboxing should always have been in Java!
Description: The Integer and the int are happily added together without any explicit conversion necessary.
// automatically convert one type to another
Integer integer = 1;
System.out.println(integer);

// mix Integer and ints in the same expression
int i = integer + 3;
System.out.println(i);
to add a new posting or reply to an existing posting.

Enhanced for loop

Iterating through an array has never been easier.

2/23/04
12:00 AM
Enhanced For Loops Are Easy To Use
Purpose:
Description: lskjldkfjjkdhkdfj
2/10/04
12:00 AM
Enhanced For Loops Are Easy To Use
Purpose: The drudgery of iterating through an array is taken care of with enhanced for loops.
Description: An integer array is added and the sum is printed.
int array[] = {1, 2, 3, 4};
int sum = 0;
for (int e : array)  // e is short for element; i would be confusing
    sum += e;
System.out.println(sum);
to add a new posting or reply to an existing posting.

Enums

Java programmers rejoice with the availability of enums.

Sample output:

clubs
diamonds
hearts
spades

2/10/04
12:00 AM
Enums
Purpose: Enums can be complex, but most of the time they don't need to be. This example shows how easy enums are to define and use.
Description: An enum called Suit is created, with members clubs, diamonts, hearts and spades. Note that the enum looks a lot like an inner class. The values of the enum are iterated through and printed.
public class EnumTest {
  public static void main(String[] args) {
    for (Suit suit : Suit.values())
      System.out.println(suit);
  }

  public enum Suit { clubs, diamonds, hearts, spades };
}
to add a new posting or reply to an existing posting.

Here is a more complex example.

Sample output:

penny (1) nickel (5) dime (10) quarter (25)

2/10/04
12:00 AM
More Sophisticated Enum Example
Purpose: You can excert a great deal of control over how enums work. Java is the only computer language that allows enums to have custom methods. This example shows a custom value() method for the Coin enum, implemented here as an inner class.
Description: You can excert a great deal of control over how enums work. An enum called Coin is defined, with members penny, nickel, dima and quarter. Specific values are assigned to the coins. Enums are rather like specialized classes and a value() method is defined to provide the value of a specific member. The Coin enum is converted to java.util.List of Coins so an iterator can be obtained that is used to print out all of the coin values.
public class EnumFun {
  private enum Coin {
    penny(1), nickel(5), dime(10), quarter(25);
    Coin(int value) { this.value = value; }
    private final int value;
    public int value() { return value; }
  }

  public static void main(String[] args) {
    for (Coin coin : Coin.values()) 
      System.out.print(coin + " (" + coin.value() + ") ");
  }
}
to add a new posting or reply to an existing posting.

Generics

The addition of generics to the Java language was a major improvement.  Take a look at how this affected the Collections classes.

Importing Static Members

No longer is it necessary to write

Math.abs(x)     Math.sqrt(x)    Math.max(a, b)

We can import methods once per class.

Sample output:

16.0
4.0
3.3

2/10/04
12:00 AM
Static Import
Purpose: Static imports reduce the verbosity of your Java program, with the risk that some ambiguity might be introduced.
Description: Because java.lang.Math.* is statically imported, method calls can be shortened to abs(x) instead of the more verbose Math.abs(x).
import static java.lang.Math.*;

public class Import {
    public static void main(String[] args) {
        double x = 16.0, a = 2.2, b = 3.3;
        System.out.println(abs(x));
        System.out.println(sqrt(x));
        System.out.println(max(a, b));
    }
}
to add a new posting or reply to an existing posting.

Metadata

This is one of Calvin Austin's code examples.


2/11/04
12:00 AM
Debug Metadata
Purpose: Metadata has many uses, from declarative programming to extending language capability. This example creates an artificial debug metadata annotation which is then simply displayed at runtime.
Description: Note the @Retention and @debug language extensions.
import java.lang.annotation.*;
import java.lang.reflect.*;
                                                                                
@Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @interface debug  {
    boolean  devbuild() default false;
    int counter();
}
                                                                                
public class MetaTest {
    final boolean production=true;

    @debug(devbuild=production,counter=1) public void testMethod()  { }
                                                                               
    public static void main(String[] args) {
        MetaTest mt = new MetaTest();
        try {
            Annotation[] a = mt.getClass().getMethod("testMethod").getAnnotations();
            for (int i=0; i<a.length ; i++)  { 
                System.out.println("a["+i+"]="+a[i]+" "); 
            } 
        } catch(NoSuchMethodException e) { 
            System.out.println(e); 
        } 
    } 
}
to add a new posting or reply to an existing posting.

Monitoring and Manageability

This is another one of Calvin Austin's code examples.

Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java platform.  The following code reports the detailed usage of the memory heaps in the Hotspot JVM.


Sample output (reformatted):

Memory type=Non-heap memory Memory usage=init = 163840(160K) used = 533824(521K) 
   committed = 557056(544K) max = 33554432(32768K)
Memory type=Heap memory Memory usage=init = 524288(512K) used = 205088(200K) 
   committed = 524288(512K) max = 4194304(4096K)
Memory type=Heap memory Memory usage=init = 131072(128K) used = 0(0K) 
   committed = 131072(128K) max = 458752(448K)
Memory type=Heap memory Memory usage=init = 1441792(1408K) used = 0(0K) 
   committed = 1441792(1408K) max = 61997056(60544K)
Memory type=Non-heap memory Memory usage=init = 8388608(8192K) used = 1529696(1493K) 
   committed = 8388608(8192K) max = 67108864(65536K)

10/13/04
5:02 PM
Monitoring and Manageability (Tweaked for JDK 5.0 final release)
Purpose: Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java platform. This code example reports the detailed usage of the memory heaps in the Hotspot JVM.
Description: MXBeans are used, but it all seems like magic, doesn't it?
import java.lang.management.*;
import java.util.*;

public class MemTest {
     public static void main(String args[]) {
          List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
          for (MemoryPoolMXBean p: pools) {
               System.out.println("Memory type="+p.getType()+" Memory usage="+p.getUsage());
         }
     }
}
2/11/04
12:00 AM
Monitoring and Manageability
Purpose: Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java platform.
Description: The following code reports the detailed usage of the memory heaps in the Hotspot JVM. This feature isn't quite working yet, as you can see.
import java.lang.management.*;
import java.util.*;
import javax.management.*;

public class MemTest {
    public static void main(String args[]) {
        List pools = ManagementFactory.getMemoryPoolMBeans();
        for (ListIterator i = pools.listIterator(); i.hasNext();) {
            MemoryPoolMBean p = (MemoryPoolMBean) i.next();
            System.out.println("Memory type=" + p.getType() + 
                " Memory usage=" + p.getUsage());
        }
    }
}
to add a new posting or reply to an existing posting.

Variable Arguments

This is just using ellipses as syntactic sugar for arrays.

Sample output:

3 arguments

2/10/04
12:00 AM
Trivial Example of Variable Arguments
Purpose: Variable arguments can be used as an idiomatic synonym for an array argument.
Description: Doesn't provide much value, but it works.
public class Test {
    // main() looks different, doesn't it?
    // try changing the runtime arguments above and rerun
    public static void main(String... args) {
        System.out.println(args.length + " arguments");
    }
}
to add a new posting or reply to an existing posting.

Challenge: Here is a program that reads the name of a class from the command line, followed by a method name.  It instantiates an object of the specified type, and invokes the method.  For example, if fed a command line like java.util.Date toString, this program will print the current date and time.  Of course, this class only works with methods that don't require arguments.  The challenge is to use ellipses to specify the variable arguments to invoke.

2/10/04
12:00 AM
Attempt at Showing A Use for Variable Arguments
Purpose: You can use variable arguments in method invocation via reflection. This program reads the name of a class from the command line, followed by a method name. It instantiates an object of the specified type, and invokes the method.
Description: For example, if fed a command line like java.util.Date toString, this program will print the current date and time. Of course, this class only works with methods that don't require arguments. The challenge is to use ellipses to specify the variable arguments to invoke.
to add a new posting or reply to an existing posting.

J2SE 5 API Changes

Scanner

These examples are taken from the J2SE 5 Javadoc.

Sample output:

1
2
red
blue

12/17/04
9:43 PM
Scanner with method calls to pick up numbers
Purpose: .
Description: .
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();
to add a new posting or reply to an existing posting.

Sample output:

1
2
red
blue

12/17/04
9:40 PM
Scanner with parameters
Purpose: .
Description: .
String input = "1 fish 2 fish red fish blue fish";
Scanner s = new Scanner(input);
s.findInLine("(\\d+) fish (\\d+) fish (\\w+) fish (\\w+)");
MatchResult result = s.match();
for (int i=1; i<=result.groupCount(); i++)
    System.out.println(result.group(i));
s.close();
to add a new posting or reply to an existing posting.

Collections

The collections framework is greatly enhanced by generics, which allows collections to be typesafe.

Sample output:

of course my horse 

8/18/04
12:00 AM
The iterator creation in the first example is redundant
Purpose:
Description: This is just like the first example but with the reduntant row creating a never-used Iterator removed.Just cleaned up the first example
LinkedList<String>  stringList  = new LinkedList<String>();

stringList.add("of");

stringList.add("course");

stringList.add("my");

stringList.add("horse");



for (String s : stringList)

    System.out.print(s + " ");
2/10/04
12:00 AM
Typesafe LinkedList
Purpose: Shows a typesafe LinkedList and an enhanced for loop.
Description: A LinkedList of String is created and then printed out.
LinkedList<String>  stringList  = new LinkedList<String>();
stringList.add("of");
stringList.add("course");
stringList.add("my");
stringList.add("horse");

Iterator<String> iterator = stringList.iterator();
   for (String s : stringList)
       System.out.print(s + " ");
to add a new posting or reply to an existing posting.

Formatted Output

Developers now have the option of using printf type functionality to generated formatted output.  Most of the common C printf formatters are available.

2/11/04
12:00 AM
Formatted Output
Purpose: If you know C, this is a page out of history. For C programmers, printf() is an old friend.
Description: printf() accepts a variable number of arguments, and the formatting strings have a lot of variety.
System.out.printf("name count\n");
String user = "fflintstone";
int total = 123;
System.out.printf("%s is %d years old\n", user, total);
to add a new posting or reply to an existing posting.

Improved Diagnostic Ability

This is one of Calvin Austin's code examples.

Generating Stack traces has been awkward if no console window has been available.  Two new APIs, getStackTrace and Thread.getAllStackTraces provide this information programmatically.

Sample output:

java.lang.Thread.dumpThreads(Native Method)
java.lang.Thread.getStackTrace(Thread.java:1333)
Class2005.main(Class2005.java:5) {Thread[Reference Handler,10,system]=[Ljava.lang.StackTraceElement;@130c19b, Thread[main,5,main]=[Ljava.lang.StackTraceElement;@1f6a7b9, Thread[Signal Dispatcher,10,system]=[Ljava.lang.StackTraceElement;@7d772e, Thread[Finalizer,8,system]=[Ljava.lang.StackTraceElement;@11b86e7}

2/11/04
12:00 AM
View Stack Traces Without a Console Window
Purpose: Until JDK 1.5 is has been awkward to view a stack trace without examining the system console. Two new APIs, getStackTrace and Thread.getAllStackTraces() provide this information programmatically
Description: An array of StackTraceElements is printed.
StackTraceElement e[] = Thread.currentThread().getStackTrace();
for (int i=0; i <e.length; i++) 
    System.out.println(e[i]);

System.out.println("\n" + Thread.getAllStackTraces());
to add a new posting or reply to an existing posting.

Monitoring and Manageability

This is another one of Calvin Austin's code examples.

Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java platform.  The following code reports the detailed usage of the memory heaps in the Hotspot JVM.

Sample output (reformatted):

Memory type=Non-heap memory Memory usage=init = 163840(160K) used = 533120(520K) 
   committed = 557056(544K) max = 33554432(32768K)
Memory type=Heap memory Memory usage=init = 524288(512K) used = 195232(190K) 
   committed = 524288(512K) max = 4194304(4096K)
Memory type=Heap memory Memory usage=init = 65536(64K) used = 0(0K) 
   committed = 65536(64K) max = 458752(448K)
Memory type=Heap memory Memory usage=init = 1441792(1408K) used = 0(0K) 
   committed = 1441792(1408K) max = 61997056(60544K)
Memory type=Non-heap memory Memory usage=init = 8388608(8192K) used = 119112(116K) 
   committed = 8388608(8192K) max = 67108864(65536K)
Memory type=Non-heap memory Memory usage=init = 8388608(8192K) used = 5735280(5600K) 
   committed = 8388608(8192K) max = 8388608(8192K)
Memory type=Non-heap memory Memory usage=init = 12582912(12288K) used = 5973320(5833K) 
   committed = 12582912(12288K) max = 12582912(12288K)

10/13/04
5:02 PM
Monitoring and Manageability (Tweaked for JDK 5.0 final release)
Purpose: Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java platform. This code example reports the detailed usage of the memory heaps in the Hotspot JVM.
Description: MXBeans are used, but it all seems like magic, doesn't it?
import java.lang.management.*;
import java.util.*;

public class MemTest {
     public static void main(String args[]) {
          List<MemoryPoolMXBean> pools = ManagementFactory.getMemoryPoolMXBeans();
          for (MemoryPoolMXBean p: pools) {
               System.out.println("Memory type="+p.getType()+" Memory usage="+p.getUsage());
         }
     }
}
2/11/04
12:00 AM
Monitoring and Manageability
Purpose: Monitoring and Manageability is a key component of RAS (Reliability, Availability, Serviceability) in the Java platform.
Description: The following code reports the detailed usage of the memory heaps in the Hotspot JVM. This feature isn't quite working yet, as you can see.
import java.lang.management.*;
import java.util.*;
import javax.management.*;

public class MemTest {
    public static void main(String args[]) {
        List pools = ManagementFactory.getMemoryPoolMBeans();
        for (ListIterator i = pools.listIterator(); i.hasNext();) {
            MemoryPoolMBean p = (MemoryPoolMBean) i.next();
            System.out.println("Memory type=" + p.getType() + 
                " Memory usage=" + p.getUsage());
        }
    }
}
to add a new posting or reply to an existing posting.

Word Frequency Counter

This is Josh Bloch's new and improved word frequency counter.

2/10/04
12:00 AM
Typesafe Maps and enhanced for loop
Purpose: Typesafe Maps and TreeMaps don't require class casts, and are easy to use. This example counts the number of unique words in the command line arguments. The Map is then printed.
Description: Notice how Java generics appears to greatly expand the available classes to work with. You can create a collection of any type of object that you desire, without having to define them first. For example, the compiler 'knows' what a Map is, and how it should behave.
import java.text.*;
import java.util.*;

public class Freq {
    public static void main(String[] args) {
        Map<String, Integer> m = new TreeMap<String, Integer>();
        for (String word : args) {
            Integer freq = m.get(word);
            m.put(word, (freq == null ? 1 : freq + 1));
        }
        System.out.println(m);
    }
}
to add a new posting or reply to an existing posting.

Grep

This is one of Sun's NIO examples.  This program has a bug: instead of working from a directory name or accepting wildcards, the only way it works is to specify the exact filename that you are looking for... which defeats the purpose.  Perhaps you'd like to figure out the fix?

We have placed files in the JDK 1.5 shared sandbox called /usr/share/fileXX.data, where XX runs from 1 to 10.  These files have privileges that allow them to be read by users, so this example will be able to generate viewable results.  If you attempt read a file for which you do not have privilege, a java.io.FileNotFoundException error will result.

Sample output

This is file #1
This is file #2
This is file #3
This is file #4
This is file #5
This is file #6
This is file #7
This is file #8
This is file #9
This is file #10

2/10/04
12:00 AM
Sun's NIO Example has a bug
Purpose: Instead of working from a directory name or accepting wildcards, the only way this program works is to specify the exact filename that you are looking for... which defeats the purpose. Perhaps you'd like to figure out the fix?
Description: We have placed files in the JDK 1.5 shared sandbox called /usr/share/fileXX.data, where XX runs from 1 to 10. These files have privileges that allow them to be read by users, so this example will be able to generate viewable results. If you attempt read a file for which you do not have privilege, a java.io.FileNotFoundException error will result.
to add a new posting or reply to an existing posting.

System.nanoTime() and HttpURLConnection()

System.nanoTime() is a new static method that is only good for measuring intervals, and no, it doesn't guarantee nanosecond accuracy.  We confess that we cheated ... HttpURLConnection() is an abstract class, but we didn't want to take advantage of all it's features, so we created an anonymous class.

3/24/04
12:00 AM
High resolution timer and enhanced HttpConnection
Purpose: Shows how you can time an event using the highest resolution available on your computer. This example also shows an enhanced UrlConnection class. System.nanoTime() is a new static method that is only good for measuring intervals, and no, it doesn't guarantee nanosecond accuracy.
Description: We confess that we cheated ... HttpURLConnection() is an abstract class, but we didn't want to take advantage of all it's features, so we created an anonymous class.
long startTime = System.nanoTime();
try {
    HttpURLConnection huc = new HttpURLConnection(new URL("http://java.sun.com")) {
        public void connect() {}
        public void disconnect() {}
        public boolean usingProxy() { return false; }
    };
} catch (MalformedURLException ignored) {}
System.out.println((System.nanoTime() - startTime) + " nanoseconds.");
to add a new posting or reply to an existing posting.

Add New Code Samples Here

If you have code samples that don't fit into any of the topics above which you would like to contribute, please put them here.  We'll sort them out into their own sections as appropriate later.

2 Quality Tested Examples 0 Problems & Suggestions 0 Closed Issues
7/11/05
5:26 AM
generics
Purpose: implements generic
Description: // now with generics in JDK 5 List stringList2 = new ArrayList(); stringList2.add("Java 5.0"); stringList2.add("with generics"); // no need for type casting String s2 = stringList2.get(0); System.out.println(s2.toUpperCase());
// now with generics in JDK 5
    List<String> stringList2 = new ArrayList<String>();
    stringList2.add("Java 5.0");
    stringList2.add("with generics");
    // no need for type casting
    String s2 = stringList2.get(0);
    System.out.println(s2.toUpperCase());
7/11/05
5:20 AM
code
Purpose: implement Generic
Description: // in JDK 1.4 List stringList1 = new ArrayList(); stringList1.add("Java 1.0 - 5.0"); stringList1.add("without generics");*/ // cast to java.lang.String String s1 = (String) stringList1.get(0); System.out.println(s1.toUpperCase()); // now with generics in JDK 5 List stringList2 = new ArrayList(); stringList2.add("Java 5.0"); stringList2.add("with generics"); // no need for type casting String s2 = stringList2.get(0); System.out.println(s2.toUpperCase());
// in JDK 1.4
    List stringList1 = new ArrayList();
    stringList1.add("Java 1.0 - 5.0");
    stringList1.add("without generics");*/
    // cast to java.lang.String
   String s1 = (String) stringList1.get(0);
   System.out.println(s1.toUpperCase());
                              
    // now with generics in JDK 5
    List<String> stringList2 = new ArrayList<String>();
    stringList2.add("Java 5.0");
    stringList2.add("with generics");
    // no need for type casting
    String s2 = stringList2.get(0);
    System.out.println(s2.toUpperCase());
to add a new posting or reply to an existing posting.