Professional Documents
Culture Documents
About The Java Technology
About The Java Technology
About The Java Technology
The Java programming language is a high-level language that can be characterized by all
of the following buzzwords:
Architecture
Simple
neutral
Object
Portable
oriented
Distributed High performance
Interpreted Multithreaded
Robust Dynamic
Secure
With most programming languages, you either compile or interpret a program so that you
can run it on your computer. The Java programming language is unusual in that a
program is both compiled and interpreted. With the compiler, first you translate a
program into an intermediate language called Java bytecodes —the platform-independent
codes interpreted by the interpreter on the Java platform. The interpreter parses and runs
each Java bytecode instruction on the computer. Compilation happens just once;
interpretation occurs each time the program is executed. The following figure illustrates
how this works.
You can think of Java bytecodes as the machine code instructions for the Java Virtual
Machine (Java VM). Every Java interpreter, whether it's a development tool or a Web
browser that can run applets, is an implementation of the Java VM.
Java bytecodes help make "write once, run anywhere" possible. You can compile your
program into bytecodes on any platform that has a Java compiler. The bytecodes can then
be run on any implementation of the Java VM. That means that as long as a computer has
a Java VM, the same program written in the Java programming language can run on
Windows 2000, a Solaris workstation, or on an iMac.
You've already been introduced to the Java VM. It's the base for the Java platform and is
ported onto various hardware-based platforms.
The Java API is a large collection of ready-made software components that provide many
useful capabilities, such as graphical user interface (GUI) widgets. The Java API is
grouped into libraries of related classes and interfaces; these libraries are known as
packages. The next section, What Can Java Technology Do?, highlights what
functionality some of the packages in the Java API provide.
The following figure depicts a program that's running on the Java platform. As the figure
shows, the Java API and the virtual machine insulate the program from the hardware.
Native code is code that after you compile it, the compiled code runs on a specific
hardware platform. As a platform-independent environment, the Java platform can be a
bit slower than native code. However, smart compilers, well-tuned interpreters, and just-
in-time bytecode compilers can bring performance close to that of native code without
threatening portability.
However, the Java programming language is not just for writing cute, entertaining applets
for the Web. The general-purpose, high-level Java programming language is also a
powerful software platform. Using the generous API, you can write many types of
programs.
An application is a standalone program that runs directly on the Java platform. A special
kind of application known as a server serves and supports clients on a network. Examples
of servers are Web servers, proxy servers, mail servers, and print servers. Another
specialized program is a servlet. A servlet can almost be thought of as an applet that runs
on the server side. Java Servlets are a popular choice for building interactive web
applications, replacing the use of CGI scripts. Servlets are similar to applets in that they
are runtime extensions of applications. Instead of working in browsers, though, servlets
run within Java Web servers, configuring or tailoring the server.
How does the API support all these kinds of programs? It does so with packages of
software components that provide a wide range of functionality. Every full
implementation of the Java platform gives you the following features:
• The essentials: Objects, strings, threads, numbers, input and output, data
structures, system properties, date and time, and so on.
• Applets: The set of conventions used by applets.
• Networking: URLs, TCP (Transmission Control Protocol), UDP (User Datagram
Protocol) sockets, and IP (Internet Protocol) addresses.
• Internationalization: Help for writing programs that can be localized for users
worldwide. Programs can automatically adapt to specific locales and be displayed
in the appropriate language.
• Security: Both low level and high level, including electronic signatures, public
and private key management, access control, and certificates.
• Software components: Known as JavaBeansTM, can plug into existing component
architectures.
• Object serialization: Allows lightweight persistence and communication via
Remote Method Invocation (RMI).
• Java Database Connectivity (JDBCTM): Provides uniform access to a wide range
of relational databases.
The Java platform also has APIs for 2D and 3D graphics, accessibility, servers,
collaboration, telephony, speech, animation, and more. The following figure depicts what
is included in the Java 2 SDK.
Note: The Java 2 SDK, Standard Edition v. 1.3. The Java 2 Runtime Environment (JRE)
consists of the virtual machine, the Java platform core classes, and supporting files. The
Java 2 SDK includes the JRE and development tools such as compilers and debuggers.
This section dissects the "Hello World" application you've already seen. Here, again, is
its code:
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
The "Hello World" application has two blocks of comments. The first block, at the top of
the program, uses /** and */ delimiters. Later, a line of code is explained with a
comment that's marked by // characters. The Java language supports a third kind of
comment, as well -- the familiar C-style comment, which is delimited with /* and */.
Comments in Java Code further explains the three forms of comments that the Java
language supports.
Defining a Class
In the Java language, each method (function) and variable exists within a class or an
object (an instance of a class). The Java language does not support global functions or
variables. Thus, the skeleton of any Java program is a class definition. Defining a Class
gives you more information.
The entry point of every Java application is its main method. When you run an
application with the Java interpreter, you specify the name of the class that you want to
run. The interpreter invokes the main method defined within that class. The main method
controls the flow of the program, allocates whatever resources are needed, and runs any
other methods that provide the functionality for the application. The main Method tells
you more.
The other components of a Java application are the supporting objects, classes, methods,
and Java language statements that you write to implement the application. Using Classes
and Objects introduces you to these components.
/* text */
The compiler ignores everything from /* to */.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler
ignores this kind of comment, just like it ignores comments that use /* and */.
The JDK javadoc tool uses doc comments when preparing automatically
generated documentation. For more information on javadoc, see the Java tool
documentation .
// text
The compiler ignores everything from // to the end of the line.
Defining a Class
The first bold line in the following listing begins a class definition block.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
Julia Child's recipe for rack of lamb is a real-world example of a class. Her rendition of
the rack of lamb is one instance of the recipe, and mine is quite another. (While both
racks of lamb may "look and feel" the same, I imagine that they "smell and taste"
different.)
A more traditional example from the world of programming is a class that represents a
rectangle. The class would contain variables for the origin of the rectangle, its width, and
its height. The class might also contain a method that calculates the area of the rectangle.
An instance of the rectangle class would contain the information for a specific rectangle,
such as the dimensions of the floor of your office, or the dimensions of this page.
class name {
. . .
}
The keyword class begins the class definition for a class named name. The variables and
methods of the class are embraced by the curly brackets that begin and end the class
definition block. The "Hello World" application has no variables and has a single method
named main.
Every Java application must contain a main method whose signature looks like this:
• public indicates that the main method can be called by any object. Controlling
Access to Members of a Class covers the ins and outs of the access modifiers
supported by the Java language.
• static indicates that the main method is a class method. Understanding Instance
and Class Members talks about class methods and variables.
• void indicates that the main method doesn't return any value.
The main method in the Java language is similar to the main function in C and C++.
When the Java interpreter executes an application (by being invoked upon the
application's controlling class), it starts by calling the class's main method. The main
method then calls all the other methods required to run your application.
If you try to invoke the Java interpreter on a class that does not have a main method, the
interpreter refuses to run your program and displays an error message similar to this:
As you can see from the following code snippet, the main method accepts a single
argument: an array of elements of type String.
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to
your application. Each String in the array is called a command-line argument. Command-
line arguments let users affect the operation of the application without recompiling it. For
example, a sorting program might allow the user to specify that the data be sorted in
descending order with this command-line argument:
-descending
The "Hello World" application ignores its command-line arguments, so there isn't much
more to discuss here. However, you can get more information about command-line
arguments, including the framework for a command-line parser that you can modify for
your specific needs, in the Setting Program Attributes lesson.
Note to C and C++ Programmers: The number and type of arguments passed to the
main method in the Java runtime environment differ from the number and type of
arguments passed to C and C++'s main function. For further information refer to
Command-Line Arguments in the Setting Program Attributes lesson.
The "Hello World" application is about the simplest Java program you can write that
actually does something. Because it is such a simple program, it doesn't need to define
any classes except for HelloWorldApp. However, most programs that you write will be
more complex and require you to write other classes and supporting Java code.
The "Hello World" application does use another class--the System class--that is part of
the API (application programming interface) provided with the Java environment. The
System class provides system-independent access to system-dependent functionality. For
information about the System class, see Accessing System Resources .
The bold code in the following listing illustrates the use of a class variable of the System
class, and of an instance method.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
To refer to class variables and methods, you join the class name and the name of the class
method or class variable together with a period (".").
Methods and variables that are not class methods or class variables are known as instance
methods and instance variables. To refer to instance methods and variables, you must
reference the methods and variables from an object.
When the System class is loaded into the application, it instantiates PrintStream and
assigns the new PrintStream object to the out class variable. Now that you have an
instance of a class, you can call one of its instance methods:
System.out.println("Hello World!");
As you can see, you refer to instance methods and variables similarly to the way you
refer to class methods and variables. You join an object reference (out) and the name of
the instance method or variable (println) together with a period (".").
The Java compiler allows you to cascade references to class and instance methods and
variables together, resulting in constructs like the one that appears in the sample program:
System.out.println("Hello World!");
This line of code displays "Hello World!" to the application's standard output stream.
Summary
A class method or class variable is associated with a particular class. The runtime system
allocates a class variable once per class, no matter how many instances exist of that class.
You access class variables and methods through the class.
An instance method or instance variable is associated with a particular object (an instance
of a class). Every time you create an object, the new object gets a copy of every instance
variable defined in its class. You access instance variables and methods through objects.
import java.applet.Applet;
import java.awt.Graphics;
The code above starts off with two import statements. By importing classes or packages,
a class can more easily refer to classes in other packages. In the Java language, packages
are used to group classes, similar to the way libraries are used to group C functions.
Importing Classes and Packages gives you more information about packages and the
import statement.
Every applet must define a subclass of the Applet class. In the "Hello World" applet, this
subclass is called HelloWorld. Applets inherit a great deal of functionality from the
Applet class, ranging from communication with the browser to the ability to present a
graphical user interface (GUI). Defining an Applet Subclass tells you how.
The HelloWorld applet implements just one method, the paint method. Every applet
must implement at least one of the following methods: init, start, or paint. Unlike
Java applications, applets do not need to implement a main method. Implementing
Applet Methods talks about the paint method, how the "Hello World" applet
implements it, and the other methods applets commonly implement.
Running an Applet
Applets are meant to be included in HTML pages. Using the <APPLET> tag, you specify
(at a minimum) the location of the Applet subclass and the dimensions of the applet's
onscreen display area. When a Java-capable browser encounters an <APPLET> tag, it
reserves onscreen space for the applet, loads the Applet subclass onto the computer the
browser is executing on, and creates an instance of the Applet subclass. Running an
Applet gives more details.
If you removed the first two lines, the applet could still compile and run, but only if you
changed the rest of the code like this:
You might have noticed that the A Closer Look at HelloWorld example from the
previous lesson uses the System class without any prefix, and yet does not import the
System class. The reason is that the System class is part of the java.lang package, and
everything in the java.lang package is automatically imported into every Java program.
Besides importing individual classes, you can also import entire packages. Here's an
example:
import java.applet.*;
import java.awt.*;
The extends keyword indicates that HelloWorld is a subclass of the class whose name
follows: Applet. If the term subclass means nothing to you, you'll learn about it soon in
Object-Oriented Programming Concepts .
From the Applet class, applets inherit a great deal of functionality. Perhaps most
important is the ability to respond to browser requests. For example, when a Java-capable
browser loads a page containing an applet, the browser sends a request to the applet,
telling the applet to initialize itself and start executing. You'll learn more about what the
Applet class provides in the Overview of Applets lesson.
An applet isn't restricted to defining just one class. Besides the necessary Applet
subclass, an applet can define additional custom classes. When the applet attempts to use
a class, the application that's executing the applet first looks on the local host for the
class. If the class isn't available locally, it's loaded from the location that the Applet
subclass originated from.
Every applet must implement one or more of the init, start, and paint methods. You'll
learn about these methods in the Overview of Applets lesson.
Besides the init, start, and paint methods, applets can implement two more methods
that the browser calls when a major event occurs (such as leaving the applet's page): stop
and destroy. Applets can implement any number of other methods, as well.
Returning to the above code snippet, the Graphics object passed into the paint method
represents the applet's onscreen drawing context. The first argument to the Graphics
drawString method is the string to draw onscreen. The second and third arguments are
the (x,y) position of the lower left corner of the text onscreen. This applet draws the
string "Hello world!" starting at location (50,25). The applet's coordinate system starts at
(0,0), which is at the upper left corner of the applet's display area. You'll learn all about
drawing to the screen in the Creating a GUI with JFC/Swing trail
Running an Applet
The bold lines of the following listing comprise the <APPLET> tag that includes the
"Hello World" applet in an HTML page.
<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>
The above <APPLET> tag specifies that the browser should load the class whose compiled
code is in the file named HelloWorld.class. The browser looks for this file in the same
directory as the HTML document that contains the tag.
When the browser finds the class file, it loads it over the network, if necessary, onto the
computer the browser is running on. The browser then creates an instance of the class. If
you include an applet twice in one page, the browser loads the class file once and creates
two instances of the class.
The WIDTH and HEIGHT attributes are like the same attributes in an <IMG> tag: They
specify the size in pixels of the applet's display area. Most browsers do not let the applet
resize itself to be larger or smaller than this display area. For example, every bit of
drawing that the "Hello World" applet does in its paint method occurs within the
150x25-pixel display area that the above <APPLET> tag reserves for it.
For more information on the <APPLET> tag, see Using the APPLET Tag .
Lesson: Solving Common Compiler and Interpreter
Problems
If you're having trouble compiling your Java source code or running your application,
this section might be able to help you. If nothing in this section helps, please refer to the
documentation for the compiler or interpreter you're using.
Compiler Problems
On UNIX systems, you may see the following error message if your path isn't set
properly:
Syntax Errors
If you mistype part of a program, the compiler may issue a syntax error. The message
usually displays the type of the error, the line number where the error was detected, the
code on that line, and the position of the error within the code. Here's an error caused by
omitting a semicolon (;) at the end of a statement:
Semantic Errors
In addition to verifying that your program is syntactically correct, the compiler checks for
other basic correctness. For example, the compiler warns you each time you use a
variable that has not been initialized:
Interpreter Problems
A common error of beginner Java programmers using the UNIX or Windows 95/NT JDK
is to try to interpret the .class file created by the compiler. For example, if you try to
interpret the file HelloWorldApp.class rather than the class HelloWorldApp, the
interpreter displays this error message:
The Java interpreter requires that the class you execute with it have a method named
main, because the interpreter must have somewhere to begin execution of your Java
application. The main Method discusses the main method in detail.
If you try to run a class with the Java interpreter that does not have a main method, the
interpreter prints this error message:
Applet Problems
See Solving Common Applet Problems if you have trouble getting your applet to run.
Question 1: When you compile a program written in the Java programming language, the
compiler converts the human-readable source file into platform-independent code that a
Java Virtual Machine can understand. What is this platform-independent code called?
a. /** comment */
b. /* comment */
c. /* comment
d. // comment
Question 3: In The Java Tutorial, what is the URL of the page that describes Khwarazm?
(Hint: You can find the answer by going to the home page and clicking on the link to the
Search page where you can perform a search.)
a. What is the highest version number of the Java 2 SDK, Standard Edition, that is
available for download (early-access releases included)? (Hint: You can find the answer
at http://java.sun.com/j2se/.)
b. What is the highest version number for an SDK that you can download and use in
shipping products (that is, not an early-access release)?
c. What is the lowest version number for an SDK that you can download? (Note that
"SDK" used to be called "JDK.")
Question 6: What is the first thing you should check if the interpreter returns the error:
Exception in thread "main" java.lang.NoClassDefFoundError:
HelloWorldApp.java.
Exercises
Exercise 2: Download this file: Useless.java Compile and run this program. What is
the output?
Exercise 4: Change the height of the HelloWorld applet from 25 to 50. Describe what the
modified applet looks like.
• FirstClass.java
• SecondClass.java
Compile the files, and then run the resulting program. What is the output? If you have
trouble compiling the files but have successfully compiled before, try unsetting the
CLASSPATH environment variable, and then compile again.
Question 1: When you compile a program written in the Java programming language, the
compiler converts the human-readable source file into platform-independent code that a
Java Virtual Machine can understand. What is this platform-independent code called?
Answer 1: Bytecode.
Question 2: Which of the following is not a valid comment:
a. /** comment */
b. /* comment */
c. /* comment
d. // comment
Question 3: In The Java Tutorial, what is the URL of the page that describes Khwarazm?
(Hint: You can find the answer by going to the home page and clicking on the link to the
Search page where you can perform a search.)
Answer 3: http://java.sun.com/docs/books/tutorial/information/FAQ.html#knm
Question 4: Answer the following questions: a. What is the highest version number of the
Java 2 SDK, Standard Edition, that is available for download (early-access releases
included)? (Hint: You can find the answer at http://java.sun.com/j2se/.)
Answer 4a: Answer on 11/23/00: Java 2 SDK, Standard Edition, version 1.3.0.
TM
b. What is the highest version number for an SDK that you can download and use in
shipping products (that is, not an early-access release)?
Answer 4b: Answer on 11/23/00: Java 2 SDK, Standard Edition, version 1.3.0.
TM
c. What is the lowest version number for an SDK that you can download? (Note that
"SDK" used to be called "JDK.")
Answer 4c: Answer on 11/23/00: JDK 1.0.2 from http://java.sun.com/products/jdk/1.0.2/
a. Which bug has the highest number of votes at the Java Developer Connection? Give
the bug number, description, and number of votes. (Hint: Look for the answer at
http://developer.java.sun.com/developer/bugParade/.)
Answer 5a: Answer on 11/23/00: bug number #4204845; Remote use of double buffering
on JDK 1.2 is very slow; 365 votes.
Answer 6: Check your classpath. The interpreter cannot find your class.
Exercises
Exercise 2: Get the following file from the online Tutorial: Useless.java Compile and
run this program. What is the output?
Answer 2: This program prints out your default locale; for example,
en_US
Answer 3: Here's the error you get when you try to compile the program:
To fix this mistake, you need to close the quotation marks around the string. Here is the
correct line of code:
Exercise 4: Change the height of the HelloWorld applet from 25 to 50. Describe what the
modified applet looks like.
Answer 4: To answer this question correctly, make sure you modify the applet's height
HTML file -- not the .java file. Here is a snapshot of the resulting applet:
• FirstClass.java
• SecondClass.java
Compile the files, and then run the resulting program. What is the output? If you have
trouble compiling the files but have successfully compiled before, try unsetting the
CLASSPATH environment variable, and then compile again.
Answer 5: The key is to compile and run the SecondClass. FirstClass does not have a
main method, so it cannot run independently.