In this section, you write an applet, learn how to incorporate it into an HTML document, run it within your browser and also by using the appletviewerutility, which is built into the JDK
Trang 1your procedure are Comments also help when you go back and add new func-tionality to your code because you will be less likely to be confused by what you had previously done There are two basic types of comments in Java—single-line comments and multi-line comments If you just want to make a note about a par-ticular line of code, you usually precede that line of code with a single-line com-ment as shown here:
//The following line of code prints a message using standard output System.out.println("Hello, World!");
Single-line comments start with double slashes // This tells the compiler to dis-regard the following line of code After the double slashes, you can type anything you want to on that single line and the compiler will ignore it
Single line comments are also commonly used to temporarily disable a line of code during the debugging process Simply add the double slashes at the begin-ning of the line of code to make the compiler skip the line You typically do this if you want to test a modified version of the commented line or if you need to see how the program runs without executing that particular statement This way, you don’t have to delete it and you can replace the statement simply by removing the double slashes.
Sometimes you might want to write a comment that spans more than one line
of code You can precede each line with double slashes if you choose to, but Java allows you to accomplish this more easily Simply start your comment with a slash followed by an asterisk: /* You can type anything you want to after this, including carriage returns To end this comment, all you need to do is type */ /* I just started a comment
I can type whatever I want to now and the compiler will ignore it.
So let It be written
So let It be done I'm sent here by the chosen one
so let It be written
so let It be done
to kill the first born pharaoh son I'm creeping death
from Metallica's song, Creeping Death
I guess I'll end this comment now */
Everything in between the start and end of this comment is considered free text This means you can type anything you want to within them If you take another look at the HelloWorld source code, you will notice that I used a multi-line com-ment I typed the name of the HelloWorld program and then followed with sev-eral more lines I preceded every line with an asterisk You don’t have to do this
I only did it to make the comments stand out more Feel free to develop your own style of commenting your code, but keep in mind that you or someone else
T R I C K 18
J a
s o
l ut
n e
Trang 2might need to refer to the source code, so try to make your comments easy to understand
There is actually another form of multi-line commenting used in Java It has the added capability to be converted into HTML documentation using the javadoc utility included with the JDK.
The main() Method
When running a Java application, the main()method is the first thing the inter-preter looks to It acts as a starting point for your program and continues to drive
it until it completes Every Java application requires a main()method or it will not run In this section, I point out what you should understand about it because you’ll be using it often In fact, you use it in every application you write
The main() method always looks just like it did when you programmed the
HelloWorldapplication
public static void main(string args[]) { Let’s take a closer look at the parts of the main()method:
• The publicand statickeywords are used in object-oriented program-ming Simplified, publicmakes this method accessible from other classes and staticensures that there is only one reference to this method used
by every instance of this program (class) Static methods are also referred
to as class methods, because they refer to the class and not specific instances of the class This is a difficult concept to understand at this point You can simply gloss over it for now
• The voidkeyword means that this method does not return any value when it is completed
• mainis the name of the method, it accepts a parameter—String args[] Specifically, it is an array (list) of command-line arguments As is the case with all methods, the parameters must always appear within the paren-theses that follow the method name
• Within the curly braces of the main()method, you list all the operations you want your application to perform I stated earlier that every Java appli-cation requires a main()method; however, it is possible to write a Java source code file without defining a main()method It will not be consid-ered an application, though, and it won’t run if you use the java com-mand on it Now your head might be spinning at this point Don’t let all this make you forget what I stated earlier The main()method is simply the driver for your application
H I N T
19
Trang 3Writing Your First Applet
Applets differ from stand-alone applications in that they must be run within a Java-enabled browser and they don’t require a main() method In this section, you write an applet, learn how to incorporate it into an HTML document, run it within your browser and also by using the appletviewerutility, which is built into the JDK The appletviewerutility allows you to run applets from the com-mand prompt, outside of your browser Applets are covered in greater detail in Chapter 8, “Writing Applets.” At this point, your goals are to understand what an applet is, to learn how to create a simple one, and to understand how an applet differs from an application
Back to the HelloWeb Applet!
Remember the project introduced at the beginning of this chapter? In this sec-tion, you actually learn to create the HelloWebapplet This applet performs a task similar to that of the HelloWorld application, but it runs within a Web browser instead of as a stand-alone application Applets add a great deal of life to Web doc-uments If you include an applet in a Web document and publish it on the Inter-net, anyone can browse to it and run your program without having to explicitly download it In the real world, you can play Java games online The source code, although only one statement longer than the HelloWorld application, is a bit more complex Now, you will create this applet
/*
* HelloWeb
* A very basic Applet
*/
import java.awt.Graphics;
public class HelloWeb extends java.applet.Applet { public void paint(Graphics g) {
g.drawString("Hello, World Wide Web!", 10, 50);
} } Copy or type this source code into your text editor and name the file Hello-Web.java Even though this is an applet, you compile it exactly the same way as you do applications Just use the javaccommand After it’s compiled, your applet
is still not ready to run Figure 1.7 shows what will happen if you try to run this
as an application, further emphasizing the fact that all applications must define
a main()method
20
J a
s o
l ut
n e
Trang 4Writing the HTML
In order to run the applet, you need to write an HTML document and include the applet within it You don’t need to know much about HTML for the purposes of this book You write only the bare essentials in the HTML document and include the applet This is the listing for the HTML document:
<html>
<head>
<title>HelloWeb Applet</title>
</head>
<body>
<h1 align=center>HelloWeb Applet</h1>
<center>
<applet name="HelloWeb" code="HelloWeb.class"
width=250 height=100></applet>
</center>
</body>
</html>
Copy or type this HTML code into your text editor and save it as helloweb.htmlin the same directory as your applet The name is not all that important but the html extension is
Running the Applet
After you have created the HTML file, you are ready to run your applet You can
do this in one of two ways First, you can use the appletviewertool by typing the following at the command prompt:
appletviewer helloweb.html Figure 1.8 shows what the appletviewer window looks like while running the HelloWeb applet
21
FIGURE 1.7
There is no main() method,
so it cannot be run
as an application.
Trang 5J a
s o
l ut
n e
Next you can double-click your helloweb.html icon to run the applet in your browser
Congratulations! You’ve just written and run your first Java applet If your applet
is running fine using appletviewer, but you can’t get it to run inside your browser, you should make sure that you have the latest Java plug-in
I will quickly explain the new syntax that appears in this applet’s source code First, there is the importstatement:
import java.awt.Graphics;
This code imports the Graphicsclass By importing classes, you tell the JRE where
to look for the class definition so you can use it in your code Your applet uses the
Graphicsclass, so you must import it Your applet also uses the extendskeyword:
public class HelloWeb extends java.applet.Applet {
You can see that it is part of your class definition statement This is what actually
makes your program an applet Extending a class, such as the Appletclass, is a way
of reusing the functionality of another class that has already been defined and gives you the capability to extend its characteristics and capabilities When one
class extends another, it is referred to as a subclass and the class it extends is called its super class This is one of the benefits of object-oriented programming.
One last thing to understand is the way you instructed your applet to print a message
Public void paint(Graphics g) { g.drawString("Hello, World, Wide, Web!", 10, 50);
}
FIGURE 1.8
Using the appletviewer to view your applet.
Trang 6The pre-existing Appletclass already defines a paint()method Here you over-ride it to do what you want it to do You tell the Graphicsclass to draw the string
"Hello, World Wide Web!"inside of your applet with g.drawString() The num-bers that follow your string in your parameter list are the x, y coordinates describing where to paint the string You’ll learn more about this in Chapter 8
Summary
You accomplished a lot in this chapter You learned that Java is a platform-independent, object-oriented programming language that you can use to write applications and applets You installed the Software Development Kit and set it
up, giving your system the capability to compile and run Java programs You wrote your first application, learned how to use the javaccommand to compile
it and the javacommand to run it After you successfully ran the HelloWorld application, you looked back and examined your code You learned the basics of Java syntax You also wrote your first applet and learned the basic differences between applications and applets You learned how to include an applet within
an HTML document Finally, you learned how to run an applet by using the
appletviewerutility and also how to run it in your browser You are ready to take
23
I N THE R EAL W ORLD
In the real world, applications and applets typically do much more than simply print a message to the screen Programmers to tend to use the System.out.println() method while debugging code Although you didn’t use this in your first applet, it is possible to use standard output in applets Java-enabled Web browsers typically have a Java console, or window that displays these types of messages For example, if you’re using Internet Explorer, you can call up the Java console by selecting that option from the View menu.
Standard output is useful when debugging your code If you are having difficulty getting your program to run the way you intend it to run, you can print infor-mation about the program as it is running This way, you can see the state of the program at key locations in the code This will, more often than not, lead to the source of the problem when you see that some specific part of the program does not look the way it should look while it is running At this point, you will have to trace only the code that affects that part of the program.
Trang 7on some new challenges In the next chapter you learn about variables, data types, mathematical operations, and how to accept simple user input
24
J a
s o
l ut
n e
C H A L L E N G E S
1 Write a Java application that prints your first name to standard output.
2 Rewrite your Java application from challenge #1 to print your last name to standard output without deleting any lines by commenting out the line you don’t need and adding the one that you do.
3 Write a Java application that prints two separate lines to standard output
by repeating the System.out.println() statement using a different sentence.
4 Write an applet that displays your name and run it with both the appletviewer utility and with your browser.
Trang 8In this chapter, you learn how to use variables, data types,
and standard input/output to create an interactive appli-cation You start by learning what variables are and what they are used for Then you learn what the primitive data types are and how they are assigned to variables After you understand variables, you learn how to work with numbers and use mathe-matical operations After that you learn about strings and how to accept simple user input Finally, you put all this knowledge together and build an application that uses standard output, accepts user input, and works with strings and numbers In this chapter, you will
•Learn to use data types
•Declare and name variables
•Work with numbers
•Get simple user input
•Parse strings to numbers and other String class operations
•Accept command-line arguments
Variables, Data
Types, and Simple I/O
2
C H A P T E R
Trang 9The Project: the NameGame Application
You’ll use the concepts introduced in this chapter to create this interactive appli-cation It is interactive because it allows users to enter input It then processes this input and issues output Figure 2.1 shows how this application appears when you run it
26
J a
s o
l ut
n e
In this simple game, the program prompts the user for a first name Next, the program responds to the user and asks a last name The program then proceeds
to manipulate the name and show off to the user In fact, it demonstrates, how-ever basically, most of the concepts behind what an application should be able to
do It provides a user interface, which prompts the user for some information, allows the user to enter this information, processes the information, and outputs the information in a new form for the user to ingest These basic functions are present in any useful application and are the keys to learning any programming language
Variables and Data Types
In this section you learn what variables and data types are and how Java uses
them Variables are basically containers that hold specific types of data Oddly
enough, these specific types of data, such as integers, floating-point numbers,
and bytes, are called data types The data contained by the variable can vary (that’s
why it’s called a variable), but the data type cannot change Variables are used to temporarily store pieces of data that the program makes use of Think of a folder
A folder holds documents A person can use the folder by reading the information
FIGURE 2.1
This shows two successive runs of the NameGame
application.
Trang 10that it holds This person can also take the document out and put a new one in it that can be used later In this analogy, the folder acts as the variable, documents act as the data type, and the information in the documents acts as the data
Learning Primitive Data Types
A variable must have a data type A variable’s data type can be a reference data
type or a primitive data type Primitive data types are built into the system They
are not objects They are specific values that can easily be stored by a computer using a specific amount of memory If you declare a variable to be of a specific primitive data type, that variable will always hold a value that is of that data type For example, if you specify variable nto be an inttype, nwill always hold
an integer Reference data type variables—used for class, interface, and array ref-erences—don’t actually contain the object data Instead, they hold a reference to the data In other words, they tell the computer where to find the object’s data
in memory Unlike other languages, primitive data types in Java are system-inde-pendent because Java specifies their size and format There are eight primitive data types They are listed in Table 2.1
The four integer types (byte, short, int, and long) can be positive, negative, or zero The same is true for the two floating-point types (floatand double) The
chartype can hold one Unicode character (for example: a, b, c, A, B, C, 7, &, *, and
~) Unicode is a character set that provides a unique number for every character
The booleantype can hold only the values trueor false After you have declared
a variable to be of a certain type, it can only hold that specific type of data
27
i a
l e
float Single-precision floating point 32-bit double Double-precision floating point 64-bit
T A B L E 2 1 P R I M I T I V E D A T A T Y P E S