|
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.
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
Autoboxing Basics
One of the new features of the J2SE v5 (aka Tiger) release is a feature called autoboxing. Some people confuse autoboxing with casting, so let's explore the two features.
Casting support has been around since the beginning of the Java programming language. It involves placing parentheses and a datatype before a variable or value, to treat how it is accessed from one type to another. For instance...
// Bad code
float f = 3;
int i = f;
would result in a compilation error. While the value in the variable f is the value 3, it is 3 as a floating point number. Converting a float variable to an int variable could result in the loss of precision, so a compilation error happens, unless you add a casting operation:
float f = 3;
int i = (int)f;
The (int) here is a cast operation. Had you wanted to put the int variable into the float field, this would not need a casting operation, since the full range of int values fit into the range of available float values. Here, the reverse compiles fine:
int i = 3;
float f = i;
What's this have to do with autoboxing? Autoboxing is the automatic conversion of numeric objects to primitives, and vice versa. For instance, each of the following lines results in a compilation error, prior to V5
// Bad code in 1.4
Integer i = 5;
int j = i;
But, the same code in version 5 is perfectly fine. And, that's exactly what autoboxing (and unboxing) is. Prior to version 5, converting from int to Integer and back again typically involved using the static methods of the java.lang.Integer class:
// 1.4 conversion code
int i = 4;
Integer j = Integer.valueOf(i);
or
Integer k = new Integer(i);
int l = j.intValue();
As a more complete example, the following program sums up the numbers passed in from the command line. The first loop goes straight from String to int. The second pass goes from String to Float to float, possibly adding in some additional numbers.
public class Convert {
public static void main(String args[]) {
int sum = 0;
for (int i=0, n=args.length; i<n; i++) {
try {
// Convert String to int
sum += Integer.parseInt(args[i]);
} catch (NumberFormatException ignored) {
// skip it
}
}
System.out.println(
"Sum of int args on command line is: " + sum);
float sum2 = 0;
for (int i=0, n=args.length; i<n; i++) {
try {
// Convert String to Float then box to float
sum2 += Float.valueOf(args[i]);
} catch (NumberFormatException ignored) {
// skip it
}
}
System.out.println("Sum of float args on command line is: "
+ sum2);
}
}
While autoboxing is convenient, keep the garbage collector in mind. The second pass through the args array above creates a Float object for each argument. It doesn't need to as you can create a float directly from a String with Float.parseFloat(String). Autoboxing is convenient, but be careful with its usage as unnecessary object creation slows things down in the long run.
Test what you learned in this article about autoboxing.
Java Bits 2
java.net: A Community for Everyone
Java.net is popular for its open source projects, such as the JOGL API Project, NetBeans, JXTA, and Project Looking Glass. These projects attract developers who are experienced in working on the Java platform. From this, it's easy to get the impression that java.net is not for developers new to the Java platform, but it is. In fact, the big development projects are only a portion of java.net. Above all else, java.net is a community, and much of the site is devoted to educating many types of people about the Java platform, from new programmers to educators to hard core developers.
java.net provides a central site for articles, conversations, news, and innovative development projects related to Java technology. The community can grow with industry associations, software vendors, universities, and individual developers and hobbyists as they meet, share ideas, and use the site's collaboration tools. Within the overall main community, sub-communities emerge, as people from diverse areas and backgrounds uncover synergies and create solutions that render Java technology even more valuable.
No matter what your experience is with the Java platform, you are welcome to be a part of any of those communities or help and encourage a community more suitable to your needs and interests. In addition, educators are encouraged to bring their classes online and work on projects collaboratively.
Read more
Making Sense of the Java Classes
Data Transfer and Package java.awt.datatransfer
Data transfer is a frequently used and important function in software applications from selecting a block of text and moving it to a different paragraph in a word processor to moving images or diagrams around an a presentation application. The Java API provides support for data transfer through transferring data to and from the clipboard, and using drag and drop within or between applications. This month you'll learn about data transfer through using the clipboard and the Clipboard class.
A clipboard is an area within memory that stores information for support of cut, copy, and paste tasks. To transfer data through the clipboard or through drag and drop, you need to become familiar with the java.awt.datatransfer package, which provides interfaces and classes for transferring data between and within applications. It defines the notion of a transferable object, which is an object capable of being transferred between or within applications.
Package interfaces:
Transferable -- Defines the interface for classes that can be used to provide data for a transfer operation.
ClipboardOwner -- Defines the interface for classes that provide data to a clipboard.
FlavorMap -- A two-way Map between "natives" (Strings), which corresponds to platform specific data formats, and "flavors" (DataFlavors), which correspond to platform-independent MIME types.
FlavorTable -- A FlavorMap which relaxes the traditional 1-to-1 restriction of a Map.
An object identifies itself as being transferable by implementing the Transferable interface. A transferable object must be able to provide a list of formats called "data flavors", ordered from the most-richly descriptive flavor to the least. It must also be able to return the data in the form of an Object reference when requested in a particular flavor, or throw an exception if that flavor is not supported or the data is no longer available.
Data flavors are ways of representing data. For instance, MIME stands for Multipurpose Internet Mail Extensions. Data flavors are just the way of representing MIME types within your programs. MIME types have textual representations like text/html or text/plain. Data flavors, on the other hand, are classes. Flavors get created by textual representations, but they are classes in the system. They are used by the data transfer mechanism so that when you place something on the clipboard, you can state what type of object it is. When someone gets something off the clipboard, that person can ask what flavors of data are available. If all the flavors are ones they don't support, they can't get the object off the clipboard.
You provide data through the data transfer mechanism with multiple flavors so that you can support the widest possible audience. For instance, if you were to copy text within a word processor, you would want to retain the formatting information. You specify that the transferable data can be represented by one or more flavors, you provide the means to check if a particular flavor is supported. In addition, you provide the mechanism to get the data for a specific flavor. The Transferable interface does that for you.
DataFlavor itself is a class. It makes several default flavor and MIME types available through class constants and a method. Going from simplest to most complex, you get predefined flavors for plain text, strings, a file list, and images. There are also three MIME types defined for local, serialized, and remote objects. From the MIME types, you can create the flavors.
getTextPlainUnicodeFlavor
stringFlavor
javaFileListFlavor
imageFlavor
javaJVMLocalObjectMimeType
javaSerializedObjectMimeType
javaRemoteObjectMimeType
When you make something available to the clipboard, you don't actually copy the data there. Instead, you copy a reference and that reference is accessed when you want to take something off the buffer. Because you may need to keep track of that external reference, the clipboard will actually notify you when something else replaces an item on the clipboard. That notification is handled by the ClipboardOwner interface:
public interface ClipboardOwner {
public void lostOwnership(Clipboard clip,
Transferable t);
}
There is no built-in support for having multiple items on the clipboard. When something new is added to the clipboard, the old reference is thrown away.
To demonstrate the use of the system clipboard, take a look at the StringSelection class. It implements both the Transferable and ClipboardOwner interfaces. Use it to transfer strings to the clipboard. Adding a string to the clipboard involves creating a StringSelection item and setting the clipboard contents, through its setContents method. Here's what the code for that task looks like.
// Get String
String selection = ...;
// Convert to StringSelection
StringSelection data = new StringSelection(selection);
// Get system clipboard
Clipboard clipboard =
Toolkit.getDefaultToolkit().getSystemClipboard();
// Set contents
clipboard.setContents(data, data);
Getting the clipboard data is a little more involved, but not too difficult. There are basically three steps involved:
- Get the reference to the data from the clipboard, the
Transferable object.
- Find a flavor you can handle that it supports, where
DataFlavor.stringFlavor is for text strings.
- Get the data for that flavor.
You also need to do some exception handling, as an UnsupportedFlavorException or IOException could be thrown.
// Get data from clipboard
Transferable clipData =
clipboard.getContents(clipboard);
// Make sure not empty
if (clipData != null) {
// Check if it supports the desired flavor
if (clipData.isDataFlavorSupported
(DataFlavor.stringFlavor)) {
// Get data
String s = (String)(clipData.getTransferData(
DataFlavor.stringFlavor));
// Use data
...
}
}
The following example program involves a text area and two buttons, Copy and Paste. When the Copy button is selected, the current selection within the text area is copied to the system clipboard. When the Paste button is selected, the current selection is replaced with the contents of the system clipboard. If the flavor of data on the clipboard is not supported, the system beeps.
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import javax.swing.*;
public class ClipboardExample {
public static void main(String args[]) {
JFrame frame = new JFrame("Copy/Paste");
Container contentPane = frame.getContentPane();
final Toolkit kit = Toolkit.getDefaultToolkit();
final Clipboard clipboard =
kit.getSystemClipboard();
final JTextArea jt = new JTextArea();
JScrollPane pane = new JScrollPane(jt);
contentPane.add(pane, BorderLayout.CENTER);
JPanel bottom = new JPanel();
JButton copy = new JButton("Copy");
bottom.add(copy);
ActionListener copyListener = new
ActionListener() {
public void actionPerformed(ActionEvent e) {
String selection = jt.getSelectedText();
StringSelection data = new
StringSelection(selection);
clipboard.setContents(data, data);
}
};
copy.addActionListener(copyListener);
JButton paste = new JButton("Paste");
bottom.add(paste);
ActionListener pasteListener = new
ActionListener() {
public void actionPerformed(ActionEvent
actionEvent) {
Transferable clipData =
clipboard.getContents(clipboard);
if (clipData != null) {
try {
if (clipData.isDataFlavorSupported(
DataFlavor.stringFlavor)) {
String s =
(String)(clipData.getTransferData(
DataFlavor.stringFlavor));
jt.replaceSelection(s);
} else {
kit.beep();
}
} catch (Exception e) {
System.err.println("Problems getting data:
" + e);
}
}
}
};
paste.addActionListener(pasteListener);
contentPane.add(bottom, BorderLayout.SOUTH);
frame.setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.show();
}
}
When trying out the program, copy and paste between native applications like your word processor. Because you are using the system clipboard, the program will transfer the contents of the clipboard.
Your application should look something like the image below:
Next month, look for information on drag and drop.
Sun's J2SE Web Courses
Understanding the Building Blocks of Java Technology
This course provides you with the basic syntax for creating variables and objects, identifies keywords and data types used in the Java programming language, covers the essentials for working with arrays, describes the main parts for defining a class, and introduces interfaces. In addition, this course uses a new learning tool, called the ObjectTool (patent pending), specifically created to help you more readily understand object-oriented concepts.
Find out more
Sun's Server-Side Web Courses
Using Java Servlet Technology in Web Applications
This course provides an understanding of developing web applications using Java technology servlets. The modules in this course describe specific web application features, such as: session management, security, error handling, and concurrency control.
Find out more
Sun's Instructor Led Courses
Implementing Java Security
Securely transferring vital data in the Internet world requires sophisticated technologies. The Java development language has several built-in mechanisms as well as a number of extensions that elegantly address security concerns. Recently updated for the Java 2 SDK, Standard Edition, Implementing Java Security provides students with a hands-on development experience using Java security technologies in both existing applications and new applications that they create.
Practical work: This course provides students with plenty of lab time for practical experience implementing all of the major Java technology security features presented in the course.
Find outmore
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.
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.
|