Understanding HelloWorld

   

The result you get from running HelloWorld might not seem very interesting, but then it's a simple program. There is a good bit to be learned from the code, however. After you understand each piece, you'll be much closer to being able to write any program you want.

Comments

The HelloWorld source code begins with a comment that describes the purpose of the program:

 /** * My first program demonstrates displaying * a string on the screen */ 

Given enough time, another programmer reading your code can usually understand what it does, but comments allow you to explain why you implemented a program in a certain way, or even how you intend for it to be used. Java supports several styles of comments that are described in Chapter 3, "Data Types and Other Tokens." This example is a simple one, but the sooner you develop the habit of commenting your code, the better.

See "Comments,"

Declaring a Class

Java is a language built on classes, so the first task when creating any Java program is to create a class. Look at the first line of the HelloWorld application that follows the comment:

 public class HelloWorld { 

This declares a class called HelloWorld. The compiler would allow the class to be named almost anything, but remember to use descriptive class names so their purposes will be clear to other programmers.

See "Classes in Java,"

Note

Although the compiler doesn't require it, it is considered good style to always begin class names with a capital letter and use mixed case to separate words. There are also a number of limitations on the names you can assign to a class, but you'll learn more about that later in Chapter 7, "Classes."

Sun's "Code Conventions for the Java Programming Language" includes these class naming guidelines along with many other elements of proper Java coding style. You can access this document at http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html to help you adopt good style conventions while you're learning the language.


Next , notice the brace ( { ) that is located after the class name . If you look at the end of the class, there is also a closing brace ( } ). The braces tell the compiler where your class definition begins and ends. Any code between those two braces is considered part of the HelloWorld class.

Braces are used to delimit blocks, which are covered in more detail in Chapter 4, "Methods and Exceptions."

A closing brace closes the open brace closest to it. In the case of the HelloWorld program, there are two open braces and two closing braces, one to close the main method and one to close the class.

The main Method

Now look again at the next line of HelloWorld:

 public static void main(String args[]){ 

This line declares a method named main within the HelloWorld class. Methods are equivalent to functions or procedures in other languages. Each method performs some of the tasks of a program. The main method is special because it is the first method called when a Java application starts. When you run java HelloWorld, the Java interpreter starts executing at the first line of the main method. A Java application stops running after the main method and any user threads started by it have finished executing.

When creating any Java application, you need to create a main method as shown. In Chapter 4, you'll learn more about the different parts of a method declaration, such as the meaning of the public access specifier and static modifier used here. For now, consider only the method return type and the args parameter. Notice that the return type is specified to be void, which means that nothing is returned by the main method. Unlike some languages, a Java program does not return a value to the process that launched it using a method return value. However, you can return a value with a special statement that is used to force a program to exit:

 System.exit(0); 

You can terminate a Java program at any point by calling System.exit and passing an integer status code. Passing zero as shown in the preceding example indicates a normal exit condition. You should pass a nonzero code if your program is exiting abnormally because of an error condition.

Now look at the single method parameter, String args[], that is part of the declaration. This parameter declaration means that the main method must be passed as an array of zero or more String objects when it is called. String is the Java class used to represent text strings (see Chapter 8, "Using Strings and Text" ). When main is called, the method parameter represents any command line arguments that are passed to the java program when the application is started. When you run java HelloWorld, the only string given to the java program is the name of the class that starts your application. The class name does not count as a command line argument, so in this case the args array passed to main is an empty array (that is, an array of length zero). If you instead type java HelloWorld hello, main is called with an args array that contains the string "hello" as its first element. Chapter 3, "Data Types and Other Tokens," contains more details of how arrays are used in Java.

Writing to the Screen

How does the text Hello World! appear when you run the HelloWorld program? The answer (as you have probably guessed) lies in the next line of the program:

 System.out.println("Hello World!"); 

This line outputs the string specified within the quotation marks. You can replace the "Hello World!" text with any text you would like to display.

Now you've seen all the steps necessary to make HelloWorld work. With your first Java program behind you, you're ready to learn more about System.out, its counterpart System.in, and how to use them to write more interesting programs.

System.out and System.in

You have just seen how System.out.println is used to print text to the screen. In fact, System.out.println can be used at any time to print text to what is known as Standard Out. Standard Out is typically the screen but you can also redirect it elsewhere (for example, to a text file) by supplying a new destination through the System.setOut method. System.out refers to an instance of the PrintStream class that is a standard part of Java (see Chapter 21, "Streams, Files, and Serialization" ).

Chapter 21 describes streams in more detail, but fundamentally a stream is an object that represents a supplier or a receiver of data, such as a keyboard, a printer, or a file. In the case of a data receiver, println is a PrintStream method that sends the parameter passed to it to the associated output stream.

This method serves roughly the same purpose as writeln in Pascal, printf in C, or cout in C++.

println Versus print

There is one minor variation on println that is also commonly used: print("Hello World!"). The difference between println and print is that print does not add a line separator at the end of the line. Strictly speaking, print is the true parallel to printf and cout for C/C++ programmers.

To demonstrate this, expand your HelloWorld example a little by copying Listing 2.2 into a file called HelloWorld2.java and compiling it with the line javac HelloWorld2.java.

Listing 2.2 A HelloWorld Program with Two Printouts
 public class HelloWorld2 {   public static void main(String args[]){     System.out.println("Hello World!");     System.out.println("Hello World Again!");   } } 

To run the program, type java HelloWorld2.

You should see output that looks like the following:

 Hello World! Hello World Again! 

Notice that each phrase appears on its own line. Now, for comparison, try the program again using print instead of println. Copy Listing 2.3 into a file called HelloWorld3, compile, and run it.

Listing 2.3 A HelloWorld Output Using print Statements
 public class HelloWorld3 {   public static void main (String args[]){     System.out.print ("Hello World!");     System.out.print ("Hello World Again!");   } } 

You should notice that the output looks like this because of the lack of line separators:

 Hello World!Hello World Again! 
Getting Information from the User with System.in

Having a means for output is balanced by having a similar means for input. System.out is used to write to a stream, and System.in is used to read from one.

Requesting Input from the User

Use System.in.read when you want to get a character from the user. This is not covered in too much depth here because System.in isn't used that often in Java programs. Typical applications that require user input are graphical, Swing-based applications that use more sophisticated means for accepting user input. Also, as you learn in the upcoming section "HelloWorld as an Applet," System.in does not apply to applets. Nevertheless, Listing 2.4 shows an example of a Java application that reads a character from the user and echoes it to the screen.

Listing 2.4 ReadHello ” An Application that Reads Input from the User
 import java.io.*; public class ReadHello {   public static void main (String args[]){     int inChar;     System.out.println("Enter a Character:");     try {       inChar = System.in.read();       System.out.print("You entered ");       System.out.println(inChar);     }     catch (IOException e){       System.out.println("Error reading from user");     }   } } 

You've probably already noticed that there is a lot more to this code than there was to the last one. Before that's explained, you should compile the program and prove to yourself that it works. After compiling, execute the program by typing java ReadHello, enter an A as the character to be read, and you should see the following result displayed onscreen:

 Enter a Character: A You entered 65 

You probably noticed that this program printed a number instead of the character you typed. Let's look more closely at the example to see why.

In this example, the code you are most interested in is the line that reads:

 inChar = System.in.read(); 

System.in.read() is a method that accepts a single character from an input stream (associated with the keyboard in this case) and returns that character so that it can be used in an expression or assigned to a variable.

In the case of ReadHello, the character returned by System.in.read is assigned to a variable called inChar.

Following the input of a character, the program calls System.out.println to display what was typed.

Note

It isn't necessary to assign the result of System.in.read to a variable. If you prefer, you can print it out directly in the second System.out call by changing it to the following:

 System.out.println(System.in.read()); 

The program displays a number instead of a character for what you entered because the read method of System.in returns an integer code between -1 and 255, not an actual character.

The code represents a character in the ASCII character set or “1 if the end of the stream has been reached.

To convert the number that is returned from System.in.read into a character, you must use a cast. Casting converts a given data type to another one. Change ReadHello to look like Listing 2.5.

Listing 2.5 ReadHello2 ” An Application That Reads in a Character from the User
 import java.io.*; public class ReadHello2 {   public static void main (String args[]){     char inChar;     System.out.println("Enter a Character:");     try {       inChar =(char) System.in.read();       System.out.print("You entered ");       System.out.println(inChar);     }      catch (IOException e){       System.out.println("Error reading from user");     }   } } 

Notice the differences from the original version. In Listing 2.5, inChar is now declared as a character instead of an integer and a cast operator, (char), has been inserted before the read call. The cast operator causes the integer returned from the read method to be treated as a character. The result of the cast is a character that is assigned to inChar.

The Rest of the Code: try and catch What does the rest of the code do? The input and output calls are contained inside what is called a try-catch block.

A try-catch block provides a simple mechanism for handling errors or exceptional conditions. In some programming languages, when a problem occurs during execution, there is no way for you as a programmer to intercept it and try to handle it gracefully.

Java, along with languages such as C++ and Ada, supports what is known as exception handling. Most error conditions in a Java program will cause an exception that can be "caught" and handled. You place statements that might cause an exception inside a try block and follow that with a catch statement to intercept exceptions that occur. System.in.read will cause an IOException if an error occurs reading from an input stream, so, as shown in this example, it must be placed inside a try block.

See "Catching and Throwing Exceptions,"

   


Special Edition Using Java 2 Standard Edition
Special Edition Using Java 2, Standard Edition (Special Edition Using...)
ISBN: 0789724685
EAN: 2147483647
Year: 1999
Pages: 353

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net