.
.
developers.sun.com java.sun.com
.
    March 10, 2005    

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.

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.

- Java Programming Language Basics: Filing Systems and Class File
- Making Sense of the Java Classes & Tools: Getting Started with an Integrated Development Environment (IDE)
- Java Bits: Basic Memory Management
- Program Challenge
- What's New on java.net: Join the Java Tools Community Controlling Code in Your Open Source Project Timing is Everything
- Sun's Web Courses: J2SE 5.0 New Features and Behavioral Changes: Overview Overview of the Sun Java Studio Creator IDE
- Sun's Instructor-Led Courses: Java Programming Language
- For More Information

.

Java Programming Language Basics

Filing Systems and Class File by John Zukowski

An operating system.s filing system is one of the most basic services provided to applications. Historically, it was one of the very first services to be developed. Today, all filing systems allow a hierarchical directory structure of arbitrary complexity to organize files of almost equally arbitrary length (4GB is a common system limit per file). Filenames identify files and are usually limited in length to 32,256 characters, though earlier MS-DOS systems had a now familiar 8.3 character format and limit.

Although all filing systems are essentially identical in terms of these basic services, their exact implementations are different.

File Class

To shield applications from this incompatibility obstacle, the java.io.File class defines platform-independent methods for manipulating a file maintained by a native filing system. Looking at the complete list of supported methods in the javadoc, you'll notice that the File class does not allow you to access the contents of the file. There are no read() or write() methods of File to let you do this. Class File primarily names files, queries file attributes, and manipulates directories or temporary files, all in a system-independent way. The following is a description of what you can do with files without opening them.

Naming Files

Files are named in two manners. You can either provide both a directory and a file within the directory, or you can provide both, combined into one value. Either way, you are providing the full name of a file you wish to potentially access. The benefit of providing a directory and file name separately is that you don't have to worry about how to combine the two.

For instance, on Microsoft Windows-based platforms, the separator character is the backward slash character (.\.). On UNIX platforms, it is the forward slash character (./.). While you can ask the File class what the separator character is through the separator class variable, why bother combining the two terms yourself if you can let the constructor of the File class do it for you?

To demonstrate, the following code fragment attempts to create three File objects. Each line does succeed in creating a File object.

   File f1 = new File("tmp/foo");
   File f2 = new File("tmp", "foo");
   File f3 = new File(new File("tmp"), "foo");

Querying File Attributes

Class File provides a handful of methods for querying a minimal set of file attributes:

If the file exists
If the file is read protected
If the file is write protected
If the file is, in fact, a directory
If the file is hidden
If the file is specified as an absolute location

Discovering other common file attributes, such as whether a file is a system or an archived file, is not supported, as this designation is platform-specific.

The following program shows how to use a File instance to query the attributes of a file. The file is specified as a command line parameter:

   import java.io.*;
   public class Attr {
     public static void main (String args[]) {
       File path = new File(args[0]);
       String exists   = getYesNo(path.exists());
       String canRead  = getYesNo(path.canRead());
       String canWrite = getYesNo(path.canWrite());
       String isFile   = getYesNo(path.isFile());
       String isHid    = getYesNo(path.isHidden());
       String isDir    = getYesNo(path.isDirectory());
       String isAbs    = getYesNo(path.isAbsolute());
       System.out.println("File attributes for '" 
                                       + args[0] + "'");
       System.out.println("Exists        : " + exists);
       if (path.exists()) {
         System.out.println("Readable      : " + canRead);
         System.out.println("Writable      : " + canWrite);
         System.out.println("Is directory  : " + isDir);
         System.out.println("Is file       : " + isFile);
         System.out.println("Is hidden     : " + isHid);
         System.out.println("Absolute path : " + isAbs);
       }
     }
     private static String getYesNo(boolean b) {
       return (b ? "Yes" : "No");
     }
   }

You can experiment with this program by passing in various filenames and directory names, either relative or absolute. An absolute filename would be one that started at the root level of the file system, like C:\. Of course, while C:\ is absolute, it is not a file. The path of the directory at that level would be C:\., where the "." specifies the directory file.

Manipulating Directories

A handier program would be one that could list the contents of a directory, like the dir or ls commands in most operating systems. Fortunately, class File supports directory-list generation through its list and listFiles methods. Here's another program that recursively (that is, calling upon itself) lists directories and their contents:

   
   import java.io.*;
   import java.util.*;
   public class Dir {
     static int indentLevel = -1;
     static void listPath(File path) {
       File files[];  // list of files in a directory
       indentLevel++; // going down...
       // create list of files in this dir
       files = path.listFiles();
       // Sort with help of Collections API
       Arrays.sort(files);
       for (int i=0, n=files.length; i < n; i++) {
         for (int indent=0; indent < indentLevel; indent++) {
           System.out.print("    ");
         }
         System.out.println(files[i].toString());
         if (files[i].isDirectory()) {
           // recursively descend dir tree
           listPath(files[i]);
         }
       }
       indentLevel--; // and going up
     }
     public static void main (String args[]) {
       listPath(new File(args[0]));
     }
   }

The program relies on a couple of interesting concepts. First of all, it calls itself recursively in the statement listPath(files[i]). This repeated invocation of the listPath method restarts listPath with a new path, initialized to contain the deeper directory to list.

The directory listing is sorted with the help of the Arrays class of the Collections Framework.

To highlight the current directory level, the contents of a directory are indented according to its nesting level in the filing hierarchy. The depth of the recursion level, tracked in the class variable indentLevel, determines this nesting level.

When a method exits, class variables are not destroyed, as are simple method variables. The program relies on this behavior to track the recursion level across multiple invocations of listPath.

Manipulating Temporary Files

One nice feature of the File class is support for temporary files. Thanks to the static createTempFile methods and the java.io.tmpdir system property, you can guarantee that the File object created by the method did not previously exist. Also, by calling deleteOnExit, you can ensure the file will be deleted if the Java environment ends naturally. The general framework for usage follows:

   
   // prefix and suffix
   File temp = File.createTempFile("sun", ".tmp");
   temp.deleteOnExit();
   // use like any other File

Summary

There's so much more you can do with the help of the File class. While you can get file attributes, list directories, and create unique temporary files without ever opening the file, just think what you can do if you were to open the file.

.
.

Making Sense of the Java Classes

Getting Started with an Integrated Development Environment (IDE) by Dana Nourie

Many people learn to program using a simple text editor, but eventually most end up using an integrated development environment (IDE) for building applications. An IDE is a set of tools that aids application development. Most IDEs have tools that allow you to:

  • Write and edit source code
  • See errors as you type
  • See highlighted code syntax
  • Automate repetitive tasks
  • Compile code
  • Browse class structures
  • View JavaDocs
  • Use drag-and-drop utilities for easy building of features, such as graphic objects or creating database connections

In addition, some IDEs do the following:

  • Provide templates for quick creation of JSP pages, servlets and other web components
  • Provide code-completion as you type
  • Automatically create classes, methods, and properties
  • Integrate with source code repositories, such as CVS
  • Integrate with web application servers, such as Apache Tomcat
  • Integrate with build utilities, such as Apache Ant
  • HTTP monitoring for debugging web applications
  • Unified UI for debugging Java code
  • Macros and abbreviations
  • Refactor code
  • Provide UML support

It's no wonder developers move to an IDE, but which IDE is right for you? Which features do you need? Sun Microsystems supports three IDEs for the Java platform: NetBeans, Sun Java Studio Creator, and Sun Java Studio Enterprise. The following descriptions should help you decide which IDE is best for your development needs.

The NetBeans Platform and IDE

The NetBeans Integrated Development Environment (IDE) 4.0 platform is an open source IDE. NetBeans is written in the Java programming language and provides the services common to desktop applications, such as window and menu management, settings storage, and so forth. It's also the first IDE to fully support JDK 5.0 features.

NetBeans also provides support for CVS/Version control access, FTP functionality, databases, scripting, and servlet and JavaServer Pages support through Tomcat.

With NetBeans you can create desktop applications, as well as web applications. NetBeans contains extensions to the Swing APIs that make it easier to write in a syntax-highlighting code editor. The editor is capable of "mixed-mode" operation in which correct syntax highlighting, code-completion, formatting, and macros are provided for documents that contain content in more than one language, such as a JSP page containing both HTML and Java code.

If you are writing applications to run strictly on the desktop, NetBeans provides everything you need. In addition, it makes creating menuing systems easy. Rather than write code to manage menus, simply write the logic that's important - what should *happen* when a user clicks on a menu item.

You can also create web applications with NetBeans, but the learning curve in this area is a bit steeper than using Sun Java Studio Creator.

NetBeans is also good for programmers and developers new to the Java programming language because it's simpler to parse through the output of the compiler when dealing with an application than when dealing with a call stack from an application server.

Download the latest free version of the NetBeans IDE

Sun Java Studio Creator IDE

While NetBeans is great for creating desktop applications, the Sun Java Studio Creator IDE is great for quick and easy web application development. In addition, this IDE is built on NetBeans, starting with a subset of the functionality and extending it.

Java Studio Creator allows you to build applications visually, like with MS Visual Basic for building asp.net applications. The programming part is cleanly separated from the UI part. With Java Studio Creator, the IDE takes care of a lot of the plumbing behind the UI.

For example, in Java Studio Creator, you rarely need to modify a JSP file directly. Instead, you use the GUI to draw the UI, and then put your code into event handlers in a Java class.

The rapid visual drag-and-drop features are based on JavaServer Faces technology, which is a framework for building user interfaces for web applications. A graphical user interface (GUI) is used for manipulating JavaServer Faces components, as well as visually defining page flow. There's also graphical support for easily working with databases and web services.

In addition, you can customize applications with localization, internationalization, and custom validation.

For programmers and developers new to the Java platform, Java Studio Creator is an easy-to-use and powerful tool for building web applications.

For $99, you get the Java Studio Creator software and a subscription that provides technical support from Sun, access to articles and tutorials that are private, and access to a community forum where you can give and receive information about using the Java Studio Creator IDE.

Download a 30-day trial version of Java Studio Creator, which includes a temporary license key providing 30-day trial access to all the SDN Standard subscription content.

Sun Java Studio Enterprise

This IDE is a powerhouse set of tools that provides a powerful, integrated framework for enterprise-grade, rapid web application development, offers enhanced debugging and development support for Web services and Java 2 Platform, Enterprise Edition (J2EE) application development.

Like Java Studio Creator, Java Studio Enterprise is also built on NetBeans and extends it. It also enables smart code editing with refactoring, performance tuning of applications with an optimal end-user experience, and simulates usage behavior for web applications with built-in load generation.

Java Studio Enterprise provides a model-driven analysis, design, and development environment that leverages Unified Modeling Language (UML). This integrated feature reduces complexity and increases visual clarity across software development projects, ensuring that a sound architecture is established and communicated throughout the enterprise.

With Java Studio Enterprise, you can jumpstart the development process using features, such as live, roundtrip (bidirectional) markerless model, code synchronization, and code-reverse engineering. In addition to class diagrams, roundtrip model to code synchronization is available from sequence diagrams as well as all other diagrams containing class nodes.

This advanced development capability is complemented with features such as:

  • A powerful HTML documentation engine to produce project documents that are vital to a team's productivity
  • An intuitive layout facility that enables the most complex of application designs to be easily visualized, navigated, and understood
  • Wizard-driven automation of common tasks, such as code-reverse engineering, live roundtrip model, and source code synchronization, integrated with model-driven version control

Java Studio Enterprise resources and services are delivered through a developer portal. Developers can contact a team of engineers for product support and participate in discussion forums where questions can be posted to a community of developers and Sun engineers. In addition, a comprehensive knowledge base is available with powerful search capabilities for answers to common problems. Interactive webinars, chats, and code camps are frequently provided, enabling developers to interact with experts and innovate using the latest Sun technologies. This portal also provides access to the latest releases of Java Studio Enterprise software.

For the programmer or developer new to the Java platform, Java Studio Enterprise might have a steep learning curve, but it will definitely get the job done.

If you want to switch to Java Studio Enterprise from some other IDE, Sun has several migration guides published to help you make that transition:

A free 90-day trial of Sun Java Studio Enterprise 7 is available for the Solaris and Windows platforms in three languages - English, Japanese, and Simplified Chinese. After completing your 90-day trial you can easily purchase a full license version online.

.
.

Java Bits

Basic Memory Management by Robert Eckstein

Almost every modern operating system (OS) manages the memory of the computer system where it resides. Not only must it do so for itself, but also for any applications that run under it. If the OS runs out of memory, it cannot spawn new processes. At best,it denies applications that are currently running new memory, which could cause them to crash. At worst, the OS itself crashes.

Every application that runs in an OS environment, therefore, must keep track of its own memory. Not only is it responsible for allocating any needed memory from the operating system, it must also be responsible for alerting the OS that it is finished with memory and it can be reclaimed by the OS for use elsewhere.

With C and C++, the programmer is responsible for doing both tasks, through the use of the malloc (C) and new (C++) commands, as well as the free (C) and delete (C++) commands. In C, for every malloc(), there should be a free(). In C++, for every new(), there should be a delete().

The problem comes in that programmers may not know the best time to free memory, or they may simply forget to do so. This is especially troublesome when new memory is allocated within each iteration of a loop, and the resulting memory is never reclaimed. In such a case, the application is said to have a "memory leak." As long as the application continues running, more and more memory is allocated to it until it eventually depletes the OS and it crashes.

Memory leaks can be a major problem with C and C++ programmers. This is why the Java runtime system allows programmers to allocate memory with the new() command, but never requires them to free memory. Instead, the Java runtime system uses a special process that runs quietly in the background called a Garbage Collector (GC). The GC hunts out memory that is no longer referenced by anything inside the program, and reclaim it for the OS on behalf of the Java application.

The penalty for use of a runtime GC depends on the system. With most modern PCs or servers, the cost is negligible, as the Java runtime system will perform this task while the application is idling or waiting for user input. With smaller mobile devices, however, there can occasionally be a small performance penalty, especially if the system cannot spawn new threads. Even in the worst case, however, programmers can explicitly force the Java runtime system to perform a GC at the most opportune times, making any such penalty oblivious to the user.

.
.

Program Challenge

Expand upon the Dir program from this tip to accept wildcards, to limit the subset of files listed.

For instance, running the following command would list only those files that matched the "*.java" filename pattern in the c:\temp directory.

java Dir c:\temp *.java

See possible solution.

.
.

What's New on java.net

Join The Java Tools Community

See possible solution.

Java Tools Community is gathering place for those interested in Java Development Tools, where you'll find news, articles, discussions, great open source tools and all the help you'll need to start up your project.

Controlling Code in Your Open Source Project

How do you manage an open source project? Read about the problems and solutions to managing an open source project in this tip on java.net.

Timing is Everything by Chet Haase

Tick, Tick, Tick, Tick

Any time you introduce dynamic effects, animations, or time-based events to a Java application, you find yourself re-implementing the same functionality you have written for every application that required timing or animation. The built-in APIs are powerful, but they require that you write a fair amount of boilerplate code. This article considers the current situation, what is needed in a timing framework, and example code contained in a project posted on java.net: timingframework.dev.java.net.
Read more

n2java Forum Question

A new2java project member wants to know how to design a TreeTable using Swing, that has a mechanism to show/hide the rows/columns. Can you help him with a code example?

Register and add to the new2java project by sharing your favorite Java information resources, your coding projects, and conversation to the forums.

.
.

Sun's Web Courses

Free J2SE 5.0 Overview Web-based Course ($50.00 US value)

Effective March 1st 2005 through June 30, 2005, get the full overview of the J2SE 5.0 changes by registering for a free J2SE 5.0 Overview Web Course: WJT-2761 New Features & Behavioral Changes. This course is normally priced at $50.00.

Also, take $250 off a 3-5 day Java course with the JDK 5.0 web-based course between March 1st and June 30, 2005. When you purchase the Java WJO-2762 web-based training course you will receive $250 off any 3-5 day Java instructor-led training course. The web-based course and Java technology course must be purchased at the same time for credit to be applied. Use priority code WW35JVC when you register for the two courses. You must complete both classes by July 1, 2005 to qualify for this offer.

Overview of the Sun Java Studio Creator IDE (WJO-1000)

This course provides students with an overview of the technical features and capabilities of Sun Java Studio Creator, in addition to demonstrations that show some of the capabilities that facilitate application development, such as enabling page navigation, integrating database information, and using Web Services in web applications.

.
.

Sun's Instructor-Led Java Courses

Java Programming Language (SL-275)

The Java Programming Language course provides students with information about the syntax of the Java programming language; object-oriented programming with the Java programming language; and creating graphical user interfaces (GUIs), exceptions, file input/output (I/O), and threads and networking. Programmers familiar with object-oriented concepts can learn how to develop Java technology applications. The course uses the Java 2 Software Development Kit (Java 2 SDK).

.
.

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.

As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform.

.
.
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 2005 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