Your Federal Quarterly Tax Payments are due April 15th Get Help Now >>

Java Interview questions by gcrqtp

VIEWS: 641 PAGES: 61

Java Interview questions for web developers and application developers

More Info

           Java Interview questions

What are the difference between java.sql package and javax.sql

java.sql.* package is used for the basic jdbc connections.
javax.sql.* package is used for the advance jdbc. Advance is connection
pooling, rowsets...ect.

What is the use of volatile and transient modifiers?

Transient: The transient modifier applies to variables only and it is not stored
as part of its object's Persistent state. These variables are not serialized.
Transient instance fields are neither saved nor restored by the standard
serialization . You have to handle restoring them yourself.Volatile: Volatile
modifier tells the compiler that the variable modified by volatile can be
changed unexpectedly by other parts of the program. For example a Variable
might be read from Cache and not update the content if it has been changed
by another thread. Specifying a variable as volatile tells the JVM that any
threads using that variable are not allowed to cache thatvalue at all. Making
the Variable Volatile will ensure that the compiler will get the content of the
variable every time it is used and not cache its content. If not used Carefully
this modifier might introduce bugs.
If an object is garbage collected, can it become reachable again Once an
object is garbage collected, it ceases to exist. It can no longer become

What releases of Java technology are currently available?

The Java Platform, Standard Edition (Java SE), previously refered to as J2SE,
is currently shipping from Sun Microsystems, Inc. in the form of the Java
Development Kit (JDK), and Java Runtime Environment (JRE). The current
releases of the software, and links to older versions, are available from the
Java SE Downloads Page.
What do the releases contain?

Each release of the Java SE platform includes the Java Compiler, Java Virtual
Machine*, Java Class Libraries, Java AppletViewer, Java Debugger and other
tools. For more information, please see:
Latest Release
Java SE Technologies
Java SE Documentation


On what platforms is Java SE technology available?

Sun provides the Java SE for use with the Solaris Operating Environment,
Microsoft Windows, and Linux platforms.
Details of Sun's Supported Configurations for our latest release
Details of Sun’s Supported Configurations for previous releases
Additional platform support is available through Sun's network of licensees

How do I learn the Java programming language?

Training available
The New to Java Center is a growing collection of links to articles, tutorials,
online books, and software downloads.
The award-winning Java Tutorial is a searchable introduction to object-
oriented programming with the Java platform.
Complete summary of educational resources are indexed at the Java
Technology Learning pages.

What can you tell me about the current Java platform release?

Java SE 6 overview provides a high level overview of the key features in this
latest release. Full details on the Java Community Process (JCP) approved
features of the release are available on the related Java Specification Request
(JSR) Page.

What is a Java SE update release?

A Java SE update release provides all the latest fixes and enhancements for a
Java SE product release family. Update releases contain a limited number of
high priority bug fixes. On occasion, update releases may also resolve
security issues as identified by the Sun Alert notification program. Update
releases are available to end-users and developers in the form of a complete
Java Runtime Environment (JRE), and Java Developer Kit (JDK).

What is the frequency of update releases?

Sun delivers update releases, for the latest product release family,
approximately 4 times per year. Update releases for earlier supported
product release families are less frequent. Update releases for product
releases which have reached their end of life (EOL), are available to
customers who purchase a vintage support contract.
Is the latest update release compatible with earlier update releases and the
initial product family release?

Sun performs rigorous internal testing (regression, functionality, and
stability) to ensure the quality and compatibility of family update releases.
Sun intends and expects Java SE update releases to be upgradeable by
customers without regressions.


What should I do if my application breaks after installing an update

In the event that a product family update introduces any regression from
earlier behavior, customers are encouraged to report the problem to Sun
immediately and we will make our best efforts to resolve the issue promptly.
Customers with a Sun support contract can report a regression through their
regular support channels. Customers who do not have a Sun support contract
can report a regression online at:
Trademark and Licensing

What are the trademark guidelines for the Java SE platform?

Sun's Trademark and Logo Usage Requirements are listed on this page:
Is Java technology free? Where can I get information on licensing?

Binary Code: The Java SE platform binaries (JDK and JRE) are licensed under
Sun's Binary Code License (BCL) with Supplemental Terms. For most
developers and end-users, the binary JDK and binary JRE are all that's
needed to experience the world of Java technology. USE: The binary JDK and
JRE are available at no-fee from Sun (per terms of the BCL) for use with
desktop personal computers. JDK or JRE use for embedded devices and other
computing environments may require a license fee from Sun. Read more
about embedded use of Java SE, or contact your local Sun office to obtain a

Redistribution: Both the JDK and JRE can be freely redistributed with value-
add (per terms of the BCL). In addition, personal computer manufacturers
and distributors may become authorized to pre-install the JRE on Windows
operating system based personal computers. » Read More

Source Code: The JDK source code is available for researchers and others
interested in exploring the details of the JDK. Each release has its own
license or set of licenses which frequently includes the Sun Community
Source License (SCSL) terms. Sun has recently started offering simplified
access to the JDK source code under the a new Java Research License (JRL).
For more information on the JRL. Note that in either case (SCSL or JRL), if
you decide to use your project internally for productive use or distribute your
product to others, you must sign a commercial agreement and meet the Java
compatibility requirements. Contact your local Sun office to obtain an

Documentation: Generally, the Java SE documentation is not redistributable.
Individuals can download the Java SE documentation for their own use or
simply browse online. For More information on documentation redistribution


Finding a specific License: Each release has it's own license for binary code,
source code, and documentation, available on the download page.
Who is licensing Java technology?

See the list of Java SE Authorized Licensees.
Can you comment on another company's plans for licensing and using Java

No, we need to let other companies speak for themselves.

Can I use Sun's Java technology logos?

Sun does not authorize the use of the Duke character/logo or the Java
platform logo, also called the "steaming cup" or Java Technology Logo.
However, there are a number of logo usage programs available. For more
information about this, please see our Licensed Logos page.
Auto download licensing terms for Java SE:
Where do these new licensing provisions come from?

Java SE (J2SE) version 1.4 introduced Java Web Start technology as part of
the core Java platform. Java Web Start allows Java applications to be
downloaded and run from a Web browser, in the same way that Java-based
applets are downloaded and run today.
How does Java Web Start work?

When a user clicks on a Java Web Start link, a file called a JNLP file is
downloaded and then read by the Java Web Start helper application. The
JNLP file is a small XML document that contains information about the
application that the user is trying to launch, where the application is located
on the network, the application version, and the version of the Java Runtime
Environment (JRE) that is required to run the application. The JNLP file is
authored by the application provider, and serves as a set of instructions that
Java Web Start will use to download, install, run, and update the application
when a new version is available.
Is this a change from the existing Java security model?

No. Java applications still run in the Java "sandbox," and the Java SE security
model is preserved so that malicious code cannot be downloaded and run on
the client machine. In other words, Java Web Start extends the same Java
SE security model used for applets to now include Java applications. A Java
application can request direct access to local machine resources such as the
file system. In these cases, the user must grant the application permission to
operate outside of the sandbox, and this is accomplished by presenting
warning/permission dialogues to the end user.
Where does the automatic software updates from Sun come into play?

Java Web Start provides application providers the ability to target a specific
version of the Java Runtime Environment for their applications. For example,


an application provider may develop, test, and deploy an application based
upon version 1.3.1 of the JRE. If the application provider then wishes to take
advantage of new functionality in a newer release of the JRE, such as version
1.4, the application provider simply changes the target JRE in the JNLP file
from 1.3.1 to 1.4. The next time a user runs the application, Java Web Start
will detect that the application should now be run on version 1.4, and will
automatically download and install version 1.4 if it is not already present on
the client machine.

Sun Microsystems, Inc. does not proactively and automatically initiate
software updates of the JRE. An updated JRE will only be downloaded and
installed when a user attempts to run a Java Web Start enabled application
that requires a version of the JRE that is not present on the client machine.
Can the application provider update their applications as well?

Yes. In the same way that a new version of the JRE can be downloaded and
installed, the application provider can allow for newer versions of their
applications to be downloaded and run. To do this, the application provider
simply changes the version of the application to be run in the JNLP file, for
example, from 1.0 to 2.0. The next time a user runs the application, Java
Web Start will detect which version of the application should be run, and will
automatically download and install the newer application if it is not already
present on the client machine.

The application provider does not have the ability to proactively and
automatically initiate software updates of their application. An updated
application will only be downloaded and installed when a user attempts to
run the application.
Does the software update from Sun erase my previous version of Java?

No. It installs a newer version of the Java Runtime Environment while leaving
the existing versions intact. For example, a client machine can have the J2SE
versions 1.3, 1.3.1, 1.3.1_02, and 1.4 installed at the same time without
conflict. This is useful for when application provider A has only certified their
application on version 1.3, while application provider B requires version 1.4
for additional features or functionality. There are no conflicts or collisions
between JRE versions, as they all peacefully co-exist.
Where do I report a bug?

As a member of the Sun Developer Network, you can browse the Bug Parade
to see what Bugs have been filed and which have the most votes.

Join the Sun Developer Network
Browse the Bug Database
Report a Bug
Where do I request an enhancement to the Java platform?


As a member of the Sun Developer Network, you can browse the Bug Parade
to see what 'Requests for Enhancement' (RFEs) have been filed and which
have the most votes.

Join the Sun Developer Network
Browse the Bug Database
Request an enhancement

Where do I get help troubleshooting?

Please see the list of resources available in the Java Technology Online
Support pages. See also the TroubleShooting and Diagnostic Guide.
How do I send comments to the Java SE technology product teams?

One-way feedback aliases are available for your product specific comments.
See the Product & API mailing list.
A1. What releases of Java technology are currently available? What do they

The Java programming language is currently shipping from Sun
Microsystems, Inc. as the Java 2 SDK and Java 2 Runtime Environment. All
Sun releases of the Java 2 Platform software are available from the Java 2
Platform software home page (

Each release of the Java 2 SDK, Standard Edition contains:

Java Compiler
Java Virtual Machine*
Java Class Libraries
Java AppletViewer
Java Debugger and other tools
Documentation (in a separate download bundle)

To run Java 1.0 applets, use Netscape Navigator 3.x or other browsers that
support Java applets. To run Java 1.1.x applets, use HotJava 1.x or Netscape
Navigator 4.x or other browsers that support the newest version of the Java

A2.What platforms is the Java-technology software available on?

Sun provides ports of the Java 2 Platform for Windows 95, Windows 98,
Windows NT, Windows 2000, Solaris-SPARC, Solaris-Intel, and Linux.

A3. Should I use the Production Release or Reference Implementation of the
Solaris JDK software and JRE?

The following applies to versions prior to 1.3.0. Starting with J2SE 1.3.0, only
the production release exists. There is no Solaris reference implementation.


Reference Implementation - Those who want the latest Solaris
implementation of the JDK software or JRE release and do not require
optimized performance can obtain the reference implementations:
JDK 1.1 Reference Implementation
JRE 1.1 Reference Implementation
JDK 1.2 Reference Implementation
JRE 1.2 Reference Implementation
The Solaris binaries are built from the same source code as the Windows
version. The 1.1 reference implementations for Solaris do not include a JIT.
Reference implementations are distributed as (essentially) a tar file which
may be unpacked in any directory, so that root permission is not required for

Production Release - In contrast, customers whose applications/applets will
be released as products, and who need a Solaris JRE or JDK software with
optimized performance, should use the Solaris production releases:
JDK production release
JRE production release
The production releases are based on the reference implementation of the
same version number, and include a JIT compiler, additional performance
tuning, and bug fixes. The production releases are installed as standard
Solaris packages, which require root permission for installation.

Varying levels of technical support are available for both the Reference and
Production releases through the standard Solaris support channels.

For a further overview of differences between these Solaris JDK software
offerings, see JDK 1.1 for Solaris - Binary Products Overview and the FAQ for
the JDK Solaris Production Release.

A4. What about a version for my favorite platform? When can I get it?

These are extremely popular and important questions. What we can currently
say is:

   Amiga, NeXT, OS/2, Windows 3.1, Windows 32s, Macintosh, ...
We've provided our source code to make third-party ports like these possible,
but we are not officially overseeing or tracking them. For more information,
please check out:
Platforms Supporting Java technology (

A5. How do I download Java technology and/or Java 2 SDK software? How do
I install it?


You can get our releases either with a World Wide Web (WWW) browser or
by anonymous ftp. For details, including installation instructions, visit:
The Java 2 Platform web site (
Choose the software you want, and go from there.

A6. Where can I find information about HotJava browser?

The current version of HotJava browser is 1.1Beta1 and is available at
HotJava. This page has links to an email address for comments and to
HotJava browser known bugs.

A7. How can I get started programming in the Java programming language?

See our page which can guide you in the right direction:
Getting Started with Java technology.
A8. Do I need special server software to use applets?

No. Java applets may be served by any HTTP server. On the server side they
are handled the same as any other file, such as a text, image, or sound file.
All the special action happens when the applet class files are interpreted on
the client side by a Java technology-enabled browser, such as HotJava
browser or 1.x or Netscape 3.x/4.x.

A9. Who is licensing Java technology?

See our "Who's Licensing Java?" page:

Who's Licensing Java?

A10. Is JavaScript technology available? How do I find out more about it?

The initial version of the JavaScript technology is available in current releases
of Netscape Navigator 3.x. For more information, including a pointer to the
full press release, see the Netscape JavaScript technology page:

Netscape JavaScript
A11. What are the security problems I've heard about JavaScript technology

JavaScript technology is a scripting language used with Netscape Navigator.
There have been reports of privacy problems with JavaScript technology, and
Netscape is committed to addressing those concerns. JavaScript technology
cannot be used to invoke Java applets. The privacy problems reported with
JavaScript technology are not present in Java applets.

A12. I can't find the API documentation on any classes in the sun.*
packages. Where is it?


The short answer is that we provide documentation only for the public
classes in java.*. We do not provide documentation for sun.* because those
are the Sun-specific implementation, and specifically not part of the Java
technology API standard, and are therefore subject to change without notice.

In general, we don't provide javadoc documentation for sun.* classes in
order to discourage developers from writing programs that use them. For
further explanation, see the next question.

However, if you must have it, the documentation for sun.* is available in the
doc comments in the community source code release available separately,
mentioned in question A14. For example, the doc comments for are
in the source files located at:

This source code release does not include javadoc-generated documentation.
You would have to generate those docs yourself using javadoc.

A13. Why developers should not write programs that call 'sun' packages

Java Software supports into the future only classes in java.* packages, not
sun.* packages. In general, API in sun.* is subject to change at any time
without notice. For more details, see the article Why Developers Should Not
Write Programs That Call 'sun' Packages.

A14. Where can I get the Java programming language source code?

Java Software has two separate bundles of source code that you can obtain
at no charge:
The Java 2 SDK, Standard Edition itself contains a file called that
contains the source code for the public classes in the java package. Because
this does not contain sun.* classes, you cannot do a complete build of the
Java technology from these source files. These source files are for your
information, to supplement the documentation, so you can see how Java
technology works.
The full source code release is available from us by going to the Community
Source Code Licensing web site..
B1. Where did the Java name come from? What does it stand for?

The name was chosen during one of several brainstorming sessions held by
the Java software team. We were aiming to come up with a name that
evoked the essence of the technology -- liveliness, animation, speed,
interactivity, and more. "Java" was chosen from among many, many
suggestions. The name is not an acronym, but rather a reminder of that hot,
aromatic stuff that many programmers like to drink lots of.

B2. Can the Java software team keep me informed of latest developments?


We no longer keep a list of people to inform; when we started that, we never
expected that so many people would be writing to us every day! If you'd like
to keep informed, the best way is to visit our Web site

Java Software Home Page (

periodically and participate in the Java technology-related newsgroups. Note
in particular that our "What's New" page:

What's New at Java Software (

provides an overview of the most recent developments, press releases, and
so on concerning Java technology.

B3. What newsgroups carry information about Java technology?

Several newsgroups are currently available, including:

B4. What email addresses are available?

Information about our internal e-mail addresses is available at

Java Software e-mail addresses.

B5. What documentation is available? In what formats? How can I get it?

We provide a wide range of documentation (white papers, API specifications,
programmer's guide, and more), reachable from our documentation page:

Documentation Index (


Most of our documents are available in HTML, PostScript and PDF formats.

B6. Can you send me information by regular mail or by email?

Sorry, but we're mainly set up to distribute information through our Web site
( and ftp site ( We want to get as much
information out and available as possible, but we can only handle the volume
via these customer-initiated mechanisms.

B7. Can I be an alpha or beta tester?

Yes, that's essentially what you're doing when you use our beta release
software and send in bug reports. We generally don't have separate formal
programs for early-release testing.

B8. Are Java programming language courses available? Where? At what

SunService is providing Java programming language courses at sites around
the world; see

Sun Educational Services (

B9. How do I file bug reports or feature suggestions?

See instructions on our bug report page:

Submitting a Bug or Feature Request

We will not be able to acknowledge each report individually. Please accept
our gratitude in advance -- your feedback is crucial to our work.
C1. Can all Netscape 3.x versions run Java applets?

Netscape 3.x supports Java 1.0 applets on many but not all platforms. See
the release notes for your platform at:

Netscape Navigator

Java technology-enabled versions of Netscape 3.x will only run beta and
1.0.2 applets, which can be written with the 1.0.2 Java Development Kit
(JDK). Be aware that there are many Web pages with alpha applets, which
Netscape 3.x will not handle. You can distinguish between alpha and beta
applets by looking at the html source for a page: alpha applets use the
<app> tag, whereas beta applets use the <applet> tag.

Hotjava browser and Java technology-enabled versions of Netscape 4.x will
run 1.1.x applets, which can be written in with JDK 1.1.x.


C2. Can you help me with using Java technology in Netscape?

For questions that specifically concern installation, troubleshooting, feature
availability, and how to do something specific with applets in the Netscape
browser, it's best to ask Netscape directly. For instance, to report Netscape
bugs, you can use:

Netscape Bug Report

D1. Is Java technology free? Where can I get information on licensing?

The Java Development Kit (JDK) is free to download and use for commercial
programming, but not to re-distribute. We have guidelines on our web site
for using and/or licensing Java technology; see

Licensing Information

D2. Can I use Sun's Java technology logo?

Sun does not authorize the use of the Java logo. For more information about
this and other special developer logos, please see:

Java Trademark Guidelines

D3. What are your plans for XXX functionality? Why haven't you done YYY?

We welcome all input regarding Java technology -- we will read and consider
it. We're keeping many more options in mind than appear in our current
releases. However, because we are focusing on moving toward our next
release, we have time to answer only a small number of such questions. See:
Contacting Java Software

D4. Can you comment on company ZZZ's plans for licensing and using Java

No, we need to let other companies speak for themselves. We can only refer
you to official press releases. For pointers to recent press releases, see our
"What's New" page:

What's New at Java Software

D5. How can I invest in Java technology on the stock market?

Java technology is a product of Sun Microsystems, Inc., which is traded on
NASDAQ under the symbol SUNW.
E1. Will Java technology work with DOS file name limitations (8.3)?


Java technology relies on files with longer names than the old DOS limits, so
if you are running older (pre-Microsoft Windows 95) versions of DOS, Java
technology will not work. If you are running a version of DOS (such as the
one that comes with Windows 95) that allows long file names, you should not
have any problems.

Note that older versions of WinZip do not support long file names, even if the
installed version of DOS does. You can get a free upgrade of WinZip with
support for long file names from their web site.

E2. javac: Superclass java.applet.Applet of class HelloWorld not found.

The examples in the programmer's guide have been updated to conform to
the new applet API in our 1.0.2 Java Development Kit (JDK). "Superclass not
found" error messages are typical if you try to compile Java 1.0 beta code
with an alpha version of javac. The recommended fix is to download a copy
of the JDK software, and do all further development with that.

Another potential source of this error message is incorrect capitalization of
either the file name or the class name in in the file. The Java technology
system is case-sensitive, so a HelloWorld class is different from a helloWorld
class, and so on.

E3. How do I stop the copyright notice from appearing every time I start the
Windows NT/95 version of appletviewer?

The appletviewer looks for a .hotjava directory inside your home directory to
determine whether you are starting it for the first time. If the directory is not
found, the appletviewer will pop up the copyright notice. The workaround is
to manually create the .hotjava directory in your home directory. The
following paragraphs explain how to do this.

The appletviewer is written to recognize three MS-DOS environment
variables for the location of a user home directory: it uses either HOME or
the combination of HOMEDRIVE and HOMEPATH. Under Windows NT3.51, the
HOMEDRIVE and HOMEPATH environment variables are set automatically.
Under Windows 95, you will need to set the HOME environment variable to
point to an existing directory.

Once your home directory is set, all you need to do for Windows NT3.51 is to
create the .hotjava directory inside of it:
     mkdir %HOMEDRIVE%%HOMEPATH%\.hotjava

In Windows 95, the easiest method is to edit the AUTOEXEC.BAT file, adding
the following line:

     set HOME=C:\


Then save the file and reboot, so that the change to take effect. Once your
computer has rebooted, open a DOS window and execute the following

      mkdir %HOME%.hotjava

E4. My virus-checker program claims to have found a virus in some of the
JDK software files. What's going on?

Although your virus checker may have discovered a real virus, you should
consider the possibility that a false detection has occurred. Virus-checker
programs can mistakenly find "viruses" in parts of the JDK software where
there really is no virus. This can happen when the virus checker detects a bit
pattern in a class file that, by chance, matches a bit pattern in a virus. The
types of viruses that can infect .exe or .com files typically cannot infect class
files or jar files.

E5. Why do I get a NoClassDefFoundError when I try to run my HelloWorld

The problem is probably that your HelloWorld.class file is not on your class
path. The class path is the list of one or more directories in which the java
application launcher will look for the .class files comprising your application.
So, how to specify the class path?

If your program depends only on the J2SE classes, you should not need to
use classpath, because those classes are automatically on the classpath. If
your program depends on other classes, you need to set classpath to those
classes. In that case, it is preferable to use the -classpath option rather than
the CLASSPATH environment variable, as the -classpath option enables each
application to have its own classpath. For more details, see:

Setting the Class Path for Solaris/Linux
Setting the Class Path for Windows

Please send questions to the Compiling forum where others can help you.

The following assumes you're running Windows 95/98/NT/2000.

There is a CLASSPATH environment variable. You can see which environment
variables are set on your machine by running 'set' at the DOS prompt. If the
CLASSPATH variable is set, then its value is your class path. If the
CLASSPATH variable is NOT set, then the default class path is the current
directory (i.e. whatever directory you run 'java HelloWorld' from).

So if you are trying to run 'java HelloWorld' from the directory in which the
HelloWorld.class file is in, and you get the "can't find" error, it's probably an


indication that you have the CLASSPATH environment variable set. Try
unsetting the CLASSPATH variable: 'set CLASSPATH=' (i.e. setting it to no
value is the same as unsetting it). Then try running your application again.
Because the CLASSPATH variable isn't set, the class path should default to
the correct directory, and your app should launch.

Altenatively, you could set the CLASSPATH environment variable to point to
the location of your HelloWorld.class file. However, you'd run into the same
"can't find" error if you then tried to run another application located in
another directory.

You can also force the class path to be a particular value by using the -
classpath option: 'java -classpath C:\myprograms\ HelloWorld'

See class path information in the Java 2 tools documentation for more

E6. Why are Java applets and other interactive content behaving differently
in Microsoft Internet Explorer?

A recent update to Microsoft Internet Explorer included a change that alters
the way users interact with applets and other interactive content in the
browser. With this change, users are first required to manually activate (click
on) the applet's user interface, before the user can interact with the content.
If the page has multiple interactive components, users are required to
activate each user interface individually.

It is possible to get the old behavior back. Microsoft has published a general
solution for updating web pages that restores the user experience. For more
information, see the Microsoft article Activating ActiveX Controls. Working
with Microsoft, Sun has developed an Internet Explorer deployment guide
customized for Java developers, which provides examples on how to leverage
the Microsoft work around, and minimize user impact of the Internet Explorer
*As used on this web site, the terms "Java virtual machine" or "JVM" mean a
virtual machine for the Java platform.
What are applets prevented from doing?

In general, applets loaded over the net are prevented from reading and
writing files on the client file system, and from making network connections
except to the originating host.

In addition, applets loaded over the net are prevented from starting other
programs on the client. Applets loaded over the net are also not allowed to
load libraries, or to define native method calls. If an applet could define
native method calls, that would give the applet direct access to the
underlying computer.


There are other specific capabilities denied to applets loaded over the net,
but most of the applet security policy is described by those two paragraphs
above. Read on for the gory details.

Can applets read or write files?

In Java-enabled browsers, untrusted applets cannot read or write files at all.
By default, downloaded applets are considered untrusted. There are two
ways for an applet to be considered trusted:

The applet is installed on the local hard disk, in a directory on the
CLASSPATH used by the program that you are using to run the applet.
Usually, this is a Java-enabled browser, but it could be the appletviewer, or
other Java programs that know how to load applets.

The applet is signed by an identity marked as trusted in your identity
database. For more information on signed applets, refer to an example of
using signed applets, and to a short description on using javakey.

Sun's appletviewer allows applets to read files that reside in directories on
the access control lists.

If the file is not on the client's access control list, then applets cannot access
the file in any way. Specifically, applets cannot
check for the existence of the file
read the file
write the file
rename the file
create a directory on the client file system
list the files in this file (as if it were a directory)
check the file's type
check the timestamp when the file was last modified
check the file's size

How do I let an applet read a file?

Applets loaded into a Java-enabled browser can't read files.

Sun's appletviewer allows applets to read files that are named on the access
control list for reading. The access control list for reading is null by default, in
the JDK. You can allow applets to read directories or files by naming them in
the property in your ~/.hotjava/properties file.

Note: The "~" (tilde) symbol is used on UNIX systems to refer to your home
directory. If you install a web browser on your F:\ drive on your PC, and
create a top-level directory named .hotjava, then your properties file is found
in F:\.hotjava\properties.


For example, to allow any files in the directory home/me to be read by
applets loaded into the appletviewer, add this line to your
~/.hotjava/properties file.
You can specify one file to be read:
Use ":" to separate entries:
Allowing an applet to read a directory means that it can read all the files in
that directory, including any files in any subdirectories that might be hanging
off that directory.

How do I let an applet write a file?

Applets loaded into a Java-enabled browser can't write files.

Sun's appletviewer allows applets to write files that are named on the access
control list for writing. The access control list for writing is empty by default.

You can allow applets to write to your /tmp directory by setting the acl.write
property in your ~/.hotjava/properties file:
You can allow applets to write to a particular file by naming it explicitly:
Use : to separate entries:

Bear in mind that if you open up your file system for writing by applets, there
is no way to limit the amount of disk space an applet might use.

What system properties can be read by applets, and how?

In both Java-enabled browsers and the appletviewer, applets can read these
system properties by invoking System.getProperty(String key): key
 ____________              ______________________________
 java.version              Java version number
 java.vendor               Java vendor-specific string
 java.vendor.url Java vendor URL
 java.class.version Java class version number            Operating system name
 os.arch            Operating system architecture
 os.version        Operating system version
 file.separator     File separator (eg, "/")
 path.separator     Path separator (eg, ":")
 line.separator     Line separator


Applets are prevented from reading these system properties: key
 ____________             _____________________________
 java.home         Java installation directory
 java.class.path   Java classpath         User account name
 user.home         User home directory
 user.dir          User's current working directory

To read a system property from within an applet, simply invoke
System.getProperty(key) on the property you are interested in.

For example,
 String s = System.getProperty("");
How do I hide system properties that applets are allowed to read by default?

There's no way to hide the above ten system properties from applets loaded
into a Java-enabled browser. The reason is that the browsers don't consult
any external files as part their Java configuration, as a security precaution,
including the ~/.hotjava/properties file.

From the appletviewer, you can prevent applets from finding out anything
about your system by redefining the property in your ~/.hotjava/properties
file. For example, to hide the name of the operating system that you are
using, add this line to your ~/.hotjava/properties file:
How can I allow applets to read system properties that they aren't allowed to
read by default?

There's no way to allow an applet loaded into a Java-enabled browser to read
system properties that they aren't allowed to read by default.

To allow applets loaded into the appletviewer to read the property named by
key, add the property key.applet=true to your ~/.hotjava/property file. For
example, to allow applets to record your user name, add this line to your
~/.hotjava/properties file:
How can an applet open a network connection to a computer on the internet?

Applets are not allowed to open network connections to any computer,
except for the host that provided the .class files. This is either the host where
the html page came from, or the host specified in the codebase parameter in
the applet tag, with codebase taking precendence.

For example, if you try to do this from an applet that did not originate from
the machine, it will fail with a security exception:


     Socket s = new Socket("", 25, true);
How can an applet open a network connection to its originating host?

Be sure to name the originating host exactly as it was specified when the
applet was loaded into the browser.

That is, if you load an HTML page using the URL
then your applet will be able to connect to its host only by using the name Using the IP address for won't work, and using a
"shorthand" form of the host name, like foo.state instead of,
won't work.

How can an applet maintain persistent state?

There is no explicit support in the JDK applet API for persistent state on the
client side. However, an applet can maintain its own persistent state on the
server side. That is, it can create files on the server side and read files from
the server side.

Can an applet start another program on the client?

No, applets loaded over the net are not allowed to start programs on the
client. That is, an applet that you visit can't start some rogue process on
your PC. In UNIX terminology, applets are not allowed to exec or fork
processes. In particular, this means that applets can't invoke some program
to list the contents of your file system, and it means that applets can't invoke
System.exit() in an attempt to kill your web browser. Applets are also not
allowed to manipulate threads outside the applet's own thread group.

What features of the Java language help people build secure applets?

Java programs do not use pointers explicitly. Objects are accessed by getting
a handle to the object. Effectively, this is like getting a pointer to an object,
but Java does not allow the equivalent of pointer arithmetic on object
handles. Object handles cannot be modified in any way by the Java applet or

C and C++ programmers are used to manipulating pointers to implement
strings and to implement arrays. Java has high-level support for both strings
and arrays, so programmers don't need to resort to pointer arithmetic in
order to use those data structures.

Arrays are bounds-checked at runtime. Using a negative index causes a
runtime exception, and using an index that is larger than the size of the
array causes a runtime exception. Once an array object is created, its length
never changes.


Strings in Java are immutable. A string is zero or more characters enclosed in
double quotes, and it's an instance of the String class. Using immutable
strings can help prevent common runtime errors that could be exploited by
hostile applets.

The Java compiler checks that all type casts are legal. Java is a strongly
typed language, unlike C or C++, and objects cannot be cast to a subclass
without an explicit runtime check.

The final modifier can be used when initializing a variable, to prevent runtime
modification of that variable. The compiler catches attempts to modify final

Before a method is invoked on an object, the compiler checks that the object
is the correct type for that method. For example, invoking
when t is not a Thread object causes a compile time error.

Java provides four access modifiers for methods and variables defined within
classes and makes sure that these access barriers are not violated.
public: a public method is accessible anywhere the class name is accessible
protected: a protected method is accessible by a child of a class as long as it
is trying to access fields in a similarly typed class. For example,
  class Parent { protected int x; }
  class Child extends Parent { ... }
The class Child can access the field "x" only on objects that are of type Child
(or a subset of Child.)

private: a private method is accessible only within its defining class
default: if no modifier is specified, then by default, a method is accessible
only within its defining package

For example, programmers can choose to implement sensitive functions as
private methods. The compiler and the runtime checks ensure that no
objects outside the class can invoke the private methods.

What is the difference between applets loaded over the net and applets
loaded via the file system?

There are two different ways that applets are loaded by a Java system. The
way an applet enters the system affects what it is allowed to do.

If an applet is loaded over the net, then it is loaded by the applet class
loader, and is subject to the restrictions enforced by the applet security


If an applet resides on the client's local disk, and in a directory that is on the
client's CLASSPATH, then it is loaded by the file system loader. The most
important differences are
applets loaded via the file system are allowed to read and write files
applets loaded via the file system are allowed to load libraries on the client
applets loaded via the file system are allowed to exec processes
applets loaded via the file system are allowed to exit the virtual machine
applets loaded via the file system are not passed through the byte code

Java-enabled browsers use the applet class loader to load applets specified
with file: URLs. So, the restrictions and protections that accrue from the class
loader and its associated security manager are now in effect for applets
loaded via file: URLs.

This means that if you specify the URL like so:
      Location: file:/home/me/public_html/something.html
and the file something.html contains an applet, the browser loads it using its
applet class loader.

What's the applet class loader, and what does it buy me?

Applets loaded over the net are loaded by the applet class loader. For
example, the appletviewer's applet class loader is implemented by the class

The class loader enforces the Java name space hierarchy. The class loader
guarantees that a unique namespace exists for classes that come from the
local file system, and that a unique namespace exists for each network
source. When a browser loads an applet over the net, that applet's classes
are placed in a private namespace associated with the applet's origin. Thus,
applets loaded from different network sources are partitioned from each

Also, classes loaded by the class loader are passed through the verifier. The
verifier checks that the class file conforms to the Java language specification
- it doesn't assume that the class file was produced by a "friendly" or
"trusted" compiler. On the contrary, it checks the class file for purposeful
violations of the language type rules and name space restrictions. The
verifier ensures that
There are no stack overflows or underflows.
All register accesses and stores are valid.
The parameters to all bytecode instructions are correct.
There is no illegal data conversion.

The verifier accomplishes that by doing a data-flow analysis of the bytecode
instruction stream, along with checking the class file format, object


signatures, and special analysis of finally clauses that are used for Java
exception handling.

Details on the verifier's design and implementation were presented in a
paper by Frank Yellin at the December 1995 WWW conference in Boston.

A web browser uses only one class loader, which is established at start-up.
Thereafter, the system class loader cannot be extended, overloaded,
overridden or replaced. Applets cannot create or reference their own class

What's the applet security manager, and what does it buy me?

The applet security manager is the Java mechanism for enforcing the applet
restrictions described above. The appletviewer's applet security manager is
implemented by sun.applet.AppletSecurity.

A browser may only have one security manager. The security manager is
established at startup, and it cannot thereafter be replaced, overloaded,
overridden, or extended. Applets cannot create or reference their own
security manager.

Is there a summary of applet capabilities?

The following table is not an exhaustive list of applet capabilities. It's meant
to answer the questions we hear most often about what applets can and
cannot do.

NN: Netscape Navigator 4.x, loading unsigned applets over the Net
NL: Netscape Navigator 4.x, loading unsigned applets from the Local file
AN: Appletviewer, JDK 1.x, loading applets over the Net
AL: Appletviewer, JDK 1.x, loading applets from the Local file system
JS: Java Standalone applications              Stricter ------------------------>
Less strict

                      NN   NL     AN    AL     JS

read file in /home/me,     no     no    no     yes     yes

read file in /home/me,     no     no    yes    yes    yes

write file in /tmp,   no   no     no    yes    yes


write file in /tmp,   no   no    yes   yes   yes

get file info,        no   no    no    yes   yes

get file info,  no         no    yes   yes   yes

delete file,        no     no    no    no    yes
using File.delete()

delete file,       no      no    no    yes   yes
using exec /usr/bin/rm

read the         no    yes   no    yes    yes

connect to port            no    no    no    yes    yes
on client

connect to port            no    no    no    yes    yes
on 3rd host

load library          no   yes   no    yes   yes

exit(-1)              no   no    no    yes   yes

create a popup             no    yes   no    yes    yes
window without
a warning

If other languages are compiled to Java bytecodes, how does that affect the
applet security model?

The verifier is independent of Sun's reference implementation of the Java
compiler and the high-level specification of the Java language. It verifies
bytecodes generated by other Java compilers. It also verifies bytecodes
generated by compiling other languages into the bytecode format. Bytecodes
imported over the net that pass the verifier can be trusted to run on the Java
virtual machine. In order to pass the verifier, bytecodes have to conform to
the strict typing, the object signatures, the class file format, and the


predictability of the runtime stack that are all defined by the Java language

None of these examples are malicious - the one line descriptions can be
taken at face value. You can look at the source code for each applet, before
visiting the page that has that applet inside. (The first link in each example
takes you to the source code, and the second link takes you to an html page
that includes the executable content for the example.)

Can this applet read files on your system?
Can this applet obtain information about files on your system?
Can this applet write a file on your system?
Can this applet use File.delete() to delete the file named /tmp/foo?
Can this applet use the unix command /bin/rm to delete the file named
System Properties:
Can this applet read the ten system properties that applets are allowed to
read by default?
Can this applet read hidden properties like or user.home?
Can this applet replace your browser's property file?
Can this applet connect to port 25 on
Can this applet send data to
Can this applet kill your browser?
Can this applet run some program on your computer?
Libraries and name spaces:
Can this applet load a library on your computer?
Can this applet create its own class loader?
This applet tries to create a class of its own in the namespace, but it
can't. This example will not compile with the Java compilers that conform to
the Java language specification.
What does a window created by an applet look like?

Glossary of terms used in this FAQ
A Java program that is run from inside a web browser. The html page loaded
into the web browser contains an <applet> tag, which tells the browser
where to find the Java .class files. For example,


Standalone Java application
A Java program that is run by invoking the java interpreter. For example,


     java coolApplication
Who should use JNDI?

Any Java application that needs to access information about users, machines,
networks, and services. User information includes security credentials, phone
numbers, electronic and postal mail addresses, and application preferences.
Machine information includes network addresses, machine configurations,
etc. In addition, any Java application that needs to either export objects or
access objects exported by other applications and services. Examples include
printers, calendars, and networked file systems.

Can I use JNDI now?

Yes, Sun Microsystems has released JNDI as a Java Standard Extension. Sun
Microsystems has also released service providers that plug in seamlessly
behind JNDI for a number of naming and directory services: LDAP, NIS,
CORBA (COS) Naming, and files. These and service providers produced by
other vendors are available for download.

Where is JNDI being used in the Java platform?

HotJava Views 1.1 is using JNDI to access LDAP. Enterprise APIs such as
Enterprise JavaBeans, Java Message Service, JDBC 2.0 make use of JNDI to
for their naming and directory needs. RMI over IIOP applications can use
JNDI to access the CORBA (COS) naming service.

Who will provide implementations of JNDI?

At the time of this writing, IBM, Novell, Sun, and WebLogic have produced
service providers for JNDI. We maintain a listing of publicly available service

What protocols does JNDI provide an interface to?

JNDI itself is independent of any specific directory access protocol. Individual
service providers determine the protocols to support. There will be provider
implementations for popular protocols, such as LDAP, NDS, DNS, and
NIS(YP), supplied by different vendors.

How does JNDI relate to LDAP?

JNDI provides an excellent object-oriented abstraction of directory and
naming. Developers using JNDI can produce queries that use LDAP or other
access protocols to retrieve results; however, they are not limited to LDAP
nor do they have to develop their applications wired to LDAP. JNDI supports
the key capabilities in LDAP v3.


How does JNDI relate to Netscape's Java LDAP API?
Netscape's API is LDAP-specific. It is used for low-level access to LDAP
directories. It exposes details about the protocol that applications typically do
not need to know.

JNDI is a generic directory API for Java programs. It is analogous to the class for accessing files. There might be some administrative
programs that need to manipulate a file at the protocol level (such as NFS),
but typically all Java applications use the File class to access to file system.
Similarly, most Java programs should use JNDI to access directories.
Applications that need to manipulate directory content at the protocol level
may choose to use Netscape's API.

How does JNDI relate to OMG's CORBA standards for naming?

A Java CORBA application can use JNDI to access to the CORBA (COS) name
service, as well as other naming and directory services. It offers the
application one interface for accessing all these naming and directory

Using JNDI also paves the way for Java CORBA applications to use a
distributed enterprise-level service like LDAP to store object references.

How does JNDI relate to Microsoft's ADSI?

The Java ADSI package allows Java programs to access Active Directory
based on the COM model. Although it can be used to access other directories,
it is a Windows-centric solution.

JNDI offers Java applications, regardless of whether they're running on
Windows or accessing Active Directory, to access directories using the Java
object model. For example, you can manipulate objects such as AWT and
JavaBeans components, bind them into the directory, and look them back up
without having to do any translation or deal with data representation issues.

What is XFN and how does this relate to JNDI?

XFN is X/Open Federated Naming, a C-based standard for accessing multiple,
possibly federated naming and directory services. A programmer familiar
with XFN will find it easy to use JNDI.

What about security?

Different directories have different ways of dealing with security. JNDI allows
for applications to work in conjunction with directory-specific security
systems. In the future, JNDI-based applications will be able to take
advantage of any single sign-on mechanism developed for the Java platform.


The computer that hosts the web page that contains an applet. The .class
files that make up the applet, and the .html files that reference the applet,
reside on the server. When someone on the internet connects to a web page
that contains an applet, the server delivers the .class files over the internet
to the client that made the request.

The server is also known as the originating host.

The computer that displays the web page that contains an applet.

The terms server and client are sometimes used to refer to computers, and
are sometimes used to refer to computer programs. For example, is a server, and the httpd process running on is
its server process. My computer at home is a client, and the web browser
running on my computer at home acts as the client process.
Q: What is Java 2D?
A: Java 2D is an integral part of the Java SE platform that provides a
powerful, flexible framework for device- and resolution-independent 2D

Java 2D handles arbitrary shapes, text, and images and provides a uniform
mechanism for performing transformations, such as rotation and scaling, on
these objects. With Java 2D, application developers can render to display
devices, discover and render to printer devices, read and write in many
image formats. There is comprehensive text and font handling and color
space support and various rendering techniques and effects are offered.

Q: Who needs Java 2D?
A: The Java 2D API benefits virtually all desktop developers as it provides the
rendering engine for the Swing toolkit and is also used to develop games,
and graphics and imaging applications. Java 2D is of benefit to any developer
who wants to create a graphically rich end-user experience.

Q: Where can I go for more information about Java 2D?
A: A good place to start is The 2D Graphics Tutorial. You can also refer to the
The Java 2D Programmer's Guide

Q: Are there any news groups or mailing lists dedicated to Java 2D?
A: JAVA2D-INTEREST@JAVA.SUN.COM is the primary mailing list for those
interested in Java2D. All the Java 2D engineers at Sun monitor this alias. The
archives for this list can be located at Java2D-interest list archive

This mailing list is also linked to the Java 2D forum at

A few Sun engineers also participate in the Java 2D forums at, which is a great resource for game developers and other


performance hungry individuals:

Programming, Debugging and Performance questions

Q: What's the difference between Graphics and Graphics2D?
A: The Graphics class has been around since the first release of Java and
supports the more basic rendering operations which are sufficient for many
applications. Graphics2D is a subclass of Graphics and adds all the Java 2D
API features first introduced in Java 2 in 1998.

Q: Is there a list of the various runtime flags that Java2D uses?
A: Yes! Check out:

Q: What kinds of graphics hardware acceleration does Java2D use?
A: This question has many answers, which depend on things like:
What release you are running (we are constantly improving our hardware
acceleration renderers, so each release has more to offer)
What OS you are running (our story on Windows is different from our story
on Linux which is again different from our story on Solaris ... and the Apple
folks have their own story for their platform)
What kind of hardware you have (your graphics card capabilities can be the
single most important factor in enabling Java2D hardware acceleration).
We have tried to write down some of the more interesting and important
hardware acceleration features in various articles and blogs. Here are some
pointers, but I'm sure you can find more:
OpenGL: Here is an article about our OpenGL support in J2SE 5.0:
VolatileImage: here are two blogs about VolatileImage objects: and
Windows/Direct3D: Here is a blog about some of the hardware acceleration
improvements in Windows in the Java SE 6 release:

Q: How can I get better performance for my Java2D application?
A: The answer depends entirely on what you are trying to do, and what
environment you are running on. There are a lot of articles you can read to
see if they help you, such as:
All of the articles listed for the "hardware acceleration" Q&A above
An article on using Intermediate Images to accelerate repeated renderings of
complex operations:
Online chat transcripts and interviews on performance:


The gamers on are highly sensitive to performance
and that web site has several good discussions about performance issues.

Q: Are there any tracing facilities in Java2D to help me track down
performance issues in my application?
A: Yes. In J2SE 1.4 and above, Sun's implementation of the Java2D API
includes a simple system property that can help you determine the source of
your performance bottleneck. Simply run your application with the following
system property:


For more information on this tracing facility, refer to the following

Image questions

Q: What image-file formats does Java 2D support?
A: Through its Image I/O package (javax.imageio) Java 2D supports reading
and writing GIF, JPEG, PNG, BMP and WBMP images. The Image I/O package
includes support for easily plugging in additional image format support: JAI
(Java Advanced Imaging) in particular has developed Image I/O plugins that
add reading and writing support for formats such as TIFF and JPEG2000 in its
"JAI Image I/O Tools" package, which has no dependency on the core JAI

Q: Which ColorModel should I use if I need optimum performance?
A: The best way to improve your performance with ColorModel optimization
is to use an opaque ColorModel. If you are using an IndexColorModel, make
sure you have no transparent pixel values and no alpha values in cmap
arrays, and set hasAlpha to false. If you are using a ComponentColorModel,
set Transparency to OPAQUE and hasAlpha to false. If you are using a
DirectColorModel, make sure you have no alpha mask, or set the mask to
zero. If you are using a BufferedImage, construct it only with one of the
types that do not contain alpha.

Q: What image types should I use to get the best performance?
A: If you are creating an image whose data will be copied to the screen,
create the image with the same depth and type of the screen. This way, no
translation between the image and the screen is necessary before copying
the image. To ensure that the depth and type of your image match the
screen, use the createImage(w, h) method of your on-screen component
which returns an image that has the same depth as the screen. Alternatively,
if you are using a BufferedImage, create it with one of the pre-defined types


or use GraphicsConfiguration.createCompatibleImage(w, h) to match the
image with the screen format.

Q: How do I create a resized copy of an image?
A: Here's one way to do it: create a BufferedImage of the desired size and
draw the original image into it, scaling on the fly. Note that depending on
whether your original image is opaque or non-opaque (that is, if it's
translucent or transparent), you may need to create an image with an alpha
BufferedImage createResizedCopy(Image originalImage,
                       int scaledWidth, int scaledHeight,
                       boolean preserveAlpha)
   int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB :
   BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight,
   Graphics2D g = scaledBI.createGraphics();
   if (preserveAlpha) {
   g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null);
   return scaledBI;
You can control the quality of the scaled copy with the
Graphics2D.setRenderingHint() method.
Add the following before the drawImage() call:

Q: There are several types of images in Java2D; how do I know which one is
appropriate in a particular situation?
A: This article attempts to address that general question:
.html. You might also look at other articles in this blog, particularly the ones
on VolatileImage and BufferedImage objects:

Q: Can I use Java2D to generate dynamic images from my servlet (or other
server-side Java application)?
A: Certainly! Java2D isn't just for desktop applications. You can use the
Java2D API to dynamically generate images in your server application, and


then use the Image I/O API to write the image to a File or to an
OutputStream (so that it can be viewed in a browser). For example, you can
generate a weather map using real-time weather data, or create a pie chart
using data from your accounting database. The possibilites are endless...

Here is a simple example of a servlet that generates a smiley face using
Java2D, and then writes a JPEG image that can be viewed in a browser:

import   java.awt.*;
import   java.awt.image.*;
import   javax.imageio.*;
import   javax.servlet.*;
import   javax.servlet.http.*;

public class ImageServlet extends HttpServlet {

  public void doGet(HttpServletRequest request,
               HttpServletResponse response)
    throws ServletException, IOException

     // Create image
     int width=200, height=200;
     BufferedImage image =
        new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

     // Get drawing context
     Graphics2D g2d = image.createGraphics();

     // Fill background with white
     g2d.fillRect(0, 0, width, height);

     // Draw a smiley face
     g2d.fillOval(10, 10, 180, 180);
     g2d.fillOval(40, 40, 40, 40);
     g2d.fillOval(120, 40, 40, 40);
     g2d.fillRect(50, 150, 100, 10);

     // Dispose context

     // Write image to the output stream
     ServletOutputStream os = response.getOutputStream();


        ImageIO.write(bi, "jpeg", os);

Q: I have an application that reads, writes, and processes images (but does
not display them) using Java2D. When I run my application on Solaris or
Linux, it complains that X11 is not available. What can I do to make my
application work in this environment?
A: When AWT is initialized, it expects to find an Xserver, regardless of
whether it is needed for actual display.

Although many image operations using the Image I/O APIs or the JAI
optional package might not have any obvious need for display, they often
invoke code that needs an AWT resource. For example, calling getGraphics()
on a BufferedImage initializes AWT and causes these error messages seen by
developers. There is no way to say that a particular API does or does not
have this problem; it depends on what particular operations are being
invoked, and might also depend on what the application does with the
images that is not strictly related to any of the APIs cited above.

There are two possible solutions. As of J2SE 1.4 (and above), the preferred
solution is to use the "headless AWT toolkit". This feature allows you to use
the Java2D API in a server-side application without the need for a display
environment. To specify the headless environment, run your application with
the following system property:


For releases prior to J2SE 1.4 you can provide a "pseudo X-server" to
emulate a display environment. One of these Xserver emulators is Xvfb,
available for download at Another possibility is to start a
VNC server ( and then run your application in that

Xvfb does still have one possible use in J2SE 1.4: A server application may
need to display to an Xserver, but requires no user interaction. The headless
toolkit won't support this situation, but xvfb will. This is a completely
hypothetical scenario and it is not clear if any real world application exhibits
such a behavior.

Font and Text questions

Q: What are the capabilities of the Java 2D text rendering system?

A: These include:
Antialiased and sub-pixel (aka LCD) text display
Transformed text


Text as shapes that can be filled with colours, gradient paints etc.
Rendering complex text scripts (eg Indic), Bidi text etc
APIs to locate and use platform fonts
APIs to directly load and register fonts from files and network resources.

These capabilities are all uniformly supported across platforms both for on-
screen display and for printing.

Q: What are the different ways that text can be rendered using Java 2D?


java.awt.Graphics2D.drawString() draws a String of text using the current
font and other rendering attributes. This is the most
common and recommended API as it will automatically identify and properly
handle complex scripts, Bidi etc.

java.awt.font.TextLayout object allows you to implement text editing
yourself: it includes mixed styles, BIDI text layout, carets, highlighting, hit
testing and many other features.

java.awt.font.GlyphVector can be used to accomplish
glyph-level manipulation can be accomplished by using GlyphVector and
GlyphMetrics classes if you want to implement custom text layout algorithms.
Since glyphs are actually shapes, you can do with glyphs anything that you
can do with shapes, such as clipping and stroking.

Using Swing text components : since Swing is based upon Java 2D
JTextField, JTextArea, and JEditorPane, which supports editing and multiple
fonts and styles, all utilise the above Java 2D APIs. Many developers will
therefore not directly use the 2D text APIs but will use the UI-oriented Swing

Q. What font types does Java 2D support?

A. The primary and preferred font format is the TrueType font format. Java
2D also supports Opentype layout tables within TrueType fonts for complex
text rendering (Arabic, Indic etc). In addition Java 2D supports Postscript
Type1 fonts.

Q: Are any fonts bundled with Java 2D?
A: Yes, the Java SE SDK includes three Lucida TrueType font families: Lucida
Sans (Sans Serif), Lucida Typewriter (Terminal/Monospaced) and Lucida
Bright (Serif). However, only one font : Lucida Sans Regular is always
distributed with the JRE that is installed with Java Plugin for running applets
in web browsers to limit download size as TrueType fonts can be quite large.
End users can elect to install the other fonts but only Lucida Sans Regular is
guaranteed to be always available in any Java application. However since


Lucida Sans Regular supports many character sets, such as Basic Latin, Latin
1, Latin Ext A, Greek, Cyrillic, Hebrew, Arabic, currency symbol, super
subscripts, number forms, dingbats, it means applications have a guaranteed
good base line of support. The font files are located in the
$JAVAHOME/jre/lib/fonts directory.

Q: How can I list all available fonts?

A: You may get a list of all available font family names using
java.awt.GraphicsEnvironment.getAvailableFontFamilyNames() or may list all
the font instances using java.awt.GraphicsEnvironment.getAllFonts() In each
case the returned list will include the logical fonts such as "Dialog".
java.awt.GraphicsEnvironment. getAvailableFontFamilyNames() is typically
the most useful for presenting a menu of fonts to a user as a particular style
(eg Bold) can requested for a font by specifying it in the style field of the
Font constructor.

For sample code, see the implementation of the Font2DTest demo shipped
with the JDK (demo/jfc/Font2DTest/src)

Q: How can I make my custom font available to my Java application?
A: Since Java 2D can locate fonts installed in the O/S one option is to just
install the font on your system in the usual platform manner - eg dragging it
into the Windows font folder.

If you don't want other applications to use your font then there are two other
If you ship a private JRE with your application you can copy your fonts to
$JAVAHOME/jre/lib/fonts since they will be available only to java applications
executed by that JRE and will be visible via Java's font enumeration APIs.

You may also load custom fonts dynamically - by using
java.awt.Font.createFont() to instantiate your fonts from files or network

Fonts instantiated via createFont() offer even more flexibility in limiting the
visibility of the font. Font instances using such custom fonts cannot normally
be constructed. Instead you must use Font.deriveFont() on the instance
returned from the Font.createFont() method. Therefore only code to which
you provide a references to the Font can use it. Note that each call to
createFont from the same source (file) will create a new distinct Font which
will be GC'd only when it is no longer referenced. So if you expect to need to
use the created Font in many places simultaneously cache a single copy to
derive from rather than re-creating from the source file.

As of Java SE 6, there is a method : GraphicsEnvironment.registerFont()
which gives you the ability to make a "created" font available to Font
constructors and to be listed via Font enumeration APIs. Font.createFont()


and this method combine to provide a way to "install" a Font into the running
JRE so it is available just as O/S installed fonts are. However this Font does
not persist across JRE invocations.

Q: Why does (eg) a 10 pt font in Java applications appear to have a different
size from the same font at 10pt in a native application?

A: Conversion from the size in points into device pixels depends on device
resolution as reported by the platform APIs. Java 2D defaults to assuming 72
dpi. Platform defaults vary. Mac OS also uses 72 dpi. Linux desktops based
on GTK (Gnome) or Qt (KDE) typically default to 96 dpi and let the end-user
customise what they want to use. Windows defaults to 96 dpi (VGA
resolution) and also offers 120 dpi (large fonts size) and lets users further
specify a custom resolution. So a couple of things can now be seen
The DPI reported by platform APIs likely has no correspondence to the true
of the display device
Its unlikely that Java 2D's default matches the platform default.

So a typical results is that for Window's default 96 DPI that a 10 pt font in a
Java application is 72/96 of the size of the native counterpart.

Note that Swing's Windows and GTK L&Fs do scale fonts based on the system
DPI to match the desktop. If you want to do the same in your application you
can call java.awt.Toolkit.getScreenResolution() and use this to apply a simple
scale to the size you specify for fonts.

Q: How to I find if I use a font to display Cyrillic, or Hindi etc?

A: Use Font.canDisplay() to find out if there is a glyph matching a given
Unicode character in a given font.

Q. How can I specify the text antialiasing/font smoothing settings to be used
by Swing in applications on Java SE 6?

A. This is generally is a question from users of KDE (on Linux or other Unix)
or Windows 2000 who would like to use LCD subpixel text. There's no
programmatic way to do it in Java SE 6 (but see to see if
that has changed since this was written). However if you know what you
want you can set a system property :
java -Dawt.useSystemAAFontSettings=lcd
which request to use LCD subpixel text in the most common subpixel
configuration There are several useful values for this property as follows :

"false" corresponds to disabling font smoothing on the desktop.
"on" corresponds to Gnome Best shapes/Best contrast (no equivalent
Windows desktop setting)


"gasp" corresponds to Windows "Standard" font smoothing [see note (*)
below] (no equivalent Gnome desktop setting)
"lcd" corresponds to Gnome's "subpixel smoothing" and Windows "ClearType"

The full details are documented in the 2D Flags Guide at

(*) Something that surprises people is that Windows "Standard" font
smoothing does not mean always smooth/AA. In fact at typical GUI sizes
most text is black and white. It uses information in a TrueType font (the gasp
table) which specifies whether to use hinted B&W or greyscale smoothing. So
if you expected the JDK to do AA at all sizes with this setting, don't be
surprised when it doesn't. If you look closely you'll see windows native apps
are behaving similarly. See

Q: How do I obtain font metrics?

A: You may obtain a Fontmetrics instance by calling
java.awt.Graphics.getFontMetrics(Font) This will decribe the font-wide
metrics using the current FontRenderContext of the Graphics instance.

Font wide metrics are not specific to a particular piece of text. It is based on
data in the font specified by the font designer to reflect the overall design of
the font. Do not expect that, for example, the reported "ascent" of the font
will be as high as the highest ascent of any glyph in the font.

If you are looking for accurate bounds for string of text - please look at the
next question.

FontMetrics are widely used in helping to layout GUIs. They are also cheap to

Q. What is the difference between logical, visual and pixel bounds?
Logical bounds are the most commonly used and include the ascent, descent,
leading and advance of the text. They are useful to position the text
correctly, particularly when appending one string after another or for multiple
lines of text but they very likely will not enclose the rendered image.
Particular examples of this may be glyphs which extend a pixel to the left of
the "origin" at which it is drawn. "W" is a particular example - the leftmost
long diagonal may extend to the left of the rendering origin. Glyphs in italic
fonts are may commonly extend further to the right than the overall
"advance" of the text may indicate. These two issues may lead to text being
clipped on the left or the right if placed in a tight area measured using the
advance of the string. Adding a couple of pixels of padding at each end is
probably the simplest workaround for this.


Similarly large descenders, or diacritics that are used in European languages
may extend beyond the reported descent or ascent. If used to create a tight
bounding box for a label for example this may clip at the bottom or top.
Extra padding is again the simplest solution.

To get the logical bounds of a String one may use any of following methods
as appropriate :

*   Font.getStringBounds(...)
*   TextLayout.getAscent()
*   TextLayout.getDescent()
*   TextLayout.getLeading()
*   TextLayout.getAdvance()
*   GlyphVector.getLogicalBounds(...)

Note that ascent, descending, and leading which sum to the height, are also
available as font-wide properties. That is commonly used in layout of a UI
where you would not want the UI to re-layout when the text changes. These
font-wide metrics are also not guaranteed to enclose all the text.

Visual bounds guarantee that the theoretical outlines of the glyphs are
enclosed. But it still might not enclose the rendered image. Visual bounds are
returned by

    * GlyphVector.getVisualBounds(...)
    * TextLayout.getBounds()

Note that TextLayout.getBounds() in fact returns the union of the visual and
logical bounds, including any underline and strikethrough.

Pixel bounds are the most precise for where what matters is the rendered
image since pixel bounds are guaranteed to enclose all pixels and can be
useful for finding the area required to be cleared to fully erase the text. Note
that they depend on many factors (position,FontRenderContext, etc.). Since
computing pixel bounds requires that Java 2D retrieve the glyph image and
examine it, it is more expensive to compute than logical bounds.

To obtain pixel bounds use:
 * GlyphVector.getPixelBounds(...)
 * TextLayout.getPixelBounds(...) (new in Java SE 6)

Note that TextLayout.getPixelBounds(...) includes the bounds of any
underline etc.

Also note that no bounds need completely enclose any other – so use the
one that's appropriate to your needs.


Q. What are fractional metrics? What are the consequences of setting the
fractional metrics rendering hint on text performance, readability etc? When
should I use it?

A. In short fractional metrics doesn't affect performance. Principally it affects
the spacing between glyphs (characters) which on low resolution (screen)
devices can degrade the overall legibility of the text. Understanding this
requires some explanation of the topic.

"Fractional metrics" is sometimes called "Printer matching" on other
platforms. It refers to the fact that characters in a font are optimized for
particular font size and output device resolution to improve legibility of text.
These optimizations involve rounding to the pixel grid and therefore may
affect overall widths of individual glyphs as well as distances between them.

The text display system can either choose to round these "advance widths"
to an integer so that the text will have consistent spacing, or it can
accumulate the positions of the characters using the unrounded, or
fractional, values.

If it uses the fractional values then the sequence "wi" may not have
consistent spacing between the "w" and the "i" at different points along the
line. That variation in spacing creates visual noise which is disruptive to the
reading process and so is not preferred as the default on the screen. Note
that it is only the inter-glyph spacing which changes, not the glyph images,

If it uses the rounded values then the inter-character spacings are much
more uniform, but each character's rounded spacing introduces some error
and over a long string that error accumulates with each character displayed
in succession. The result may be either a longer or a shorter overall string
compared with factional metrics. That error is also dependent on the
resolution at which the text is being displayed such that the relative lengths
of strings will vary as you change the zoom factor or the resolution of the
output device. As a result, such rounded widths are considered "not matched
to the final printed output" or "not Printermatched". They also complicate
layout if you want to view the same text at different sizes or magnifications -
you have to customize the layout for each zoom level or expect the strings to
start overrunning or underrunning their static positioning.

Since non-fractional (integer) metrics are required for best screen readibility,
that is why integer metrics is the default for Java 2D.

The principal reason for turning on fractional metrics is then to closely
approximate the layout at high-device resolution when formatting output to a
printer, or for displaying a "print preview".

The simplest way to look at it is that "Fractional metrics" improve WYSIWYG
on the printer at the expense of legibility on low DPI screens.


Printing questions

Q:What are the differences between the various printing APIs I see in the

A. These are the printing APIs in the JDK:

1.1 (aka AWT) printing - java.awt.PrintJob
A UI component-oriented printing API
Can print only the 1.1 "Graphics" API, not "Graphics2D" extensions

2D printing - java.awt.print.PrinterJob
A more flexible API for printing documents
Can print all of Java 2D.
Callback printing model
Integrates with javax.print

Java Printing Service - javax.print packages
Adds discovery of printers and capabilities
Adds ability to specify job behaviour through attributes
Adds ability to install custom print services

In summary 1.1/AWT printing can be used for many basic cases but has
largely been superseded by 2D printing (as of J2SE 1.2), and when the
javax.print package was added in J2SE 1.4 it was made largely
complementary to 2D printing and integrated with it for ease of us. So most
applications which are focused on rendering to a printer will find it more
natural to centre around PrinterJob.

So the presently recommended way to print for most applications is to use
java.awt.print.PrinterJob which has methods which leverage javax.print to
enumerate printers, and can accept printing attributes from javax.print which
define job printing behaviour such as duplex printing.

Q Why is it so hard to print from Swing?

A. In most cases what this turns out to mean is:
"how can I print all a JTable?"
"how can I just ask Swing to print the contents of a text component (rather
have to work hard to do all the pagination of the rendering myself)?"

These have now been addressed: J2SE 5.0 added direct printing support on
JTable, see:


In addition, Java SE adds the same capability with

Q: What are the causes of large spool files from java.awt.print.PrinterJob and
how can I avoid them?

A: This was much more of a problem in earlier releases but as of J2SE 5.0
most applications should not see a problem. Some of it is platform specific
and in general things are better on Windows than Solaris and Linux.

Printing using non opaque colours, gradient paints, and custom paints can
cause individual pages (not the whole print job) to be generated as a raster
at device resolution. This can be mitigated in a few ways:
the application printing code could avoid using these.
the application could render a selected area which uses these to an offscreen
opaque BufferedImage and then draw that BufferedImage to the printer
the application could lower the device resolution of the print job which may
be higher than needed, using the PrinterResolution attribute.

Printing Text on Solaris with non-Postscript standard fonts. In many cases
the font requested by an application cannot be expected to be available to a
Postscript printer, and the JDK has no way to determine the capabilities of
the destination Postscript printer anyway. So often the JDK will generate text
as stroked and filled outlines. This is particularly a problem in locales where
there is no standard Postscript font support.

For English locales however, Latin text in the standard logical fonts such as
Dialog, SansSerif, Serif are mapped directly to Postscript printer fonts and
should generate compact Postscript. The same happens in the Japanese
locale. Also fonts which are "compatible" such as the TrueType font "Times
New Roman" which can be mapped to the Postscript "Times Roman" font will
be OK. But keeping to the "logical" fonts is usually the simplest way of
getting the most compact output.

Q: When printing using java.awt.PrinterJob, why does it print each page at
least twice (and sometimes much more than that)?

A: The root of this is that Java 2D printing needs to be able to print
everything that Java 2D can render to the screen, and that includes
translucent colours, images etc which cannot always be printed directly in
Postscript or GDI except when printing everything as one big image, so the
implementation tries to avoid this by calling first to discover the rendering
that needs to be done for the page. If its simple opaque rendering then only
one more call is needed to render the page. If there are translucent colours
then multiple calls are done for "bands" down the page to limit the size of the
image being generated and hence constrain peak memory usage.


Q How do I keep the information from getting cut off from the top and left
sides of the page when I print using the Java 2D printing API?

Because many printers cannot print on the entire paper surface, the
PageFormat specifies the imageable area of the page: this is the portion of
the page in which it's safe to render. The specification of the imageable area
does not alter the coordinate system; it is provided so that the contents of
the page can be rendered so that they don't extend into the area where the
printer can't print. If you find that information is clipped from your page, you
might need to translate the information to the imageable area of the page, as
shown in this sample:
   public int print(Graphics g, PageFormat pf, int pageIndex)
      throws PrinterException
      Graphics2D g2 = (Graphics2D)g;
      pf.getImageableY() + 72);

Q: Why are my 1-pixel wide lines repositioned when I print them? How do I
correct this?

A: For horizontal or vertical 1-pixel wide line fills, it is generally better to use
fillRect rather than drawLine. The rounding of the drawLine method moves
lines by half a device pixel, which make the lines appear more consistent
whether or not antialiasing is applied. Therefore, if you have a 1-pixel wide
line, the line is moved by half of its width. Because this adjustment occurs at
the device-space level, your lines can move by half of a line width on
printouts from high-resolution printers.

Q: How do I trouble shoot printing problems in Windows?

First, make sure that you have the latest printer driver. It is advisable to use
the printer vendor's version of the driver and you can generally do this by
downloading it online at their website. If you have the latest driver and are
still having problems, sometimes a simple change in the printer's setting or
Window's advanced spool options will fix your problem. You can also go to and search the bug archive for similar problem. A
workaround may be available there. If not, please file a bug.

Q: How do I scale an image to fit a page?

Here is a sample code that uses the page's imageable width and height to
scale an image.

public int print(Graphics graphics, PageFormat pageFormat, int
 pageIndex) throws PrinterException


if(pageIndex > 0)
   return Printable.NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) graphics;

//Set us to the upper left corner
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
AffineTransform at = new AffineTransform();

//We need to scale the image properly so that it fits on one page.
double xScale = pageFormat.getImageableWidth() / m_image.getWidth();
double yScale = pageFormat.getImageableHeight() / m_image.getHeight();
// Maintain the aspect ratio by taking the min of those 2 factors and
using it to scale both dimensions.
double aspectScale = Math.min(xScale, yScale);

g2d.drawRenderedImage(m_image, at);
return Printable.PAGE_EXISTS;

Q: When I print using PDF or HTML using the corresponding DocFlavor, how
come it is printed as garbage or plain text?

First, do not assume that any of the defined DocFlavors are supported. Use
the PrintService's isDocFlavorSupported to find out which flavors are
supported. If you find out that it is not supported but know that your printer
can handle this then you may go ahead and print it using the This is equivalent to printing a raw data. If on
the other hand your printer does not support it you need to write your own
PrintService which handles the conversion from PDF/HTML to the printer
language e.g. PostScript.
Q: Why is Java unable to print to my CUPS 1.2 printers ?
As noted in the CUPS 1.2 releases notes CUPS now supports
Unix Domain Sockets :

/Domain Sockets;/
CUPS now supports the much faster UNIX domain sockets for local printing
As a consequence, by default CUPS on Unix/Linux is now configured to listen
for connections on both
localhost:631 via a TCP/IP socket connection - this is the same as in
previous releases.
a unix domain socket at /var/run/cups/cups.sock


So far so good, except that the unix domain socket is now the default and
the CUPS API call cupsServer() now returns the unix domain socket pat
/var/run/cups/cups.sock instead of "localhost".

This can be an incompatible change for any pre-1.2 aware client which
retrieves that name and expects to be able to use to open a TCP/IP

In particular this breaks Sun's JDK (aka Java/aka Java SE, aka JRE) versions
1.5 and Java SE 6. ie all releases to date (Dec 2006) which connects to the
CUPS IPP server to provide access to platform printing support. The symptom
may be no printers found, or printers 'not accepting jobs'. This will be
patched in the next available minor update releases of each of JDK 1.5 and
JDK6. The Sun bug to track this can be viewed at and the
updated releases in which this is fixed will then be viewable there. The
expectation is that this will be fixed in JDK6 update 1 (1.6.0_01) and JDK 1.5
update 12 (1.5.0_12).

Until then there are several workaround options for configuring CUPS 1.2 to
work with JDK

1. System-wide :
Edit the cups configuration file, usually /etc/cups/cupsd.conf, and locate
and comment out using a # the line that listens on the domain socket. It
should look like this when you are done:
# Listen /var/run/cups/cups.sock
Ensure the line to listen on TCP/IP port 631 is present and UNcommented :
Listen localhost:631

Finally save the file and restart cups
sh /etc/init.d/cups restart

2. Per-user workaround #1 Add a ~/.cups/client.conf file with a "ServerName
localhost" line. This will make the CUPS API library prefer localhost as the
server to report

3. Per-user workaround #2 Set the CUPS_SERVER environment variable to
localhost so that the CUPS API library will use and report that :
CUPS_SERVER=localhost; export CUPS_SERVER

This approach could if necessary be set only in the environment in which
your Java printing application is run and its effects confined to that.

There is one additional step to the workaround for at least some systems.
JDK looks for"". This is usually a symlink to the specific version, eg
"" but on systems without a developer package it may not exist.


The solution is to locate the cup library on your system and if necessary
create a symbolic link. For example
cd /usr/lib
ln -s

Rendering questions

Q: What is the Rendering Process?

A Rendering is the process of taking a collection of shapes, text, and images
and figuring out what colors the pixels should be on a screen or printer. In
the Java 2D API, the Graphics2D class is the rendering engine: the
Graphics2D object contains state attributes, such as color, and applies these
attributes to the primitives when rendering them to various output devices.

The seven different attributes are:
paint, which represents the color or pattern rendered to the destination for
the text and shape draw and fill methods.
stroke, which describes the line style of the outline of shapes which are
rendered using the shape draw (but not fill) methods.
font, which is the font of the text to be rendered in the text draw methods.
rendering hint, which suggests optional algorithms for how a primitive should
be rendered, such as whether a faster or more accurate algorithm should be
transform, which represents the mapping from user space to device space
and additional coordinate transforms, such as rotate and scale, to be applied
to all primitives.
composite, which defines how the paint colors should replace or be mixed or
blended with the colors already in the destination for all primitives.
clip, which identifies a subset of the pixels in the destination which are
allowed to be changed. Pixels which fall outside the clip should never be
modified by any primitive.

The following figure illustrates the rendering process:

Q: What kinds of shapes can I draw using Java 2D?

A: The Java 2D API provides classes for drawing basic shapes like rectangles
and circles but also allows you to draw any arbitrary shape. The following
table lists the classes that represent predetermined shapes.
  Arc2D        Represents an arc defined by a bounding rectangle, start angle,
angular extent, and a closure type.
CubicCurve2D         Represents a cubic parametric curve segment.


Ellipse2D     Represents an ellipse defined by a bounding rectangle.
Line2D        Represents a line segment in (x, y) coordinate space.
Point2D       A point representing a location in (x,y) coordinate space. Points
render nothing when drawn or filled, but the Point2D class is used in many of
the APIs that manipulate or construct shapes.
QuadCurve2D          Represents a quadratic parametric curve segment.
Rectangle2D Represents a rectangle defined by a location (x, y) and
dimension (w x h).
RoundRectangle2D Represents a rectangle with rounded corners defined by a
location (x, y), a dimension (w x h), and the width and height of the corner

In addition to these classes that allow you to create common shapes, the
Java 2D API provides two other classes that allow you to define odd shapes:
GeneralPath and Area. Shapes created with GeneralPath must be created
segment by segment, but this means that you can combine straight lines and
curved lines into a single shape. The Area class supports constructive area
geometry, which allows you to combine two shapes to create another shape,
either by adding or intersecting the shapes, subtracting one shape from
another, or by subtracting the intersection of the shapes. To see Java 2D and
CAG in action, go to
Constructing Complex Shapes from Geometry Primitives in the Java Tutorial.

You can also create a Shape object from a String by calling getOutline on a
TextLayout object. After creating the Shape, you can perform operations
such as filling and transforming on the Shape.

For more information on working with shapes in Java 2D, see the 2D
Graphics tutorial.

Q: How do I draw on an image?

A: If your image is an external image in a format such as JPG then first you
load it into a BufferedImage using the javax.imageio.ImageIO class Then you
can obtain a Graphics2D for rendering to the in-memory copy of the image.
Here's a sample that does this:
   BufferedImage bi = null;
   try {
       bi = File("images/bld.jpg"));
   } catch (IOException ioe) {
   Graphics2D g2d = bi.createGraphics();
   g2d.drawLine(10, 10, 20, 20); // draw a line on the image


Q: I have a shape whose outline intersects itself. How do I control the filling
of the shape?

A: You can control the filling of an arbitrary shape by setting the winding
rule. The winding rule specifies which part of a shape is considered the inside
of the shape. If you have an arbitrary shape with an outline that intersects
itself, you might get different filling results depending on which winding rule
you choose. Because the GeneralPath class is used to represent such
arbitrary shapes, any Shape objects that are instances of GeneralPath can
use the setWindingRule(int) method to set the winding rule to either
WIND_NON_ZERO or WIND_EVEN_ODD. See the GeneralPath class
comments for a description of each winding rule.

Note that any given Shape can only have a single winding rule that applies
for its entire outline. If you have a complex combination of shapes that
overlap and intersect with each other in many places, it may be easier to use
the Area class to combine the shapes with explicit intersection, union,
subtraction and exclusive or operations rather than to try to control the
action of the multiple overlapping sections with a single winding rule.

Q: What does it mean to flatten a Shape?

A: Flattening is the process of converting the curved lines of a Shape into
straight line segments. During rasterization, flattening is often performed on
all curved path segments before they are stroked or filled because rendering
calculations are much faster for straight lines than for curves. Shape objects
provide a getPathIterator(aT, flatness) method which returns a PathIterator
object that iterates through the path with only straight line segments that
approximate the original path of the Shape. The flatness parameter must be
a double value greater than or equal to 0.0 which controls how closely the
straight lines approximate the curve. The smaller the number, the closer the
straight lines will approximate the curve. The original Shape object is not
modified by this method as the flattening is done on the fly as the path is

Q: How do I draw a quadratic arrow-headed curves?

A: There is no direct API for doing this. However, the following sample code
can be used to achieve this effect.
     GeneralPath path = new GeneralPath();
     float p1x = 10, p1y = 10; // P1
     float p2x = 100, p2y = 10; // P2
     float cx = 55, cy = 50;     // Control point of the curve
     float arrSize = 5;        // Size of the arrow segments

     float adjSize = (float)(arrSize/Math.sqrt(2));
     float ex = p2x - cx;


     float ey = p2y - cy;
     float abs_e = (float)Math.sqrt(ex*ex + ey*ey);
     ex /= abs_e;
     ey /= abs_e;

     // Creating quad arrow
     path.moveTo(p1x, p1y);
     path.quadTo(cx, cy, p2x, p2y);
     path.lineTo(p2x + (ey-ex)*adjSize, p2y - (ex + ey)*adjSize);
     path.moveTo(p2x, p2y);
     path.lineTo(p2x - (ey + ex)*adjSize, p2y + (ex - ey)*adjSize);

Q: Why do I get unexpected results when I use the setTransform method of
Graphics2D to perform transformations?

A: Because the setTransform method is not intended for adding new
coordinate transformations onto an existing transform. In fact, when you use
setTransform, you are overwriting the Graphics2D object's current transform,
which might be needed for other purposes, such as applying a scaling
transformation to adjust for printer resolution. The setTransform method
should ONLY be used to restore the Graphics2D transform to an earlier saved
state after performing some temporarily transformed rendering.

To perform transformations, use these steps:
Use getTransform to get the current transform:
AffineTransform aT = g2.getTransform();
Use the transform, translate, scale, shear, or rotate methods to concatenate
a transform:
Perform the rendering:
Restore the original transform using setTransform:
Q: How do I join the Java 3D projects on

To join the parent java3d project you will need follow these steps:

Create a account if you don't already have one
Login to using your username/password
Go to the role request page in the parent java3d project, and request an
"Observer" role

Joining the parent java3d project lets you file issues (bugs and feature


Note: unless you want to work with the Java 3D internals, or see automated
source code checkin messages, you only need to join the parent java3d

Q: How do I subscribe to the Java 3D discussion forum / mailing list

The new Java 3D interest list is available either as a discussion forum (which
is what most of the community uses) or as a mailing list. Messages posted to
one are cross-posted to the other automatically.

Discussion Forum

To participate in the discussion forum, you should first do the following:

Create a account if you don't already have one
Login to using your username/password

The URL for the Java 3D forum on is:

Mailing List

If you prefer to send/receive messages via a mailing list, you will need to
follow these steps:

Create a account if you don't already have one
Login to using your username/password
Go to the "Mailing Lists" page of the parent java3d project and subscribe to
the "" mailing list

You will then receive e-mail when messages are posted to the forum or sent
to the "" mailing list.

More Information

For a description of the various mailing lists and the forum, go here:

Q: How do I file an issue?

You need to join the parent java3d project as an Observer, if you aren't
already signed up for a role in the project.

All Java 3D-related bugs for j3d-core, j3d-core-utils, vecmath, and j3d-
examples, are filed using the Issue Tracker in the parent java3d project.


To file an issue:

Login to using your username/password
Go to the Issue Tracker and click on the appropriate link for the type of issue
you want to enter: Defect, Patch, Task, Feature, or Enhancement. Defect is
the most common one and is used for reporting bugs.

After you submit a Defect, please attach a test program that reproduces the
problem. You can do this by going to the issue and clicking on the "Create a
new attachment" link, which is located below the summary.

For more information about filing issues, please see:

Q: How do I download the Java 3D source code?

Before downloading the source code, you will need to create a
account if you don't already have one.

You must use CVS to download the source code for projects on (see:
Q: What is CVS and How Do I Use It? if you are unfamiliar with CVS). Java
3D is composed of three main CVS modules (projects), which can be checked
out using a CVS client:


In order to build the code, the three top-level directories must be named
exactly as shown above and they must be sibling directories. To ensure this,
run the cvs checkout command for each of the modules from the same
parent directory. For example:

cd <cvs-root-dir>
cvs checkout vecmath
cvs checkout j3d-core
cvs checkout j3d-core-utils

Q: How do I build Java 3D from the source code?

You need to do the following steps:

Download the source code for the following three projects: j3d-core, j3d-
core-utils, and vecmath (see Q: How do I download the Java 3D source


Build vecmath (see vecmath/README-build.html in the source tree)
Build j3d-core (see j3d-core/README-build.html in the source tree)

Q: What is CVS and how do I use it?

Concurrent Version System (CVS) is a source code control system used by projects. If you are new to CVS, Login to and go to the
following page:


For more information see the following CVS links:

Q: How can I contribute to Java 3D?

For information on how you can contribute to the Java 3D projects on, go here:

Q: What graphics cards are supported?

Java3D 1.3.1:

Works fine on NVidia cards. ATI cards with new drivers do not work with j3d
1.3.1 on Windows (on Linux work fine). Matrox cards do not work with
turned off Z-buffer (it is turned off by default in this videocards, so, if you
want to run java3d on matrox, you should turn on Z-buffer). Also, in some
cases matrox does not work even with turned Z-buffer or does not render
textures (these problems can be solved by using DirectX j3d version, setting
16-bit color depth, setting 800x600 video mode at last). Intel cards have
troubles with refreshing on OpenGL version.

Java3D 1.3.2:

Works fine on NVidia, ATI ( Win32 : CATALYST 5.3 or later ) and Matrox
(with turned on Z-buffer). Also works fine on Windows 2000 using S3
Savage4 ( driver Sigma Savage4 v8.40.03) . Savage4 is a OpenGL? 1.1
hardware, so it lacks some advanced features, as DOT3 bump mapping,
Cube mapping, etc.


Java3D 1.4:

Works fine as in Java3D 1.3.2. If programmable shader is used NVidia family
( Tested : FX 500, FX 3000, FX6600, FX Go6600 and FX6800) works well.
ATI has limited success.

Q: What platforms are supported?

The following platforms are fully supported and have nightly builds. See the
binary downloads page:
Windows (x86)
Linux (x86)
Linux (AMD64)
Solaris (SPARC)
Solaris (x86)

The following platforms can be built from the Ant build.xml file, but are not
supplied as pre-built downloads.
Linux (Power PC)
Linux (IA64 Itanium)

The following platform is not officially supported, but java3d has been ported
to it by the manufacturer. The latest version of java3d may not be available.

Mac OS X 10.3.1 or later.
According to Apple, 10.4 (Tiger) is not supported, but user reports suggest
that Java3d works fine on 10.4 with no problems.

See Apple's download site:

Q: Is software rendering supported?

No. Java3d requires a supported 3D graphics card and communicates with it
using native method calls. However, software rendering has been requested
by some members of the user community.

Q: How do I download and install a Java 3D binary release?

The answer varies with the operating system.

For Versions of Mac OSX after Panther, no installation is required.


On windows, Linux, and Solaris, installers are available here:

Q: How do I run a Java 3D application?

Like other java applications, Java3D applications are invoked by calls to:

static void main (String[] args) { .. }

In other words, as long as the Java3D classes are installed properly and
available, Java 3D applications are invoked in the exact same manner as
other applications.

Similarly, Java3D applets run exactly like other applets.
Q: What are the Java Foundation Classes?
A: The Java Foundation Classes (JFC) are a comprehensive set of GUI
components and services which dramatically simplify the development and
deployment of commercial-quality desktop and Internet/Intranet

Q: What is the difference between JFC and AWT?
A: The Java Foundation Classes are a superset that contains AWT. JFC
extends AWT by adding many components and services.

Q: How is JFC different from other framework classes from third parties?
A: There are six main differences:
No need to bundle. Java Foundation classes are core to the Java 2 Platform.
JavaBeans components. All JFC components are JavaBeans components. JFC
components have all the benefits that JavaBeans components offer --
reusability, interoperability, and portability. For more information on
JavaBeans visit
There is no framework lock-in. Developers can easily bring in other third-
party JavaBeans components to enhance their applications written using JFC.
JFC offers an open architecture.
Truly cross-platform. Being part of the Java Platform, all JFC components and
services are designed to work everywhere. For example, Drag and Drop
services within JFC work the same between the Java Platform and all
operating systems. While third-party vendors might be able to implement
certain components to be cross-platform, only Sun can make sure that
foundation services behave consistently across all Java-Compatible
Fully customizable. Developers can easily extend these components to create
other more customized components. In addition, even the look and feel of
these components can be change by either developers or users through the
Pluggable Look and Feel architecture in JFC.


Not just components. In addition to components, Java Foundation Classes
include foundation services such as Java 2D. These services significantly
enhance the type of applications developers can build.

Q: Are the Java Foundation Classes easy to use?
A: Not being a port from a different environment, the Java Foundation
Classes conform 100% with Java's object and component model. Developers
find JFC a very easy and natural extension to the Java Platform.

Q: How do the Java Foundation Classes make developers' lives easier?
A: The Java Foundation Classes substantially reduces the amount of
programming needed by providing many reusable and cross-platform UI

In addition, foundation services offered in JFC enable developers to build
richer solutions with fewer lines of code. The last and most important point is
that developers don't have to worry that their application will only perform
well on one platform. JFC is designed to be 100% cross-platform.

Q: Are the Java Foundation Classes supported by major Java tools vendors?
A: Absolutely; we have close relationships with all the major Java
development environment vendors. As part of the Java Platform, JFC is
available in all major Java development tools. A listing of tool providers can
be found on the site under the product directory.

Q: Do the Java Foundation Classes run better on one platform than others?
A: Because the Java Foundation Classes are designed to be truly cross-
platform, they run equally well on all Java Compatible Platforms.

Q: What specific components are available in JFC?
A: The JFC/Swing components can be divided into two groups -- those that
provide improved, JFC/Swing versions of AWT components, and those that
are new. Swing versions
of AWT components          New components
text fields
check boxes
radio buttons
combo boxes (Choice in AWT)
text areas
scroll panes and scroll bars
menus and menu bars        tool tips


styled text areas
progress bars
spinners (as of 1.4)
formatted text fields (as of 1.4)
color choosers
file choosers
split panes
tabbed panes
internal frames
layered panes

Q: What specific foundation services are available in JFC?
A: Available for JDK 1.1 and in the Java 2 Platform:
Swing components (listed above)
Pluggable look and feel
Accessibility: support for people with disabilities

Available only in the Java 2 Platform:
Java 2D API
Drag and drop

For specific details on each feature, visit The Swing Connection at

Q: What does a JFC-based application user interface look like?
A: Applications built using JFC are not locked in to a specific look and feel.
Using JFC, developers can create apps that either have a native platform look
and feel or use the Java look and feel -- or they can create their own custom
look and feel. The power lies in the hands of developers -- they can develop
their products using the look and feel that is most appropriate for their users.

Q: What is the difference between lightweight components and peerless
A: They are the same thing. These are just two term that describe the
attributes of JFC components.

Q: What does JFC cost?
A: Nothing! Sun does not charge for the use or distribution of JFC.

Q: What is Swing?
A: Swing is the project code name for the lightweight GUI components in

Q: What is Java Accessibility?


A: As part of JFC, the Accessibility API enables Java applications to work with
alternate input and output devices such as Screen Readers, Screen
Magnifiers, Braille terminals, and others. The Accessibility API takes the
current Java system that is visually oriented and extends it to be usable by
people who need to work with other non-visual devices. We are truly taking
"Write Once, Run Anywhere" to another level by extending the benefits of
Java Computing to users with disabilities.

Q: What is Java 2D?
A: With Java 2D, developers can render, manipulate, and transform complex
2D images and text. Java 2D enables the creation of richer-looking
components and applications.

Q: Why was the Java look and feel developed?
A: To provide a common interface for developers who are deploying
applications and services in a heterogeneous computing environment.

Q: Are other native look and feel designs available?
A: Yes. The Java 2 Platform, SE, provides pluggable look-and-feel
implementations for the Windows and UNIX platforms. Other look and feels
are available, as well.

Q: Why is there a locking mechanism on the Windows look and feel?
A: We have not determined that we have the right to deliver the Windows
look and feel on platforms other than Windows. If Microsoft were to confirm
our right to deliver this look and feel on other operating systems, we would
be delighted to remove the lock. To date, Microsoft has declined to do this.

Why do I get a NullPointerException when loading a JAR file into the

Usually this is because of a mistake in the JAR file being loaded. In the
meantime, typical errors include:
The MANIFEST file uses classes using the wrong file separator ("/" should be
used in all platforms).
The MANIFEST file refers to classes in a package but the actual .class files
are not really in that package.

Why do I get a duplicate name error when loading a JAR file?

The most common reason for a "java.lang.ClassFormatError: Duplicate
name" error is that a .class file in the JAR contains a class whose class name
is different from the expected name. So for example if you have a file called
"a/B.class" and it contains a class called "B" or "a.X" instead of the class
"a.B" then you will get this error.


The most common causes for this problem are either forgetting to include a
"package a;" statement or having a "package" statement with the wrong

Why does my Beans.instantiate() fail?

Beans.instantiate() does two things: it loads a class and creates a Class
object, and it then instantiates an object of that class. If the Bean name
corresponds to a serialized Bean prototype, it uses that prototype. Otherwise
the instantiation uses a zero-argument constructor. Several things may fail in
these actions, including:
There may not be a class of the given name
The class may not be public
The class may be in a package that cannot be created given the existing
Security Manager (for example, the Applet Security Manager typically will not
let the applet instantiate "java.*" and "sun.*" classes)
There may not be any public zero-argument constructor for the class.
The serialized stream may contain a version of the class that is not
compatible with the one loaded (or available through the classloader
argument) in the JVM.

A typical idiom to use Beans.instantiate is
Beans.instantiate(this.getClass().getClassLoader(), theBeanName)

Why nobody at Sun wants to read the messages sent to java-

Probably, because of the fact, that 99% of all messages is spam. It is
recommended to post on JavaBeans forum, which is inspected by Sun
engineers on a regular basis.

How can I subscribe/unsubscribe to the BEANS-INFO mailing list?

A discussion list, BEANS-INFO, has been set up for people interested in the
JavaBeans API. It is a forum where users help users, but you'll see
participation from Sun engineers, too. This is the primary forum for
discussions pertaining to JavaBeans.
Subscribing to BEANS-INFO

To subscribe to the BEANS-INFO list, send email with

in the message body to:
Sending Messages to BEANS-INFO

To send messages to the discussion list, send email to:


Please help in keeping the list's atmosphere polite and reasonable. The
people who answer your questions do it mostly in their free time and without
obligations to do so. If you seek help, please follow these guide lines:
First search the archive to find out if this problem has been discussed before.
Including the following infos in your email will make it more likely to get a
quick response:
short and precise problem description (i.e. expected vs. actual behavior)
output of the program and full exception trace
Java Version
the source code of a small program which reproduces the problem. Keep it as
small as possible, but it should still be compilable.
Please do not send large attachments (>50KB) to the list. Instead, make the
file available via HTTP and FTP and send the link to the list.

Unsubscribing from BEANS-INFO

To unsubscribe from the BEANS-INFO list, send email with

in the message body to:
What is JavaBeans?

JavaBeans is a portable, platform-independent component model written in
the Java programming language, developed in collaboration with industry
leaders. It enables developers to write reusable components once and run
them anywhere -- benefiting from the platform-independent power of Java
technology. JavaBeans acts as a Bridge between proprietary component
models and provides a seamless and powerful means for developers to build
components that run in ActiveX container applications.

What is a Bean? Why isn't a Bean an Applet?

JavaBeans components, or Beans, are reusable software components that
can be manipulated visually in a builder tool. Beans can be combined to
create traditional applications, or their smaller web-oriented brethren,
applets. In addition, applets can be designed to work as reusable Beans.

Individual Beans will function quite differently, but typical unifying features
that distinguish a Bean are:
Introspection: enables a builder tool to analyze how a Bean works
Customization: enables a developer to use an app builder tool to customize
the appearance and behavior of a Bean
Events: enables Beans to communicate and connect together
Properties: enable developers to customize and program with Beans
Persistence: enables developers to customize Beans in an app builder, and
then retrieve those Beans, with customized features intact, for future use


Why are component architectures useful?

Developers are turning to creating components rather than monolithic
applications to free themselves from slow, expensive application
development, and to build up a portable, reusable code base. This enables
developers to quickly attack new market opportunities, new joint
development opportunities, and new ways to sell smaller packages of

Is JavaBeans a complete component architecture?

JavaBeans is a complete component model. It supports the standard
component architecture features of properties, events, methods, and
persistence. In addition, JavaBeans provides support for introspection (to
allow automatic analysis of a JavaBeans component) and customization (to
make it easy to configure a JavaBeans component).

Why a component architecture for the Java platform?

JavaBeans brings the extraordinary power of the Java platform to component
development, offering the ideal environment for a developer who wants to
extend the concept of reusable component development beyond one platform
and one architecture to embrace every platform and every architecture in the

What kind of industry support exists for JavaBeans?

A coalition of industry leaders in component development worked with
JavaSoft to create the JavaBeans specification, which was released to the
Internet for public comments on September 4, 1996. The "frozen" JavaBeans
specification combines the work of Apple, Borland, IBM, JustSystem,
Microsoft, Netscape, Rogue Wave, SunSoft and Symantec and many, many
others... We're very pleased to see the tools community swiftly embracing
JavaBeans by announcing support for JavaBeans in their visual application
builder tools.

Are there JavaBeans components available that I can buy today?

Yes. A large number of companies, both large and small, have announced
their plans to deliver JavaBeans-based products.

What is the relationship between Sun's JFCs and JavaBeans?

The JFC (Java Foundation Classes) is based upon the AWT (Abstract
Windowing Toolkit), which has been part of the Java platform from the
beginning. JFC effectively adds a richer set of visual elements for building


JavaBeans components and applications. See the JFC web site for more

What are the security implications for downloading Beans over the Internet?

JavaBeans does not add any security features to the Java platform. Rather,
JavaBeans components have full access to the broad range of security
features that are part of the Java platform. JavaBeans components can be
used to build a range of different kinds of solutions from full-fledged Java
desktop applications to web-based Applets.

What are/is Enterprise JavaBeans?

Enterprise JavaBeans (EJB) is an API specification for building scalable,
distributed, component-based, multi-tier applications. It leverages and
extends the JavaBeans component model to provide a rich object-oriented
transactional environment for developers building enterprise applications.

Enterprise JavaBeans (EJB) technology is the basis of Java 2 Platform,
Enterprise Edition (J2EE). EJB technology provides the scalable architecture
for executing business logic in a distributed computing environment. J2EE
makes the life of an enterprise developer easier by combining the EJB
component architecture with other enterprise technologies to solutions on the
Java platform for seamless development and deployment of server side

What is the relationship between Enterprise JavaBeans and JavaBeans?

Enterprise JavaBeans extends the JavaBeans component model to handle the
needs of transactional business applications.

JavaBeans is a component model for visual construction of reusable
components for the Java platform. Enterprise JavaBeans extends JavaBeans
to middle-tier/server side business applications. The extensions that
Enterprise JavaBeans adds to JavaBeans include support for transactions,
state management, and deployment time attributes.

Although applications deploying the Enterprise JavaBeans architecture are
independent from the underlying communication protocol, the Enterprise
JavaBeans architecture specifies how communication among components
maps into the underlying communication protocols, such as CORBA/IIOP.

Where can I find more information on EJB and J2EE?

For more information on EJB, see For
more information about J2EE and how to get the specification, see


What is the InfoBus?

The InfoBus is a compact Java API which allows cooperating applets or
Beans, on a Web page or in any other Java application, to communicate data
to one another. The InfoBus architecture enables Beans to be categorized as
"data providers" and "data consumers". Data providers are Beans whose
primary function is to access data from their native store, such as a DBMS,
spreadsheet, flat file, Lotus Notes database etc., and to offer data onto the

Data consumers retrieve data from the bus, for analysis or visual display.
This segregation of provider from consumer is extremely powerful in that it
enables applications to be independent of their data; for example, a charting
Bean need not understand SQL or JDBC in order to access DBMS data.

Of course, a Bean can be both a consumer and provider: for example a
spreadsheet may accept data from a DBMS and provide data to a chart Bean.

How does the InfoBus relate to JavaBeans?

The InfoBus specification extends JavaBeans by providing a set of enhanced
interfaces to share and exchange dynamic data.

Does the InfoBus compete with JavaBeans?

On the contrary, InfoBus extends the power of JavaBeans to a new range of
more dynamic applications. InfoBus is fully compatible with JavaBeans, and
Lotus enthusiastically supports JavaBeans as the component standard for
Java. Wherever possible, InfoBus uses the existing mechanisms of

Will the general public have access to the InfoBus API's?

Yes, under the usual terms of the JDK license. The specification and
technology preview are available in our products archive.

Is InfoBus easy to use?

Using InfoBus aware components, such as the ESuite components from
Lotus, users can easily construct powerful data driven applications. No
programming or scripting is required: simple parameters are used to
establish connections to databases and to select data for processing. For
developers creating InfoBus components, InfoBus offers a straightforward
API compatible in style with other features of JavaBeans.


Is the InfoBus client side only?

Yes. InfoBus is typically used to communicate among Beans at the client, and
it can also be useful for sharing information among components at a single
server site. The initial version of InfoBus is not distributed, and is therefore
not intended for transmission of data between clients and servers.

A variety of Java communication services, including JDBC, CORBA, and RMI
can be used by InfoBus components for access to distributed data. For
example, the ESuite Data Access component is a Bean that connects any
JDBC compliant data source to the InfoBus. Once the data is on the bus, it
can easily be imported by any InfoBus Data Consumer, such as a
spreadsheet, charting component, word processor or data analysis tool.

JavaBeans has mechanisms like "bound properties" for data transfer between
components. Why is the InfoBus necessary?

JavaBeans mechanisms, such as bound properties, are very useful in cases
where the type of data to be communicated can be hard-coded into the
source and target components. The InfoBus adds additional features required
for more dynamic data interchange. These can be cases where
communication is driven by the content of the data and where the nature of
the data to be exchanged is determined at runtime.

Can both Java applets and JavaBeans components use the InfoBus?


What is the relation between the InfoBus and RMI?

The InfoBus architecture addresses Beans talking to one in a single JVM not
across multiple JVMs; while RMI (Remote Method Invocation) is intended for
communication across JVMs (different Java Virtual Machines across the
network). As for IIOP, one can envision a JavaBeans component that uses
RMI to talk to something on another JVM and then publishes the data on the

Additionally, RMI could be used to allow components in different security
classes to communicate within the same JVM.

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


To top