Unit 2. Introduction To Java
Unit 2. Introduction To Java
INTRODUCTION TO JAVA
Java began its life in 1990 as a new language called Oak. Sun Microsystems had
established a project group code-named green to develop new products and expand
Sun's markets. Oak was originally designed for a personal digital assistant called *7 that
The *7 was never marketed, and eventually Sun formed a company called FirstPerson
circumstances, the promise of interactive TV soon dried up, and Oak was left without a
market. However, about the time that FirstPerson and Oak were failing, the World Wide
Web was exploding. Soon companies such as Netscape began to make software that
would catapult the WWW into the Internet spotlight. Sun soon realized that Oak had
possibilities with the Web, and soon Oak was released to the Internet with a new name:
Java.
beginning to influence the direction of computing and the Internet. The Java
programming language is being released free on the Internet, and Sun is licensing the
full implementation of Java and its components to a variety of Internet software vendors
Java is a very new programming language and makes possible a very new
programming reality. As a commercial product, it is only a few years old, but few new
products have captured the attention of the information science, computer science,
software development, and programming worlds the way this new language has. One of
Java’s most attractive features is that it allows you to write a Java program on an Intel
computer and then run it on a Macintosh without doing anything special, and that truly is
In its syntax, Java is very much like another popular programming language: C++.
Unlike C++, however, Java features a number of "building blocks" for creating
Graphical User Interfaces (or GUIs, pronounced gooey), making GUIs very easy to
have a grasp of some important programming issues and some fairly complex data
structures, and if you are hoping to acquire that kind of skill, you will need to take other
Why Java
and iterative execution, simple and complex variables, and program planning. We will
also look at some aspects of the object-oriented programming paradigm, and while
Smalltalk—we will work only with Java. First of all, Smalltalk is not used by as many
programmers as C++ or Java are, and we have chosen Java over C++ and other
Java is portable—that is, as mentioned above, a Java program written for one
type of machine (say a PC) can easily work on another machine (say a
Macintosh)
Java applets can run inside a browser. (In this course, we will work primarily with
applets.)
Java allows us to write two different types of programs: applications and applets.
Java applications are computer programs that run like almost any other
computer program. They can be very complex, like the notepad application that
many of you used to build your HTML pages, or they can be very simple. Java
computer without the aid of another application, such as a Web browser. Word
Java applets are programs that are executed from within a Web browser. Put
into a Web page, a Java applet can allow users to interact with the page in
interesting ways. For example, if your family owned a carpet store, you might
want to create a simple calculator that would allow users to enter the size of a
room and type of carpet they want, and your carpet calculator would tell them the
number of square yards of carpet they need and the approximate cost of the
carpet and padding. While your Web page could furnish this information in, say, a
table or chart, potential customers might prefer instead to use a calculator applet,
Java allows us to write two different types of programs: applications and applets.
Java applications are computer programs that run like almost any other
computer program. They can be very complex, like the notepad application that
many of you used to build your HTML pages, or they can be very simple. Java
computer without the aid of another application, such as a Web browser. Word
Java applets are programs that are executed from within a Web browser. Put
into a Web page, a Java applet can allow users to interact with the page in
interesting ways. For example, if your family owned a carpet store, you might
want to create a simple calculator that would allow users to enter the size of a
room and type of carpet they want, and your carpet calculator would tell them the
number of square yards of carpet they need and the approximate cost of the
carpet and padding. While your Web page could furnish this information in, say, a
table or chart, potential customers might prefer instead to use a calculator applet,
Below are two Java examples: one is an applet and the other is an application.
NAME: NAME:
SECTION: SECTION:
ASSIGNMENT: ASSIGNMENT:
*/ */
import java.applet.Applet; {
public class Hello extends Applet public static void main(String args[])
{ {
{ }
g.drawString("Welcome to JAVA",30, }
30);
}
There are a couple of major differences between the application and applet shown
above:
While the applet executes g.drawString and g.drawRect, the application executes
browser. For that reason, it can draw graphical elements in the browser (such as lines,
circles, rectangles, strings, etc.). In this example, it draws the string Welcome to Java
and a rectangle around the string. However, the Java application does not run in a
graphical environment. It has to be run in a DOS window (also called a "console
window") on a PC. The System.out.println instructs the computer to print the text inside the
parentheses to the system's output device. Thus, the message "Welcome to Java!" is
printed to the system's output device--in this case, the DOS window (console window).
There are a couple of import statements in the applet, while there are none in the
program. In this case, the import statements make available the code that is needed to
draw a string in a browser. In contrast, the simple Java application draws no graphical
The Java application includes a method called main( ). The main( ) method is
mandatory for all Java applications. When you run the Java application, the machine
looks for its main( ) method, and if it cannot find it, the machine will "complain." Applets
does not need to include a main( ) method—the functionality normally provided by the
The table below breaks our example applet into parts and explains its important
concepts.
comment.
import java.awt.*; These import statements make code from the packages
public class Hello extends Everything in Java is written as a class. In this example,
Applet the class is named Hello. This line initiates the definition of
class Hello.
public void This line initiates the definition of a method called paint( ).
paint(Graphics g)
paint( ) method.
to JAVA",30, 30); Graphics class. The Graphics class (and, therefore, the
libraries.
g.drawRect(20, 5, 140, This calls the drawRect( ) method of the Graphics class.
50);
} This close brace marks the end of the body and definition
file. A typical Java source file (a file with the extension .java) contains a definition of one
class, and the example applet above contains the definition of class named Hello. Java
requires that the name of the class as defined in a source file be the base part of the
source file's filename (that is, part of the name before the extension). In the above
applet, the class name is Hello; therefore, the source file's filename must be Hello.java.
A class definition may contain several method definitions and may (but not
necessarily) be preceded by one or more import statements that give the applet access
to the code in external libraries. The class definition in the above example contains a
definition of a method named paint( ) and is preceded by two import statements. In the
following sections, we will analyze these chief components of a Java program (import
Import Statements
Java import statements "import" (and, hence, give our applets access to) Java code
libraries that contain code already written to do tasks we might want our applets to do.
Of course, the capacity to import code libraries is not unique to Java: many serious
programming languages have that capacity. Code libraries are simply collections of
previously written classes, methods, and functions that are ready to be executed and
can be used in other programs. The classes, methods, and functions that libraries
contain perform functions that are needed by a variety of programs. Collecting these
elements into libraries provides developers with a set of "building blocks" that are ready
to use.
a set of words delimited by dots. To use the methods of a pre-built class in our program
we need to import this class using the import statement. We could choose to import a
particular class or a whole package with all its classes. Also, all import statements are
Now, let's analyze the two import statements in the applet above.
import java.applet.Applet;
This statement imports the class Applet that is contained in the package java.applet.
The Applet class contains the code that allows us to run our program as an applet in a
Web browser.
import java.awt.*;
This statement imports all classes in the package java.awt (by the way, awt stands for
Abstract Windowing Toolkit). This package contains programs that can build the window
and do the type of drawings we need to do. The asterisk ( * ) that follows the
statement's last period ( . ) is a "wildcard character" and tells Java to import all classes
in the package.
It turns out that the language Java "knows" very little. On its own, it can do a little
arithmetic, allocate memory for data, store data in the allocated memory, make simple
true-or-false tests, and repeat things. That is not much—but that is all a programming
language really needs to be able to do. Whenever we write a program, we need to
decide which parts of the program we should write from scratch ourselves and which
parts can make use of code written by others and made available in libraries. In general,
we want to make as much use of the code available in libraries as possible. This is
someone else or out of bricks we make ourselves from scratch. Also, be aware that the
library structure for Java is very large and is still evolving, and in this course, we will use
only a few pieces of a few libraries. Therefore, if you want to be a Java programmer,
you will need to learn a lot more about the various libraries than we will cover in this
course.
the structure and behavior of a category of objects. The structure specifies the data that
is contained in the category of objects, while the behavior specifies the actions that can
be performed by the category of objects. The behavior collectively refers to the set of
An object is an instance of a class. An object is a self-contained entity that has both the
data and the means to act on the data. The example applet and application above each
have one method only (paint( ) in the applet and main( ) in the application), and there
are no structures or data in either of these—at least no data that we can see at the
present.
Now it is time to look at some of the rules for writing Java classes. There is an is-an-
instance-of relationship between an object and its class. As a short form, an is-an-
instance-of relationship is also called an is-a relationship when there is no possibility of
as in English the term Elephant refers to a category of things in the world: elephants.
When we talk about Elephant, we talk in generalities and not about any one elephant in
we will uppercase the first letter of the class's name, and when we refer to an object, we
In the real world, elephants have attributes such as height, weight, etc. They also do
things such as walk, drink, etc. Similarly, in programming you can define a set of
attributes that a class can have and a set of activities (called methods) that it can
perform.
Class Definition
Classes are the major organizational block for Java programs. A Java program consists
of one or more classes. Within this course, each class is defined in a separate source
file.
The definition of a class specifies what the class has and what it can do. Within a class,
we can import and use other classes. If you look at the first line of the definition of the
public
We can specify a Java class as public, private, or protected using the keywords public,
private, and protected; however, for now we will work only with classes that
designated public. By specifying a class as public, we are saying that the class is
available to be accessed by any code that can access the package in which the class is
declared.
class
Hello
Hello is the name of the class. As we mentioned earlier, class names by convention
should begin with a capital letter—and, as you see, this example follows that
convention. Note: for reasons we won't go into now, you must not change this name.
We will look at these reasons later and show you what you must do if you want to
change this name—but for now, please realize that if you change this name, your
extends Applet
Read the phrase extends Applet to mean that the class being defined "descends from,"
"inherits from," or "is a child of" the class Applet. That is, our class Hello is a child or a
subclass of a class named Applet. In turn, class Applet is called the superclass for
the class Hello. This means that Hello can do anything that the parent class Applet can
do. The parent in this case "knows" how to execute itself within a Web page. Since we
have declared our class Hello as a child of Applet, we don’t have to write all of the
needed Java instructions required to run the program in a Web page. Class Hello
inherited this ability from its parent class Applet. In Java, the mechanism by which a
child class acquires functionality defined in a parent class is called inheritance. There
are other methods in class Applet that class Hello can inherit and use. Some of these
methods are init( ), start( ), stop( ), and update( ). Notice that our class Hello has its
own paint( ) method. This is fine—Java will use our definition of paint and ignore the
definition of paint( ) in the class Applet. If we leave out a definition of a method, Java
This class body is bounded by or delimited by a pair of braces. The last character of the
class must always be a closing brace ( } ). All of the Java code found within these brace
All of the structure (data) and behavior (methods) of a class have to be defined in the
body of the class. That said, as you may have noticed, there is no data stored in the
Hello example class. However, there will be data in some of our future programs, but
In Java, methods are groups of instructions that have names. Methods enable our
programs to do things. Note that other languages use other terms to refer to what in
In order to have the computer execute the instructions in the body of one of our
methods, the method must be invoked or called. We have a very interesting situation
when we write applets: some of our methods are called for us automatically when we
run the applet—and others are not. For example, the paint( ) method is called
Inside the body of class Hello, the first thing we see is a definition of a method named
paint( ). The method definition consists of the method's name, followed by a set of
piece of data that is provided to the method when that method is called. After the
The keyword public tells Java that this method can be used by other classes outside of
the class Hello. Remember that somewhere, somehow, our paint( ) method is called for
otherwise our applet will not be able to run. For now, all of our methods will be defined
as public.
The keyword void means that a method does not return a value. Methods can do three
things:
They can compute and return values, such as an average of a list of numbers.
For now we will use only void methods—these are methods that do things but do not
return values. Following the keyword void is the method name: paint( ).
(Graphics g)
Following the method name in our example is a list of parameters enclosed in a pair of
parentheses. This is the list of resources the method needs to do its job. Some
methods, however, need no parameters at all, and, therefore, feature a set of empty
parentheses—a method definition must have the parentheses, even if the parentheses
are empty. However, in our example, the parentheses contain one parameter: g.
The "Graphics" inside the parentheses is the name of a class defined in one of the
imported libraries (the fact that it is capitalizes clues you in to the fact that it is a class,
since the convention is to capitalize class names). By writing "Graphics g", we are
indicating that g is an object of the Graphics class. Note here that since the parameter
we are specifying is to be an object of the Graphics class, we must specify the class
name "Graphics" exactly as it is shown above, but the object name can be anything we
choose. Here we give it the name g, but we just as easily could have named it gr or
myGraphicsObject or any other meaningful name. Any object of the class Graphics
"knows" how to draw things in an applet window, how to change color, and how to print
words. By placing this parameter in the parentheses, the method paint( ) is being given
a resource—an object named g of the Graphics class—which knows how to draw. The
paint( ) method can now use this object to draw things in the applet window. It is very
similar to me asking you to write something for me on a piece of paper and loaning you
my pen to do it. The loaning of the pen is very similar to putting "Graphics g" in the
parameter list.
The body of the method is delimited by a pair of braces, just as the body of the class is.
Everything within this set of braces is part of the paint( ) method. You can define
methods within classes, but you cannot define classes within methods, and you cannot
Inside of the body of paint( ) there are two statements. The first statement draws a
The next statement given below draws a rectangle 140 pixels in length and 50 pixels
1. Write Java code that will constitute the applet. To write code, you will use
an editor. You will save the Java code in a source file ( .java file). Note that all
java source files should have a .java extension. Furthermore, the file in which you
put the source code for a class should have the same name as the name of the
class extended with .java. In the above example, the class Hello should be placed
2. Compile the Java source code in the .java file into bytecode using a Java
compiler such as javac that is a part of Java Development Kit (JDK). The result of
compilation will be a bytecode file. Note that all bytecode files will have the
extension .class. In our example, the bytecode file generated from the source file
3. Create a HTML file that embeds this bytecode file in a pair of APPLET tags that
specify
the size (that is, the width and height) of the area occupied by the applet in
4. Run the applet by opening the HTML file in a Web browser or an applet viewer—
a special "minimal" browser for running applets that is also included in Sun's JDK.
Note that the steps necessary to run a Java application are slightly different. Below is a
diagram of the process of compiling and running a Java application. After compiling
your application's source file with the javac compiler, you will get a .class file. This .class
contains the Java application. You will run this .class file using the JDK Java
interpreter called java. Web browsers and applet viewers can't run Java applications.
Pay particular attention to the following when creating an Applet:
Spelling.
The case of letters. Java treats "import" and "Import" as different words—if you
Matching sets of parentheses ( ) and braces { }. These are called delimiters and
The punctuation marks. In this program they include the period ( . ), semicolon ( ;
Source code is the program written in Java or other high-level programming language
by the programmer. Source code can be read by humans. Source code is stored in
source files. The Java program you saw in the previous page is the source code of the
Hello applet.
Compilation is the process of converting high-level source code into machine language
or another form that can be executed by the machine. While high-level source code can
extremely strenuous for humans to follow, while extremely easy for machines to
interpret.
Compiler is a computer program that performs compilation. In our course, you will most
likely be using a Java compiler named javac that is a part of the Java Development Kit
(JDK). There is more help on installing and using JDK in the appendix section on setting
the Java compiler javac to compile the source code file Hello.java with the command:
javac Hello.java
intermediate-level format that can be run by the Java Virtual Machine. Files that contain
bytecode have a .class extension. When you compile Hello.java using the Java compiler
javac, it produces the bytecode in a file called Hello.class in the same directory. This file
is written and named by the Java compiler, and its name is always the same as the
name of the class defined in your Java program with a .class extension appended. The
result of a successful compilation of your Java program is always at least one .class file.
computer. Bytecode has to be executed by the Java Virtual Machine, or JVM. Although
JVM has the term machine in it, the machine refers to a software implementation—that
is, an abstract machine. When your bytecode is run inside the JVM, the bytecode is
translated into real machine code that can be run by the physical machine. All Java
interpreters, Java-enabled browsers, and applet viewers have a JVM inside and can
execute bytecode. The JVM acts as an intermediary between the real computer and
representation and the JVM acting as an abstract machine, Java achieves portability
across computer platforms. That is, you can run your bytecode on a Sun computer or a
Macintosh computer, or any other computer that has a JVM implementation. Currently,
A Java applet is invoked (run or executed) from within a Web page. A call of an applet
has to be embedded inside some HTML document. Here is the simplest form of an
HTML document that will run our applet Hello. Convention dictates that you name this
file Hello.html, but that is just convention and not a Java rule (unlike the case with
Hello.java).
<HTML>
<BODY>
width = 200
height = 75>
</APPLET>
</BODY>
</HTML>
The APPLET tag in the HTML file "tells" the applet viewer or Web browser three pieces
of information:
code = "Hello.class"
width = 200
height = 75
The first list item literally says that the applet to be executed is called "Hello.class". As
you remember, javac created Hello.class from Hello.java when you compiled the
Hello.java program.
The second and third list items tell the browser or applet viewer how big the applet
window must be. When a Web browser or the applet viewer executes or runs your
applet, it builds a window 200 pixels wide and 75 pixels high and executes the bytecode
instructions in the file Hello.class. The unit of measure is pixel, which is short for picture
element. The graphics display for your computer is composed of thousands (or millions)
of these individual elements; thus the pixel is the smallest piece of visual information
that your monitor can display. It is about the size of a period ( . ), like the one at the end
of this sentence.
Running the applet is done by using a Web browser or the applet viewer provided by
Sun as a part of the JDK. An applet viewer is a special program that could run applets.
It could be considered a stripped-down Web browser that can't display HTML, but can
locate an applet inside a Web page and run it. Both the browser and the applet viewer
All browsers that are java enabled (that is, they include the JVM) can understand and
execute your bytecode. And most popular browsers such as the Internet Explorer and
Netscape Navigator are Java enabled. This is one of the reasons for the remarkable
popularity of Java. However, different browsers have slight variations in the way they
execute applets. We suggest that you use an applet viewer provided with your JDK as
The typical Java applet is made up of numerous components that include keywords,
Keywords are words that have a special meaning in the Java language. Keywords are
The applet listed earlier in this page contains the following keywords:
import - is used to make parts of a library available for use in the current
program.
public - means that other classes may use this class or method during their
execution.
extends - tells Java that the class named before the keyword extends is a
subclass of the class named after the keyword. (For example, the code " public
class Hello extends Applet" tells Java that Hello is a subclass of Applet.)
Identifiers
parameter name. For example, the class name Hello is an identifier. Similarly, the name
either case (a–z and A–Z), numbers (0–9), underscores ( _ ), or dollar signs ( $ ). No
other characters are allowed. No commas, hyphens, etc. Also, identifiers cannot start
with a number. Finally, keywords cannot be used as identifiers (for this reason keywords
Statements
Statements are the basic units of execution in a program. They tell Java to do
import java.applet.*;
import java.awt.*;
These statements result in some action being performed. Some of the actions
are invisible to the user of the applet. The user will never actually see the import
statements being executed because they are directives to the compiler. The g.drawString
statement will result in a visible action because the string Welcome to JAVA will be
displayed in the applet window. Statements have one thing in common—they end with a
The body of the method paint( ) in our example has two statements:
When you modify the Java program, you may encounter some errors when you compile
it. We will soon learn what those errors mean and how they can be fixed. Sometimes it's
In all disagreements with the compiler, the rule is simple: the compiler always wins. The
author typed in the Hello Java applet program and left out the semicolon at the end of
the second line shown below—the "_" is where the missing semicolon should be:
import java.awt.*_
Here's what was typed on the command line (it was supposed to compile a Java
program):
>javac Hello.java
semicolon.
import java.awt.* Here the compiler displays the line of
code where the error might be.
^ The compiler then places a caret ( ^ )
might be.
Hello.java:8: Superclass Applet of class A second error message—this one
might be.
2 errors This is the total number of errors
found.
Now, if a semicolon is put in line 6, where it belongs, both of these errors will disappear.
As indicated above, the basic message format gives the file name and then the number
of the line on which the error might be located. Just remember that the error message
represents the compiler's best guess at what is wrong. The best way to get introduced
frustrating, but that will pass. Once you have corrected all of the errors, you can run
Errors are a part of a programmer's life—we all make them. It turns out that writing a
program takes a much higher degree of perfection than most of us are used to
achieving, and the simplest error can keep our programs from running. And once our
programs run, we must continue evaluating and testing them to make sure they are
running correctly. Some programs are so complex that they defy complete testing for
correctness. Fortunately, you will not write such programs in this class, but some of the
When you wrote Web pages in the previous unit, you probably made two types of
errors:
syntax errors
execution errors
Syntax errors occurred when you used the wrong tag or left out a closing tag or a
closing angle bracket. A syntax error would cause angle brackets to be displayed in
your Web page when viewed in a browser. The fact that the Web page is displayed at
all is due to the fact that the browser ignores HTML syntax errors and displays the page
regardless.
You can think of syntax errors as errors in grammar. Just as grammatical errors in
programs. Humans are smart enough to infer the meaning of a sentence, even if the
sentence is ill formed. But, compilers are not that smart. They will complain, and you
Execution errors are also called "logical errors." For example, maybe you wanted
something displayed as bold or centered, and that something was instead displayed as
italic or left justified—that is an execution or logical error. The browser did what it was
told to do, and the syntax of the HTML was correct, but the result was not what you
wanted. There is a story about a king who intended to spare the life of a particular
prisoner, and one day when the king's jailer sent him a letter asking, "What do you want
to do with this prisoner, kill or spare him?", the king, being pressed with many other
matters, wrote back a terse reply. Unfortunately, although the king had intended with his
reply to order the prisoner's life spared, in his haste to write "Kill not, spare" he
misplaced the comma and wrote "Kill, not spare." Thus, the king's statement illustrates
what we have called a "logical error." The statement is grammatically correct, and the
jailer could, therefore, understand and obey it as an answer to his question; but it did
not accomplish what the king had intended, because the prisoner was killed. When you
write programs, you will most likely also run into such logical errors (though not as fatal).
You should test your programs to see if they do what you intended them to do. Again,
execution errors are not errors in grammar: if the king's grammarians had examined his
statement, they wouldn't have found an error. Similarly, a compiler (which is a type of
grammarian) will not usually complain about logical errors; logical errors usually
Both of these types of errors (syntax and logical) can also occur in a Java program.
However, Java is somewhat pickier about syntax. Your browser never refused to display
your Web page—it just ignored your syntax errors. In fact, a syntax error that causes a
very bad display in one browser may not cause a bad display on another browser; this
If you have a syntax error in a Java program, it will not compile—and Java will output a
list of cryptic error messages. Once you have decoded the error messages and fixed
the errors (more evaluation/testing, planning, and coding) you will have eliminated the
syntax errors. Then you must run the applet to see if it does what you intended it to do.
Four final thoughts about syntax errors:
1. The Java compiler will provide, at best, a guess of what the error is and where it
occurred. Sometimes it is correct and shows you where to fix the error.
Sometimes it will mark a place that contains no error. If you find no error visible,
check the code above the marked line. You may have made a mistake one, two,
2. If the Java compiler prints a long list of errors, you should consider only the first
one or two to be truly valid. It is possible that the first syntax error led the
compiler down a very wrong path to find other errors that are not really errors at
all. Fix the first one or two errors and recompile your program. You may find that
3. The opposite of item two can occur. You compile and get two errors. You fix
them, and the next compile generates twelve errors. What happened? Java
found the first two errors and for various reasons stopped compiling the program.
Java literally "did not see" the rest of the errors. Once you fixed the first two
errors and recompiled, Java was able to "see" the next set of errors. This leads
to one major piece of advice that will be important to you when you write your
first original program: compile frequently and fix the errors as you go. It is usually
not a good idea to write an entire program from the opening comment to the last
"}" and then start compiling it for the first time. Seeing a list of 354 errors can be
very depressing.
4. If you read an error message and it makes no sense, get help. If you read an
error message and understand it but cannot find the actual error, look again. If
you spend more than 2–3 minutes in this state, get outside help. Ask your
teacher, or, if it's allowed, ask another student to look at your code. Just staring
at code rarely helps you find errors. Get help—an outside pair of eyes can find
things at a glance that you, as the original author, might never see.
Documenting code is one important task for which software developers are responsible.
One element of documenting code correctly is including comments within the code.
Commenting code is very important because it makes the code easy to maintain thus
making the software's total cost of ownership less expensive than it is for code that is
not well commented. When code is well commented, it is less costly to maintain
because any developer who is maintaining it requires less time to understand the code’s
When you are writing comments, you should assume that the reader of the comments
will be a developer of average competence who knows nothing about the class’s
purpose or how the code functions. Well written comments should explain the purpose
of the class somewhere near the beginning of the class. Each method should have at
least one comment placed immediately before the method name explaining the purpose
of the method and how the method performs its function. Any complicated approach
that you used to accomplish the method’s function should be brought to the attention of
the reader in order to minimize the time required by the developer to understand how
two ways. One method that can be used to create a comment is to begin the line of
Or,
In the above examples, all text appearing after the “//” AND on the same line will be
short in length. Comments are not compiled when the class is compiled. Comments are
not considered to be java statements. If the comment wraps to a new line and that line
does not begin with a “//” symbol, the compiler will not treat it as a comment and a
compile error will be generated. Sometimes the comment is placed immediately before
the line(s) of code that it is intended to document, as shown in the first example above,
and sometimes the comment is placed on the same line as the line of code that it is
acceptable.
Sometimes, a comment that spans several lines is needed. In this situation, the
comment can be created by beginning the comment with a “/*” symbol and ending it
/*
This class accepts from the user a name to display and a color in which to display it.
Upon accepting the user's input, the value of the name is stored in a variable called
strName and the value of the color is stored in a variable called strColor. Then the paint
method is called to display the output.
*/
In the above example, all text between the ‘/*' symbol and the ‘*/' symbol is a comment.
java.applet
- Provides the classes necessary to create an applet and the classes an applet
java.awt
- Contains all of the classes for creating user interfaces and for painting graphics
and images.
java.awt.event
- Provides interfaces and classes for dealing with different types of events fired by
AWT components.
Applet class
Class Applet
java.lang.Object
+--java.awt.Component
+--java.awt.Container
+--java.awt.Panel
+--java.applet.Applet
Called by the browser or applet viewer to inform this applet that it has been loaded into
the system. It is always called before the first time that the start method is called.
A subclass of Applet should override this method if it has initialization to perform. For
example, an applet with threads would use the init method to create the threads and the
Called by the browser or applet viewer to inform this applet that it should start its
execution. It is called after the init method and each time the applet is revisited in a Web
page.
A subclass of Applet should override this method if it has any operation that it wants to
perform each time the Web page containing it is visited. For example, an applet with
animation might want to use the start method to resume animation, and the stop method
Called by the browser or applet viewer to inform this applet that it should stop its
execution. It is called when the Web page that contains this applet has been replaced
A subclass of Applet should override this method if it has any operation that it wants to
perform each time the Web page containing it is no longer visible. For example, an
applet with animation might want to use the start method to resume animation, and the
Called by the browser or applet viewer to inform this applet that it is being reclaimed
and that it should destroy any resources that it has allocated. The stop method will
A subclass of Applet should override this method if it has any operation that it wants to
perform before it is destroyed. For example, an applet with threads would use the init
method to create the threads and the destroy method to kill them.
Paints the container. This forwards the paint to any lightweight components that are
entirely clipped by the current clipping setting in g, paint() will not be forwarded to that
child.
Overrides:
Parameters:
Updates the container. This forwards the update to any lightweight components that are
entirely clipped by the current clipping setting in g, update() will not be forwarded to that
child.
Overrides:
Parameters:
possible
Defining Classes
{
Declaration of instance variable1;
Definition of method1
Definition of method2
Remember that Java ignores white space—such as blanks, tabs, empty lines, etc.—
between words in programs. Note that white space inside a string (anything inside a pair
Also note that anything in a line that comes after a pair of slashes ( // ) is a comment.
Comments are for the human reader, and the Java compiler will ignore them. Thus,
when the compiler sees a pair of slashes, it ignores the rest of the line. You can also
asterisk-slash ( */ ). Anything that falls between the comment delimiters /* and */ will be