In this chapter
At least since the first edition of Kernighan and Ritchie's The C Programming Language it's been customary to begin programming tutorials and classes with the "Hello World" program, a program that prints the words "Hello World!" on the display. Being heavily influenced by Kernighan and Ritchie and not one to defy tradition , this book begins similarly. Here's the Hello World program in its entirety:
Program 3-1:
class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
Hello World is very close to the simplest program imaginable. When you successfully compile and run it, it prints the words "Hello World!" on your display. Although it doesn't teach very much programming, it gives you a chance to learn the mechanics of typing and compiling code. The goal of this program is not to learn how to print words to the terminal. It's to learn how to type, save and compile a program. This is often a non-trivial procedure, and there are a lot of things that can go wrong even if your source code is correct.
If you completed the last chapter, you should already have downloaded and installed
a Java compiler and interpreter. You should also have looked at some applets written
by other people. Also, if you're using Unix or Windows, you should have configured
your PATH
environment variable so that the command line can find the Java compiler and other utilities.
To make sure you're set up correctly, bring up a command-line prompt and type
javac nofile.java
If your computer responds with
error: Can't read: nofile.java
you're ready to begin. If, on the other hand, it responds
javac: Command not found
or something similar, then you need to go back to the last chapter and make sure
you have the Java environment properly installed and
your PATH
configured correctly.
Assuming that Java is properly installed on your system, there are three steps to creating a Java program:
To write the code you need a text editor. You can use any text editor like Notepad, Brief, emacs or vi. Personally I use BBEdit on the Mac and UltraEdit on Windows. You should not use a word processor like Microsoft Word or WordPerfect since these save their files in a proprietary format and not in pure ASCII text. If you absolutely must use one of these, be sure to tell it to save your files as pure text. Generally this will require using Save As... rather than Save.
Integrated development environments like WebGain's Cafe or Borland's JBuilder include text editors you can use to edit Java source code. Such an editor will probably change your words various colors and styles for no apparent reason. Don't worry about this yet. As long as the text is correct, you'll be fine.
When you've chosen your text editor type Program
System.out.println
is not the same as
system.out.println
. CLASS
is not the same as
class
, and so on.
Save this code in a file called HelloWorld.java. Use exactly that name including case. Congratulations! You've just written your first Java program.
Extraneous Extensions |
---|
Some Windows text editors including Notepad add a three letter .txt extension to all the files they save without telling you. Thus you can unexpectedly end up with a file called HelloWorld.java.txt. This is wrong and will not compile. If your editor has this problem, you should get a better editor. However in the meantime enclose the filename in double quotes in the Save dialog box to make editor save the file with exactly the name you want. |
Writing code is easy. Writing correct code is much harder. In the compilation step you find out whether the code you wrote is in fact legal Java code. Select the section which most closely matches your environment, and follow the instructions to compile and run your program.
To compile the code from the command line, make sure you're in the same directory where you saved HelloWorld.java and type "javac HelloWorld.java" at the command line prompt. For example,
% javac HelloWorld.java
If everything is well, then the compiler will silently return you to the command line prompt with no indication that anything has happened. However if you list the files in that directory, you'll see a new file there called HelloWorld.class. This file contains the Java byte codes for your program.
To compile the code from the command line, make sure you're in the same directory where you saved HelloWorld.java and type javac HelloWorld.java in a DOS window. For example,
C:\books\JDR2\examples>javac HelloWorld.java
If everything is well, then the compiler will silently return you to the command line prompt with no indication that anything has happened. However if you list the files in that directory, you'll see a new file there called HelloWorld.class. This file contains the Java byte codes for your program. For example,
C:\books\JDR2\examples>dir Volume in drive D has no label. Volume Serial Number is D845-2F2F Directory of C:\books\JDR2\examples 06/05/00 11:35a <DIR> . 06/05/00 11:35a <DIR> .. 06/05/00 11:37a 115 HelloWorld.java 06/05/00 11:45a 426 HelloWorld.class 4 File(s) 541 bytes 219,250,688 bytes free
Open the Tools folder in the MRJ SDK folder. You'll see a a folder called JDK Tools. Inside this folder you'll find a double-clickable application named javac. Double click it.
The dialog that pops up is the compiler.
In the empty text field at the top you type the full paths
to the files you want to compile using Unix-style path syntax. For example,
if HelloWorld.java is on the Desktop on a hard drive named Macintosh HD,
you would type
"/Macintosh HD/Desktop Folder/HelloWorld.java".
This is shown in Figure 3-1. Then press
the "Do Javac" button to compile the file.
The compiler displays any error messages in a
new dialog box. If the file compiles withot error,
the compiler places the resulting
Figure 3-1:
Your first effort to compile the code may not succeed. In fact it's probably more likely that it will fail than that it will work. In that case you may see one or more of the following error messages:
HelloWorld.java:5: ';' expected.
System.out.println("Hello World!")
^
HelloWorld.java:1: Class or interface declaration expected.
Class HelloWorld {
^
HelloWorld.java:9: '}' expected.
}
These messages may or may not be helpful. For now if you had a problem you should make sure that you did in fact type in the code exactly as written in Program 3-1. Here are a few common mistakes you can check for:
Did you put a semicolon after System.out.println("Hello World!")
?
Did you include the closing brace? There should be two open braces and two closing braces.
Did you type everything exactly as it appears here? In particular did you use the
same capitalization? Remember, Java is
case sensitive. class
is not the same as Class
.
Make sure your text editor used straight quotes like "" and not curly quotes like “ and ”.
Step 2 is by far the hardest part of this entire book. Do not get discouraged if you're having trouble getting code to compile. If after following the above suggestions you still can't compile HelloWorld.java, try the following:
Read the documentation, scant though it may be, for your development environment. This is particularly important if you're using an IDE that isn't covered here like Borland's JBuilder.
Get a knowledgeable friend to help you out. This is often the quickest road to success at this stage.
Get an unknowledgeable friend to help out. Sometimes it just takes a second pair of eyes to see what you can't.
Post a message on comp.lang.java.help. Be sure to include your complete source code, the complete text of any error messages you get, and details of the development environment and platform you're using. For example, Sun's JDK 1.1, Solaris 2.5 for Sparc, etc.
After you have successfully compiled the program, you run the program to find out whether it in fact does what you expect it to do.
When javac compiled HelloWorld.java, it wrote byte code in a file called HelloWorld.class in the same directory as HelloWorld.java. You run this program by typing "java HelloWorld" at the shell prompt. For example,
% java HelloWorld
As you probably guessed the program responds by printing "Hello World!" on your screen as shown in Figure 3-2.
Figure 3-2:
Congratulations! You've just finished your first Java program!
In the MRJ SDK 2.x folder, you'll see a folder called JBindery. Open it. Inside this folder, you'll find a double clickable aplpication called JBindery. Drag and drop the HelloWorld.class file onto the JBindery icon. This should result in the dialog shown in Figure 3-3. Then click the Run button.
Figure 3-3:
Then the program prints "Hello World!" in a standard output window your screen as shown in Figure 3-4.
Figure 3-4:
At this point you may find yourself wondering how to quit since there doesn't appear to be a standard File menu with a Quit menu item. The Quit menu item is hiding in the Java Runtime menu in the Apple menu. The reason is so that you can create your own menu bars in stand-alone applications that replace the standard Macintosh menu bars. You'll learn how to do this in Chapter !Bad Ref!.
Hello World is a Java application. A Java application is normally started from the
command line prompt and contains a main()
method.
When you typed java HelloWorld, here's what happened.
First the Java interpreter looked
for a file called HelloWorld.class. When
it found that file, it looked inside it
for a method called main()
. Once it found the main method,
it executed the statements found there, in order.
In this case there was only one statement,
System.out.println("Hello World!");
which, as you probably guessed, prints "Hello World!" on the screen. Then, since
there were no further statements in the
main()
method, the program exited.
Java source code is composed of a number of different pieces. The lowest level is made up of tokens which are like atoms. Each token cannot be split into smaller pieces without fundamentally altering its meaning. There are seven kinds of tokens:
These tokens are combined to make the molecules of Java programs, statements and expressions; and these molecules are combined into still larger structures of blocks, methods, and classes.
Keywords are identifiers like public
, static
and class
that have a special meaning inside Java source code
and outside of comments and string literals. Hello World uses
four keywords:
public
, static
, void
and
class
.
Keywords are reserved for their intended use and cannot be used by the programmer for variable or method names.
There are fifty reserved keywords in Java 1.1 (51 in Java 1.2). The forty-eight that are actually used in are listed in Table 3-1 below. Don't worry if the purposes of the keywords seem a little opaque at this point. They will all be explained in much greater detail later.
Table 3-1:
Keyword | Purpose |
---|---|
abstract | declares that a class or method is abstract |
boolean | declares a boolean variable or return type |
break | prematurely exits a loop |
byte | declares a byte variable or return type |
case | one case in a switch statement |
catch | handle an exception |
char | declares a character variable or return type |
class | signals the beginning of a class definition |
continue | prematurely return to the beginning of a loop |
default | default action for a switch statement |
do | begins a do while loop |
double | declares a double variable or return type |
else | signals the code to be executed if an if statement is not true |
extends | specifies the class which this class is a subclass of |
final | declares that a class may not be subclassed or that a field or method may not be overridden |
finally | declares a block of code guaranteed to be executed |
float | declares a floating point variable or return type |
for | begins a for loop |
if | execute statements if the condition is true |
implements | declares that this class implements the given interface |
import | permit access to a class or group of classes in a package |
instanceof | tests whether an object is an instanceof a class |
int | declares an integer variable or return type |
interface | signals the beginning of an interface definition |
long | declares a long integer variable or return type |
native | declares that a method is implemented in native code |
new | allocates a new object |
package | defines the package in which this source code file belongs |
private | declares a method or member variable to be private |
protected | declares a class, method or member variable to be protected |
public | declares a class, method or member variable to be public |
return | returns a value from a method |
short | declares a short integer variable or return type |
static | declares that a field or a method belongs to a class rather than an object |
super | a reference to the parent of the current object |
switch | tests for the truth of various possible cases |
synchronized | Indicates that a section of code is not thread-safe |
this | a reference to the current object |
throw | throw an exception |
throws | declares the exceptions thrown by a method |
transient | This field should not be serialized |
try | attempt an operation that may throw an exception |
void | declare that a method does not return a value |
volatile | Warns the compiler that a variable changes asynchronously |
while | begins a while loop |
Two other keywords, const
and
goto
, are reserved by Java but are not actually
implemented. This allows compilers to produce better error
messages if these common C++ keywords are improperly used in a
Java program.
Java 1.2 adds the strictfp
keyword to declare
that a method or class must be run with exact IEEE 754
semantics.
true
and false
appear to be
missing from this list. In fact, they are not keywords but
rather boolean
literals. You still can't use them as a variable
name though.
Language Law: Are true and false Java keywords? |
---|
According to the New Hacker's Dictionary a language lawyer is "a person who will show you the five sentences scattered through a 200-plus-page manual that together imply the answer to your question 'if only you had thought to look there.'" Language law sections are included in this book to satisfy language lawyers and other pedants who enjoy sending authors flaming email to correct minor misstatements. According to the Java language specification |
Literals are pieces of Java source code that mean exactly
what they say. For instance "Hello World!"
is a
String
literal and its meaning is
the string Hello World!
The string "Hello World!"
looks like it's several
things; but to the compiler it's just one thing, a
String
. This is similar to how an expression like
1,987,234 may be seven digits and two commas but is really just
one number.
Grammar Alert: Why is the Word String Capitalized? |
---|
The word string with a little s is a generic term in programming that
refers to an ordered sequences of characters. However in Java all strings
are members of the |
The double quote marks tell you this is a String
literal. A string is an
ordered collection of characters (letters, digits, punctuation marks, etc.).
Although the string may have meaning to a human being reading the code, the
computer sees it as no more than a particular set of letters in a particular
order. It has no concept of the meaning of the characters. For instance it
does not know that "two" + "two" is "four." In fact the computer thinks that
"two" + "two" is "twotwo"
The quote marks show where the String
literal
begins and ends. However the quote
marks themselves are not a part of the String
literal.
The value of this string is
Hello World!
, not "Hello World!"
You can change
the output of the program by changing Hello World to some other line of
text.
A Java String
has no concept of italics, bold face, font
family or other formatting. It cares only about the characters that compose
it. Even if you're using an editor like NisusWriter that lets you format
text files, "Hello World!" is identical to "Hello World!" as
far as Java is concerned.
char
literals are similar to String
literals except they're
enclosed in single quotes and must have exactly one character. For example
'c'
is a char
literal that means the letter c.
true
and false
are boolean
literals that mean true and false.
Numbers can also be literals. 34
is an int
literal and it means the number thirty-four. 1.5
is a
double
literal. 45.6
, 76.4E8
(76.4
times 10 to the 8th power) and -32.0
are also
double
literals.
34L
is a long
literal and it means the number
thirty-four. 1.5F
is a float
literal.
45.6f
, 76.4E8F
and -32.0F
are also
float
literals.
Identifiers are the names of variables, methods, classes,
packages and interfaces. Unlike literals they are not the things themselves,
just ways of referring to them. In the HelloWorld program,
HelloWorld
, String
, args
,
main
and System.out.println
are identifiers.
HelloWorld
, String
, and System
are identify classes.
main
and println
identify methods.
args
identifies a method argument and
out
identifies an object field.
Identifiers must be composed of letters, numbers, the underscore
_
and the dollar sign $
. Identifiers may only
begin with a letter, the underscore or a dollar sign.
They may not begin with a number.
Furthermore, that they cannot contain any white space
or ounctuation characetrs other than _
and $
.
It's a
good idea to use mnemonic names that are closely related to
the things they identify. It is important to note that as in C but not
as in Fortran or Basic, all identifiers are case-sensitive.
MyVariable
is not the same as myVariable
. There is
no limit to the length of a Java identifier. The following are all legal
identifiers:
- MyVariable
- myvariable
- MYVARIABLE
- x
- i
- _myvariable
- $myvariable
- _9pins
- andros
- ανδρος
- OReilly
- This_is_an_insanely_long_variable_name_that_just_keeps_going_and_going_and_going_and_well_you_get_the_idea_The_line_breaks_arent_really_part_of_the_variable_name_Its_just_that_this_variable_name_is_so_ridiculously_long_that_it_won't_fit_on_the_page_I_cant_imagine_why_you_would_need_such_a_long_variable_name_but_if_you_do_you_can_have_it
The following are not legal identifiers:
- My Identifier // Contains a space
- 9pins // Begins with a digit
- a+c // The plus sign is not an alphanumeric character
- testing1-2-3 // The hyphen is not an alphanumeric character
- O'Reilly // Apostrophe is not an alphanumeric character
- OReilly_&_Associates // ampersand is not an alphanumeric character
Tip: How to Begin an Identifier with a Number |
---|
If you want to begin an identifier with a digit, prefix the name you'd
like to have (e.g. |
White space consists mostly of the space character that you produce by hitting the space bar on your keyboard and that is commonly used to separate words in sentences. There are four other white space characters in Java:
Depending on your platform, when you hit the return or enter key, you get either a carriage return (the Mac), a linefeed (Unix) or both (DOS, Windows, VMS). This produces a hard line break in the source code text.
Outside of String
literals Java treats all white space and
runs of white space (more than one white space character in immediate
succession) the same. It's only used to separate tokens and pretty up code,
and for this purpose
one space is as good
as seven spaces, a tab and two carriage returns. Exactly which white space
characters you use is primarily a result of what's convenient for human
beings reading the code. The compiler doesn't care.
Inside String
and character literals the only white space
permitted is the space character. Carriage returns, tabs, line feeds and
form feeds must be inserted with special escape sequences like
\r
, \t
, \n
, and \f
. You
cannot break a String
literal across a line like this:
String poem = "Mary had a little lamb
whose fleece was white as snow
and everywhere that Mary went
the lamb was sure to go.";
Instead you must use \n
and the
string concatenation operator, +
, like
this:
String poem = "Mary had a little lamb\n" +
"whose fleece was white as snow\n" +
"and everywhere that Mary went\n" +
"the lamb was sure to go.";
Note that you can break a statement across multiple lines,
you just can't break a String
literal.
Also note that \n
only works on Unix. You should probably use
System.getProperty("line.separator")
instead to return
the proper line separator string for the platform your program is running on.
Java does not have all the escape sequences C has. Besides those already
mentioned it has only \b
for backspace, \\
for the backslash character
itself.
There are also \u escapes that let you include any Unicode character.
Separators help define the structure of a program. The separators
used in HelloWorld are parentheses, ( )
, braces,
{ }
, brackets, [ ]
, the period, .
, and
the semicolon, ;
. Table 3-2
lists the six Java separators (nine if you
count opening and closing separators as two).
Table 3-2:
Separator Purpose | |
---|---|
( ) | Encloses arguments in method definitions and calling; adjusts precedence in arithmetic expressions; surrounds cast types; and delimits test expressions in flow control statements |
{ } | defines blocks of code and automatically initializes arrays |
[ ] | declares array types and dereferences array values |
; | terminates statements |
, | separates successive identifiers in variable declarations; chains
statements in the test expression of a for loop |
. | Selects a field or method from an object; separates package names from sub-package and class names |
: | Used after loop labels |
You might think it would be useful to be able to store information about what is going on in a program within the source code itself. In fact you can. This is done with comments.
Comments in Java are identical to those in C++. Everything between /*
and
*/
is ignored by the compiler, and everything on a single line after //
is
also thrown away. Therefore, Program 3-2 is,
as far as the compiler
is concerned, identical to the first HelloWorld program.
Program 3-2:
// This is the Hello World program in Java
class HelloWorld {
public static void main (String[] args) {
/* Now let's print the line Hello World */
System.out.println("Hello World!");
} // main ends here
} // HelloWorld ends here
The /* */
style comments can comment out multiple lines so
they're useful when you want to remove large blocks of code, perhaps for
debugging purposes. //
style comments are better for short
notes of no more than a line. /* */
can also be used in the
middle of a line whereas //
can only be used at the end.
However putting a comment in the middle of a line makes code harder to read
and is generally considered to be bad form.
Comments evaluate to white space, not nothing at all. Thus the following line causes a compiler error:
int i = 78/* Split the number in two*/76;
Java turns this into the illegal line
int i = 78 76;
not the legal line
int i = 7876;
This is also a difference between K&R C and ANSI C.
An operator is a symbol that operates on one or more arguments to produce a result. The Hello World program is so simple it doesn't use any operators but almost all other programs you write will. Table 3-3 lists Java's operators. Don't worry if the purposes of the operators seem a little opaque at this point. They will all be explained in much greater detail later.
Table 3-3:
Operator | Purpose |
---|---|
+ | addition of numbers, concatenation of Strings |
+= | add and assign numbers, concatenate and assign Strings |
- | subtraction |
-= | subtract and assign |
* | multiplication |
*= | multiply and assign |
/ | division |
/= | divide and assign |
| | bitwise OR |
|= | bitwise OR and assign |
^ | bitwise XOR |
^= | bitwise XOR and assign |
& | bitwise AND |
&= | bitwise AND and assign |
% | take remainder |
%= | take remainder and assign |
> | greater than |
>= | greater than or equal to |
< | less than |
<= | less than or equal to |
! | boolean NOT |
!= | not equal to |
++ | increment by one |
-- | decrement by one |
>> | shift bits right with sign extension |
>>= | shift bits right with sign extension and assign |
<< | shift bits left |
<<= | shift bits left and assign |
>>> | unsigned bit shift right |
>>>= | unsigned bit shift right and assign |
&& | boolean AND |
|| | boolean OR |
== | boolean equals |
= | assignment |
~ | bitwise NOT |
?: | conditional |
Now that you know what the tokens are it's possible to break HelloWorld
into tokens. Here are the tokens in the commented version
of Hello World, one to a line.
// This is the Hello World program in Java
class
HelloWorld
{
public
static
void
main
(
String
args
[
]
)
{
/* Now let's print the line Hello World */
System.out.println
(
"Hello World!"
)
;
}
// main ends here
}
// HelloWorld ends here
There are twenty-five tokens in HelloWorld, four keywords, five identifiers, four comments, one literal and eleven separators. That, in short, is the micro-structure of HelloWorld.
HelloWorld
is very
close to the simplest program imaginable. All it does is print
two words and an exclamation point on the display. Nonetheless there's quite a lot
going on inside it. All Java applications have a certain structure and since HelloWorld
is a Java application, albeit a simple one, it shares that structure.
You might think that the only line in the code that mattered was System.out.println("Hello World!");
since that was the only line that appeared to do anything. In some sense it was the
only line that did anything. In fact it's the only statement
in the program. However the rest of the code is not irrelevant. It sets up a structure
that all Java applications must follow. Since there is so little going on in this
program, the structure is rather exposed and easy to see. Therefore let's take this
opportunity to investigate the structure of a simple Java application, line by line.
Line 1:
class HelloWorld {
The initial class
statement may be thought of as defining the program name, in this
case HelloWorld
. The compiler actually got the name for the class file from
the class
HelloWorld
statement in the source code, not from the name of the source code file.
If there is more than one class in a file, then the Java compiler will store each one
in a separate .class file.
For reasons you'll see later, it's advisable to give the
source code file the same name as the primary class
in the file followed by the .java
extension.
Line 1:
class HelloWorld {
After class HelloWorld
you open the class with a brace. The brace is used to separate
blocks of code, and must be matched by a closing brace. Thus somewhere (in this case
all the way at the end of the file) is another brace which closes the class.
Everything between those two braces is a part of this class.
Line 2:
The second line is blank. Blank lines are meaningless in Java and are used purely to make the code easier to read. You could take all the blank lines out of this program, and it would still produce identical results.
Line 3:
public static void main
(String[] args) {
HelloWorld
class contains one method, the main()
method. As in C, the main()
method
is where an application begins executing. The words before the braces declare what
the main()
method is, what type of value it returns and
what data it receives. Everything
after the brace actually is the main()
method.
Line 3:
public static void
main (String[] args) {
The main()
method is declared public
meaning that
the method can be called from anywhere. It is declared static
meaning that all instances of this class share this one method. It is
declared void
which means, as in C, that this method does not
return a value. Finally the interpreter passes
any command line arguments to the method in
an array of Strings
called args
.
In this simple program there aren't any command line arguments though.
Line 3 is the most complicated line in the program. You'll investigate each piece
of this line in much greater detail in later chapters so don't worry too much about
it now. The primary thing you need to know is that every Java application (but not
every applet) needs to have a main()
method and that method must be
declared exactly as this
one is.
Finally note that line 3 is indented by two spaces. This is because line
3 is inside the HelloWorld
class and indentation helps keep
track of how deep inside it is. Every time you open a new block with a brace,
it's customary to indent
subsequent lines by two more spaces. When you leave the
block with a closing brace, deindent by two spaces.
This makes the code
much easier to read since you can see at a glance which statements belong to
which classes, methods and blocks. However this is purely a convention and
not in any way part of the Java language. The code would produce identical
output if it had no indentation. In fact you'll probably find a few examples
in this book where the convention hasn't been followed precisely.
Indentation makes code easier to read and understand, but does not change
its meaning.
White space in Java is significant as a separator between different things, but the amount of white space is not. The Java compiler treats three consecutive spaces the same as three consecutive tabs the same as one space. Whether you use tabs or spaces to indent your code is mainly a matter of which is more convenient in your text editor.
The amount and type of white space is significant inside String literals. "Hello World!" is not the same as "Hello World!" and "Hello
World!" won't even compile.
Line 4 is another blank line.
Line 5:
System.out.println("Hello World!");
Line 5 is indented by two more spaces since it is now two braces deep in the program
(in the main()
method of the HelloWorld
class).
main()
method is called, it does exactly one thing: print Hello World! to the standard output, generally a terminal monitor or console window of some sort.
This is accomplished by the System.out.println()
method. To
be more precise this is accomplished by calling the println
method of
the out
object belonging to the System
class;
but for now just treat this as one
method.
The System.out.println()
method accepts a single argument
of any type. In this case it has the argument "Hello World!"
Next note that this line ends with a semicolon. Every statement in Java must end with a semicolon, and it's a very common mistake of even the most experienced programmers to omit semicolons. If you do the compiler will generate an error message which, depending on how smart the compiler is, may or may not have anything to do with missing semicolons. For instance if the semicolon is left out of this line here's what javac says:
HelloWorld.java:5: ';' expected. System.out.println("Hello World!") ^
You may be wondering why the other lines of this program didn't end with a semicolon.
They didn't because they're not statements. Rather they're definitions. When you
open a block with a brace you're signaling that you can't do everything you want
to do with one statement. Instead you're going to use a whole series of statements and execute
them as a group. It isn't finished so you'll continue with more statements. On the
other hand System.out.println("Hello World!")
is complete unto itself so it is terminated with a semicolon.
Sometimes you'll have lines of code that continue for some distance. It is permissible
to use a newline or carriage return instead of typing a space (except inside a
String
literal).
The Java compiler treats all white space equally.
This book makes frequent use of this feature to make long lines of code fit within the margins of the page. Remember,
the line isn't finished until you see the semicolon.
For C Programmers: println() and printf() |
---|
Unlike the |
Line 6 is blank.
Line 7 has a closing brace. This finishes the main method since the previous opening brace opened the main method. A closing brace closes the nearest preceding opening brace that has not already been closed.
Line 8 is blank.
Line 9 has the final closing brace which signals the end of the HelloWorld class.
In this chapter you learned to write a simple Java application. The things you learned included:
The goal of this chapter is to be able to write, compile and run a simple Java program. Once you've done that, you're ready to move on.
In the next chapter you'll expand the Hello World program to include
multiple statements, different data and user input. You'll learn a variation
on System.out.println()
, how to use String
variables and how to do simple arithmetic.
There isn't much more to learn about comments than you learned in this chapter. However in Chapter !Bad Ref!, JavaDoc, you will learn how to use special JavaDoc comments to combine source code with its own documentation.
There is a lot more to learn about println()
than this
chapter covered, though. You'll see more about it in Chapter !Bad Ref!, Files and Streams.
Q: Does the compiler turn comments into white space or does it throw them away completely?
A: As in ANSI C the compiler turns comments into white space. In general when you're uncertain how something may work, the way it works in ANSI C is a good first guess.
Q: I thought Java was supposed to be cross-platform, How come they're all these different instructions for Unix, the Mac and Windows?
A: Programs you create with Java are cross-platform. The Java development environment regrettably isn't.
Q: Can comments be included in the middle of a String
?
A:
No. Inside a String
literal /
and *
are just like any other characters. They have no special meaning.
For instance the following program prints
/* This is a test */:
class StringTest {
public static void main (String[] args) {
System.out.println(" /* This is a test */");
}
}
HelloEarth
?What would happen if you added the following line to the Hello World program?
/* THIS PROGRAM CANNOT BE EXECUTED WITHOUT SYSADMIN PRIVILEGES */
Write a program that produces the following output:
Hello World! It's been nice knowing you. Goodbye world!
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * * *
Now modify it to draw them next to each other like above.
The original Hello World program in C comes from
Kernighan, Brian W. And Dennis M. Ritchie, The C Programming Language, pp. 5-8, Englewood Cliffs N.J.: Prentice-Hall, Inc., 1988
Operators, literals, separators, white space, comments and identifiers are covered fully if not always clearly in sections 3.6 through 3.10 of The Java Language Specification.
Gosling, James, Bill Joy And Guy Steele, The Java Language Specification, pp. 15-25, Reading MA: Addison-Wesley, Inc., 1996