Sams Teach Yourself C in 21 Days

(singke) #1
Saying Hello, World with Java ......................................................................

Way back on Day 1, you were introduced to C programming by writing the traditional
first C program,Hello, World!Tomorrow, you’ll learn how to say Hello, Worldwith
C++. Now it’s Java’s turn. Listing B1.3 shows the Java code for Hello, World!

LISTINGB1.3 hello.java. A Java version of Hello, World!
1: public class HelloWorld
2: {
3: public static void main(String args[])
4: {
5: Say(“Hello, world!”);
6: }
7: private static void Say(String message)
8: {
9: System.out.println(message);
10: }
11: }

Hello, World!
This program is very simple, but is actually a bit more complex than it needs to
be in order to show you a Java function (called a method). Line 1 starts the defin-
ition of the program HelloWorld. Note that the program is defined as a class. This is an
example of how Java requires all aspects of a program to use object-oriented techniques.
Line 3 starts the definition of the main()function, which is a required part of all Java
applications just as in C (but a Java applet does not require a main()function, as you’ll
learn in the subsequent chapter). When a Java application runs, execution begins in the
main()function. The code on line 5 calls the Say()function, passing it the argument
“Hello, World!”Then the closing brace on line 6 marks the end of the main()function.
The function Say()is defined on lines 7 to 10. In many ways, this looks like a C func-
tion, doesn’t it? Note that the function argument is type String, which is one of the pre-
defined objects in Java’s class libraries. Line 9 does the actual work of printing the text
on the screen. System.outis another one of Java’s predefined objects, corresponding to
thestdoutstream in C and the coutobject in C++. Calling the printlnmethod of the
System.outobject displays the specific text onscreen.
This sample program is a Java console program, which works with text input and output
only. Where you see the output depends on the details of the Java development tool you
are using. If you are using a command line Java, the output appears on that command
line. If you are using one of the graphical Java development environments, you’ll see the
output in a window labeled Java Console.

644 Bonus Day 1

OUTPUT

ANALYSIS

36 448201x-Bonus1 8/13/02 11:18 AM Page 644

Free download pdf