News:
- In an internet driven environment, it is imperative for a company to keep its product or business to the forefront of potential customers' minds. The ...
- A successful enterprise is all about constantly reinventing ways to work more efficiently. In today’s techno age, this translates to testing new too...
- The IT industry plays a pivotal role in providing application development solutions and custom software development to a wide range of industries, i...
- Royal Victorian Eye and Ear Hospital, 2010 Atcomm has been contracted to implement a complex IOP glaucoma management tool which will be distribut...
- We are pleased to announce another implementation of a CMS system for a large Melbourne based fitness center - Star Plate Studio. Atcomm has depl...
Wednesday, 19 August 2009 11:24
Key Java Language Features and Libraries
-
font size
decrease font size
increase font size
Language Features Added in Java 5
Several useful syntactic elements were introduced in Java 5. All these features are supported by an updated compiler, and all translate to already defined Java bytecode, meaning that virtual machines can execute these features with no need for an update:
import java.util.logging.*;
Feb 22, 2004 4:07:06 PM BasicLoggingExample main
Test.java
Pattern pattern = Pattern.compile(“\\s*class”);
This example takes a regular expression (stored in a Pattern object) and uses a matcher to see if the regular expression matches a specific string. This is the simplest use of the regular expression routines in Java. Consult Figure 1-2 for an overview of how the regular expression classes work with each other.



import java.util.*;
Node’s absolute path: /PreferenceExample
❑ Generics: A way to make classes type-safe that are written to work on any arbitrary object type, such as narrowing an instance of a collection to hold a specific object type and eliminating the need to cast objects when taking an object out of the collection.
❑ Enhanced for loop: Acleaner and less error-prone version of the for loop for use with iterators.
❑ Variable arguments: Support for passing an arbitrary number of parameters to a method.
❑ Boxing/unboxing: Direct language support for automatic conversion between primitive types and their reference types (such as int and Integer).
❑ Type-safe enumerations: Clean syntax for defining and using enumerations, supported at the language level.
❑ Static import: Ability to access static members from a class without need to qualify them with a class name.
❑ Metadata: Coupled with new tools developed by third-party companies, saves developers the effort of writing boilerplate code by automatically generating the code. These features update the Java language to include many constructs developers are used to in other languages. They make writing Java code easier, cleaner, and faster. Even if you choose not to take advantage of these features, familiarity with them is vital to read and maintain code written by other developers.
❑ Enhanced for loop: Acleaner and less error-prone version of the for loop for use with iterators.
❑ Variable arguments: Support for passing an arbitrary number of parameters to a method.
❑ Boxing/unboxing: Direct language support for automatic conversion between primitive types and their reference types (such as int and Integer).
❑ Type-safe enumerations: Clean syntax for defining and using enumerations, supported at the language level.
❑ Static import: Ability to access static members from a class without need to qualify them with a class name.
❑ Metadata: Coupled with new tools developed by third-party companies, saves developers the effort of writing boilerplate code by automatically generating the code. These features update the Java language to include many constructs developers are used to in other languages. They make writing Java code easier, cleaner, and faster. Even if you choose not to take advantage of these features, familiarity with them is vital to read and maintain code written by other developers.
Important Java Utility Libraries
This section describes several key utility libraries in Java. These libraries are as follows:
❑ Java logging: A powerful logging system that is vital for providing meaningful error messages to end users, developers, and people working in the field.
❑ Regular expressions: A powerful “miniature language” used to process strings in a variety of ways, such as searching for substrings that match a particular pattern.
❑ Java preferences: A way to store and retrieve both system- and user-defined configuration options.
❑ Regular expressions: A powerful “miniature language” used to process strings in a variety of ways, such as searching for substrings that match a particular pattern.
❑ Java preferences: A way to store and retrieve both system- and user-defined configuration options.
Java Logging
The logging system in java.util.logging is sophisticated, including a way to prioritize log messages such that only messages a particular logger is interested in get logged, and the messages can be output to any source that a Handler object can handle. Examples of logging destinations are files, databases, and output streams. Take a close look at Figure 1-1 to see an overview of the entire logging system.

The specific Logger objects are actually hierarchical, and though not mandatory, can mirror the class hierarchy. When a Logger receives a log message, the message is also passed automatically to the parent of Logger. The root logger is named “ “ (the empty string) and has no parent. Each other Logger is usually named something such as java.util or java.util.ArrayList to mirror the package/class hierarchy. The names of the Logger objects, going down the tree, are dot-separated. Therefore, java .util is the parent Logger of java.util.ArrayList. You can name the loggers any arbitrary string, but keeping with the dot-separated convention helps with clarity.
The simplest use of the logging system creates a Logger and uses all system defaults (defined in a properties file) for the logging system. The following example outputs the log message using a formatting class called the SimpleFormatter that adds time/date/source information to the log message:
The simplest use of the logging system creates a Logger and uses all system defaults (defined in a properties file) for the logging system. The following example outputs the log message using a formatting class called the SimpleFormatter that adds time/date/source information to the log message:
import java.util.logging.*;
public class BasicLoggingExample {
public static void main(String args[])
{
Logger logger = Logger.getLogger(“BasicLoggingExample”);
logger.log(Level.INFO, “Test of logging system”);
}
}
The following is output from the BasicLoggingExample:
Feb 22, 2004 4:07:06 PM BasicLoggingExample main
INFO: Test of logging system
Regular Expressions
Regular expressions are a powerful facility available to solve problems relating to the searching, isolating, and/or replacing of chunks of text inside strings. The subject of regular expressions (sometimes abbreviated regexp or regexps) is large enough that it deserves its own book—and indeed, books have been devoted to regular expressions. This section provides an overview of regular expressions and discusses the support Sun has built in to the java.util.regex package Regular expressions alleviate a lot of the tedium of working with a simple parser, providing complex pattern matching capabilities. Regular expressions can be used to process text of any sort. For more sophisticated examples of regular expressions, consult another book that is dedicated to regular expressions.
If you’ve never seen regular expressions before in a language, you’ve most likely seen a small subset of regular expressions with file masks on Unix/DOS/Windows. For example, you might see the following files in a directory:
If you’ve never seen regular expressions before in a language, you’ve most likely seen a small subset of regular expressions with file masks on Unix/DOS/Windows. For example, you might see the following files in a directory:
Test.java
Test.class
StringProcessor.java
StringProcessor.class
Token.java
Token.class
You can type dir *.* at the command line (on DOS/Windows) and every file will be matched and listed. The asterisks are replaced with any string, and the period is taken literally. If the file mask T*.class is used, only two files will be matched—Test.class and Token.class. The asterisks are considered meta-characters, and the period and letters are considered normal characters. The metacharacters are part of the regular expression “language,” and Java has a rich set of these that go well beyond the simple support in file masks. The normal characters match literally against the string being tested. There is also a facility to interpret meta-characters literally in the regular expression language.
Several examples of using regular expressions are examined throughout this section. As an initial example, assume you want to generate a list of all classes inside Java files that have no modifier before the keyword class. Assuming you only need to examine a single line of source code, all you have to do is ignore any white space before the string class, and you can generate the list.
A traditional approach would need to find the first occurrence of class in a string and then ensure there’s nothing but white space before it. Using regular expressions, this task becomes much easier. The entire Java regular expression language is examined shortly, but the regular expression needed for this case is \s*class. The backslash is used to specify a meta-character, and in this case, \s matches any white space. The asterisk is another meta-character, standing for “0 or more occurrences of the previous term.” The word class is then taken literally, so the pattern stands for matching white space (if any exists) and then matching class. The Java code to use this pattern is shown next:
A traditional approach would need to find the first occurrence of class in a string and then ensure there’s nothing but white space before it. Using regular expressions, this task becomes much easier. The entire Java regular expression language is examined shortly, but the regular expression needed for this case is \s*class. The backslash is used to specify a meta-character, and in this case, \s matches any white space. The asterisk is another meta-character, standing for “0 or more occurrences of the previous term.” The word class is then taken literally, so the pattern stands for matching white space (if any exists) and then matching class. The Java code to use this pattern is shown next:
Pattern pattern = Pattern.compile(“\\s*class”);
// Need two backslashes to preserve the backslash
Matcher matcher = pattern.matcher(“\t\t class”);
if(matcher.matches()) {
System.out.println(“The pattern matches the string”);
} else {
System.out.println(“The pattern does not match the string”);
}
This example takes a regular expression (stored in a Pattern object) and uses a matcher to see if the regular expression matches a specific string. This is the simplest use of the regular expression routines in Java. Consult Figure 1-2 for an overview of how the regular expression classes work with each other.

In a regular expression, any single character matches literally, except for just a few exceptions. One such exception is the period (.), which matches any single character in the string that is being analyzed. There are sets of meta-characters predefined to match specific characters. These are listed in the following table.
The regular expression language also has meta-characters to match against certain string boundaries. Some of these boundaries are the beginning and end of a line, and the beginning and end of words. The full list of boundary meta-characters can be seen in the following table.

Regular expression languages also have character classes, which are a way of specifying a list of possible characters that can match any single character in the string you want to match. If you want to specify a character class explicitly, the characters go between square brackets. Therefore, the character class [0123456789] matches any single digit. It is also possible to specify “any character except one of these” by using the caret after the first square bracket. Using the expression [^012], any single digit except for 0, 1, and 2 is matched. You can specify character ranges using the dash. The character class [a-z] matches any single lowercase letter, and [^a-z] matches any character except a lowercase letter. Any character range can be used, such as [0–9] to match a single digit, or [0–3] to match a 0, 1, 2, or 3. Multiple ranges can be specified, such as [a-zA-Z] to match any single letter. The regular expression package contains a set of predefined character classes, and these are listed in the following table.


Another feature of the regular expression language is the ability to match a particular character a specified number of times. In the previous example, the asterisk was used to match zero or more characters of white space. There are two general ways the repetition operators work. One class of operators is greedy, that is, they match as much as they can, until the end. The other class is reluctant (or lazy), and matches only to the first chance they can terminate. For example, the regular expression .*; matches any number of characters up to the last semicolon it finds. To only match up to the first semicolon, the reluctant version .*?; must be used. All greedy operators and the reluctant versions are listed in the following two tables, respectively.
Java Preferences
Programs commonly must store configuration information in some manner that is easy to change and external to the program itself. Java offers utility classes for storing and retrieving system-defined and user-defined configuration information. There are separate hierarchies for the user and system information. All users share the preference information defined in the system tree; each user has his or her own tree for configuration data isolated from other users. This allows for custom configuration, including overriding system values.
The core of the preferences class library is the abstract class java.util.prefs.Preferences. This class defines a set of methods that provides for all the features of the preferences library. Each node in a preference hierarchy has a name, which does not have to be unique. The root node of a preference tree has the empty string (“”) as its name. The forward slash is used as a separator for the names of preference nodes, much like it is used as a separator for directory names on Unix. The only two strings that are not valid node names are the empty string (because it is reserved for the root node) and a forward slash by itself (because it is a node separator). The root node’s path is the forward slash by itself. Much like with directories, absolute and relative paths are possible. An absolute path always starts with a forward slash, because the absolute path always starts at the root node and follows the tree down to a specific node. A relative path never starts with a forward slash. A path is valid as long as there aren’t two consecutive forward slashes in the pathname, and no path except the path to root ends in the forward slash.
Because preferences are implemented by a third-party implementer, changes to the preferences aren’t always immediately written to the backing store. The maximum length of a single node’s name and any of its keys is 80 characters. The maximum length of a string value in a node is 8,192 characters.
The core of the preferences class library is the abstract class java.util.prefs.Preferences. This class defines a set of methods that provides for all the features of the preferences library. Each node in a preference hierarchy has a name, which does not have to be unique. The root node of a preference tree has the empty string (“”) as its name. The forward slash is used as a separator for the names of preference nodes, much like it is used as a separator for directory names on Unix. The only two strings that are not valid node names are the empty string (because it is reserved for the root node) and a forward slash by itself (because it is a node separator). The root node’s path is the forward slash by itself. Much like with directories, absolute and relative paths are possible. An absolute path always starts with a forward slash, because the absolute path always starts at the root node and follows the tree down to a specific node. A relative path never starts with a forward slash. A path is valid as long as there aren’t two consecutive forward slashes in the pathname, and no path except the path to root ends in the forward slash.
Because preferences are implemented by a third-party implementer, changes to the preferences aren’t always immediately written to the backing store. The maximum length of a single node’s name and any of its keys is 80 characters. The maximum length of a string value in a node is 8,192 characters.
Using Preferences
The following example sets a few properties in a node in the user tree, prints out information about the node, and then exports the information to an XML file:
import java.util.*;
import java.util.prefs.*;
import java.io.*;
public class PreferenceExample {
public void printInformation(Preferences p)
throws BackingStoreException
{
System.out.println(“Node’s absolute path: “ + p.absolutePath());
System.out.print(“Node’s children: “);
for(String s : p.childrenNames()) {
System.out.print(s + “ “);
}
System.out.println(“”);
System.out.print(“Node’s keys: “);
for(String s : p.keys()) {
System.out.print(s + “ “);
}
System.out.println(“”);
System.out.println(“Node’s name: “ + p.name());
System.out.println(“Node’s parent: “ + p.parent());
System.out.println(“NODE: “ + p);
System.out.println(“userNodeForPackage: “ +
Preferences.userNodeForPackage(PreferenceExample.class));
System.out.println(“All information in node”);
for(String s : p.keys()) {
System.out.println(“ “ + s + “ = “ + p.get(s, “”));
}
}
public void setSomeProperties(Preferences p)
throws BackingStoreException
{
p.put(“fruit”, “apple”);
p.put(“cost”, “1.01”);
p.put(“store”, “safeway”);
}
public void exportToFile(Preferences p, String fileName)
throws BackingStoreException
{
try {
FileOutputStream fos = new FileOutputStream(fileName);
p.exportSubtree(fos);
fos.close();
} catch(IOException ioe) {
System.out.println(“IOException in exportToFile\n” + ioe);
ioe.printStackTrace();
}
}
public static void main(String args[])
{
PreferenceExample pe = new PreferenceExample();
Preferences prefsRoot = Preferences.userRoot();
Preferences myPrefs = prefsRoot.node(“PreferenceExample”);
try {
pe.setSomeProperties(myPrefs);
pe.printInformation(myPrefs);
pe.exportToFile(myPrefs, “prefs.xml”);
} catch(BackingStoreException bse) {
System.out.println(“Problem with accessing the backing store\n” + bse);
bse.printStackTrace();
}
}
}
The output to the screen is shown here:
Node’s absolute path: /PreferenceExample
Node’s children:
Node’s keys: fruit cost store
Node’s name: PreferenceExample
Node’s parent: User Preference Node: /
NODE: User Preference Node: /PreferenceExample
userNodeForPackage: User Preference Node: /
All information in node
fruit = apple
cost = 1.01
store = safeway
Read 113 times
Published in
Java
Vicky
E-mail: This e-mail address is being protected from spambots. You need JavaScript enabled to view itLatest from Vicky
More in this category:
« Database and Data Patterns
JEE Design Patterns - Presentation Scalability »