.
.
Java Technology Fundamentals Newsletter header
    September 26, 2003    

In this Issue

Welcome to the Java Developer Connection 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 the JDC's New to Java Programming Center.

image Java Programming Language Basics: Class Loading Basics
image Java Bits: Overview of the Swing API
image Making Sense of Java Classes: Abstract Class ClassLoader
image Program Challenge: StartMeUp
image Java Workbook: Java Collections Framework & Hello World
image Online Chat: Java Technology Fundamentals
image Quiz: Test what you learned
image Java Programming Language Web Course
image For More Information: Read articles, Tech Tips, trails, and tutorials that provide more information on the topics discussed here.

.

Java Programming Language Basics

Class Loading Basics

When writing programs for the Java 2 Platform, Standard Edition (J2SE), compilers convert source code into byte codes. Byte codes are a platform neutral format defined in the Java Virtual Machine Specification. This class format is actually language agnostic, so with the right compiler, any language could theoretically be converted into Java byte codes.

When you want to run a program on the Java 2 platform, the JVM doesn't just load the byte codes and run them. Instead, the virtual machine must verify the byte codes with something called a byte code verifier. As a security precaution, it doesn't trust the compiler to generate valid byte codes, as someone could go in and edit those .class files manually. Once verified, the byte codes are passed off to the class loader. As the name might imply, the class loader is responsible for loading classes. Before the class loader loads the class though, the class loader checks to see if the class to load needs any other classes loaded. It then verifies each of those classes, and so on, until all needed classes are verified and loaded.

Verification isn't a simple check like a cyclic redundancy check (CRC) where something like a checksum is added to the end of every class file. Instead, the virtual machine checks that every byte code in the class file is valid and performs a series of validation checks that parts of those instructions are internally valid, too. For instance, while the Java programming doesn't include a 'goto' instruction, the byte codes require something similar for looping, like in a for loop. While the goto address can't be 100% validated, the validator can check that the destination is at the start of an instruction, not the middle. There are also some type safety checks to make sure what a method requires sent to it are actually the expected types, again verifying the compiler didn't accept something that it shouldn't have. In addition, the verifier ensures the first four bytes of the file are 0xCAFEBABE. Failure to verify and validate the bytes for a class file will generate a VerifyError and cause the class to not be loaded.

Access to the byte code verifier is not available unless you are building your own virtual machine. You can't customize it to do more or less verification. However, where permitted by the security manager, access to the class loader is possible. In fact, if you don't like the way the system class loader works, you can change it, or at least replace it for loading non-system classes. This access is provided via the aptly named ClassLoader class, found in the java.lang package. The system class loader looks for the system classes in a particular place and then looks for the remaining classes where the CLASSPATH says to look. If you don't like that behavior, you can replace the class loader with something that would look in a different series of locations or dealt with altered bytes for things like encryption. While the bytes could be encrypted when the class loader loads them from their designated location, the class loader must decrypt the bytes before executing the class code. Another thing using a custom class loader allows you to do is throw it away. This may sound like an odd thing to want, but throwing away the ClassLoader is how you can unload classes from the system.

One of the predefined class loaders offered by the system is the URL ClassLoader, found in the java.net package. With this class you can specify a series of URLs for locations to look for .class files. Then, you can ask to load a class from those locations. The basic process goes as follows:

ClassLoader classLoader = new URLClassLoader(
  new URL(new File("/foor").toURL()),
  new URL(new File("/bar").toURL())
);

This says to create a class loader that will look in the /foo and /bar directories for classes. If they aren't found there, and they aren't system classes, the classes won't be loaded. Of course, once the system does find the classes, the byte code verifier needs to verify them before loading.

Loading the class then involves calling the loadClass method of the ClassLoader.

The whole process of byte code verification and class loading is a bit more involved then this but this provides a high-level overview of the whole process. For addition information about the whole process, read Chapter 5 (Loading, Linking, and Initializing) in The Java Virtual Machine Specification, 2nd edition document.

.
.

Java Bits

Overview of the Swing API (From the Java Tutorial)

The Swing package is part of the Java Foundation Classes (JFC) in the Java platform. The JFC encompasses a group of features to help people build GUIs; Swing provides all the components from buttons to split panes and tables.

The Swing package was first available as an add-on to JDK 1.1. Prior to the introduction of the Swing package,the Abstract Window Toolkit (AWT) components provided all the UI components in the JDK 1.0 and 1.1 platforms. Although the Java 2 Platform still supports the AWT components, we strongly encourage you to use Swing components instead. You can identify Swing components because their names start with J. The AWT button class, for example, is named Button, whereas the Swing button class is named JButton. In addition, the AWT components are in the java.awt package, whereas the Swing components are in the javax.swing package.

As a rule, programs should not use "heavyweight" AWT components alongside Swing components. Heavyweight components include all the ready-to-use AWT components, such as Menu and ScrollPane, and all components that inherit from the AWT Canvas and Panel classes. When Swing components (and all other "lightweight" components) overlap with heavyweight components, the heavyweight component is always painted on top.

More

.
.

Making Sense of the Java Class

Abstract Class ClassLoader (From the API Documenation)

A class loader is an object that is responsible for loading classes. The class ClassLoader is an abstract class. Given the name of a class, a class loader should attempt to locate or generate data that constitutes a definition for the class. A typical strategy is to transform the name into a file name and then read a "class file" of that name from a file system.

Every Class object contains a reference to the ClassLoader that defined it.

Class objects for array classes are not created by class loaders, but are created automatically as required by the Java runtime. The class loader for an array class, as returned by Class.getClassLoader is the same as the class loader for its element type; if the element type is a primitive type, then the array class has no class loader.

Applications implement subclasses of ClassLoader in order to extend the manner in which the Java virtual machine dynamically loads classes.

Class loaders may typically be used by security managers to indicate security domains.

The ClassLoader class uses a delegation model to search for classes and resources. Each instance of ClassLoader has an associated parent class loader. When called upon to find a class or resource, a ClassLoader instance will delegate the search for the class or resource to its parent class loader before attempting to find the class or resource itself. The virtual machine's built-in class loader, called the bootstrap class loader, does not itself have a parent but may serve as the parent of a ClassLoader instance.

Normally, the Java virtual machine loads classes from the local file system in a platform-dependent manner. For example, on UNIX systems, the virtual machine loads classes from the directory defined by the CLASSPATH environment variable.

However, some classes may not originate from a file; they may originate from other sources, such as the network, or they could be constructed by an application. The method defineClass converts an array of bytes into an instance of class Class. Instances of this newly defined class can be created using the newInstance method in class Class.

The methods and constructors of objects created by a class loader may reference other classes. To determine the class(es) referred to, the Java virtual machine calls the loadClass method of the class loader that originally created the class.

For example, an application could create a network class loader to download class files from a server. Sample code might look like:

   ClassLoader loader = new NetworkClassLoader(host, port);
   Object main = loader.loadClass("Main", true).newInstance();

The network class loader subclass must define the methods findClass and loadClassData to load a class from the network. Once it has downloaded the bytes that make up the class, it should use the method defineClass to create a class instance. A sample implementation is:

 class NetworkClassLoader extends ClassLoader {
  String host;
  int port;

  public Class findClass(String name) {
    byte[] b = loadClassData(name);
    return defineClass(name, b, 0, b.length);
  }

  private byte[] loadClassData(String name) {
  // load the class data from the connection
     . . .
  }
}
.
.

Program Challenge

StartMeUp

Create a program the loads a class through a custom class loader, creates a new instance of it, and invokes a method within it.

For the class loader, have the user enter in the URL for its location from the command line. It could be on the web via an http: URL, or on disk through a file: URL. Be sure the .class file for the class to run is not in the normal CLASSPATH, otherwise, the custom class loader won't be used, instead relying on the system class loader.

Pass in the class name and URL from the command line. To allow the program to run against different classes, have each implement Runnable. That way, the program calls run() with any implementation of the interface. You won't have to hard code a class name in the program.

See a possible solution to the Challenge.

.
.

Java Workbook

Collection Framework

Hello World Applet

.
.

Online Chat

Java Technology Fundamentals

Are you new to Java technology? Do you have a basic question about Java technology? Join this chat and get your questions answered by John Zukowski, noted author of many books on Java technology. His latest books are:

Mastering Java 2, J2SE 1.4

Learn Java with JBuilder 6

John is also coauthor of this newsletter, and will answer your questions on Tuesday, September 30, at 11 A.M.-to-noon Pacific time (6 P.M.-to- 7 P.M. GMT).

.
.

Quiz

Java Technology Fundamentals

Test what you learned about class loading in this online quiz.

.
.

Java Programming Language Web Course

Practice Exam for Sun Certified Programmer for the Java 2 Platform
ePractice Exams help certification candidates prepare for Sun certification by acquainting them with the format of the exam and its questions, providing instant feedback regarding skill levels and gaps, and suggesting specific Sun training to fill those gaps. The exams include sample test questions, the correct answers including explanations, and suggestions for future study.

Implementing Intermediate Java Programming Language Concepts
This course introduces students to intermediate object-oriented programming (OOP) concepts such as inheritance and encapsulation. Additionally, arrays are introduced as a mechanism for storing and accessing similar data. ObjectTool, a new teaching tool developed by Sun, is used throughout the course to help the learner more readily understand the syntax and semantics of the language. Students taking this course can receive a solid basis in the Java programming language upon which to base continued work and training.

.
.

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.

.
.
.

Reader Feedback

  Very worth reading    Worth reading    Not worth reading 

If you have other comments or ideas for future newsletters, please type them here:

 

Have a question about Java programming? Use Java Online Support.

.
.

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


Comments? Send your feedback on the Java Technology Fundamentals Newsletter to: dana.nourie@sun.com

Go to the subscriptions page to subscribe or unsubscribe to this newsletter.

ARCHIVES: You'll find the Java Technology Fundamentals Newsletter archives at:
http://developer.java.sun.com/developer/onlineTraining/new2java/supplements/


Copyright 2003 Sun Microsystems, Inc. All rights reserved. 4150 Network Circle, Santa Clara, CA 95054

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