The "Hello World!" Application
The sections listed below provide detailed instructions for compiling and running a simple "Hello World!" application. The first section provides information on getting started with the NetBeans IDE, an integrated development environment that greatly simplifies the software development process. The NetBeans IDE runs on all of the platforms listed below. The remaining sections provide platform-specific instructions for getting started without an integrated development environment. If you run into problems, be sure to consult the common problems section; it provides solutions for many issues encountered by new users.
"Hello World!" for the NetBeans IDE
It's time to write your first application! These detailed instructions are for users of the NetBeans IDE. The NetBeans IDE runs on the Java platform, which means that you can use it with any operating system for which there is a JDK 6 available. These operating systems include Microsoft Windows, Solaris OS, Linux, and Mac OS X.
• A Checklist
• Creating Your First Application
Create an IDE Project
Add JDK 6 to the Platform List (if necessary)
Add Code to the Generated Source File
Compile the Source File
Run the Program
• Continuing the Tutorial with the NetBeans IDE
A Checklist
To write your first program, you'll need:
1. The Java SE Development Kit 6 (JDK 6)
For Microsoft Windows, Solaris OS, and Linux: http://java.sun.com/javase/6 /download.jsp
For Mac OS X: http://connect.apple.com
2. The NetBeans IDE
For all platforms: http://www.netbeans.info/downloads/index.php
Creating Your First Application
Your first application, HelloWorldApp, will simply display the greeting "Hello World!". To create this program, you will:
•Create an IDE project
When you create an IDE project, you create an environment in which to build and run your applications. Using IDE projects eliminates configuration issues normally associated with developing on the command line. You can build or run your application by choosing a single menu item within the IDE.
•Add code to the generated source file
A source file contains code, written in the Java programming language, that you and other programmers can understand. As part of creating an IDE project, a skeleton source file will be automatically generated. You will then modify the source file to add the "Hello World!" message.
•Compile the source file into a .class file
The IDE invokes the Java programming language compiler (javac), which takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes.
•Run the program
The IDE invokes the Java application launcher tool (java), which uses the Java virtual machine to run your application.
To create an IDE project:
1.Launch the NetBeans IDE.
On Microsoft Windows systems, you can use the NetBeans IDE item in the Start menu.
On Solaris OS and Linux systems, you execute the IDE launcher script by navigating to the IDE's bin directory and typing ./netbeans.
On Mac OS X systems, click the NetBeans IDE application icon.
2.In the NetBeans IDE, choose File | New Project.
NetBeans IDE with the File | New Project menu item selected.
3.In the New Project wizard, expand the General category and select Java Application as shown in the following figure:
NetBeans IDE, New Project wizard, Choose Project page.
4.In the Name and Location page of the wizard, do the following (as shown in the figure below):
In the Project Name field, type Hello World App.
In the Create Main Class field, type helloworldapp.HelloWorldApp.
Leave the Set as Main Project checkbox selected.
NetBeans IDE, New Project wizard, Name and Location page.
5.Click Finish.
The project is created and opened in the IDE. You should see the following components:
• The Projects window, which contains a tree view of the components of the project, including source files, libraries that your code depends on, and so on.
• The Source Editor window with a file called HelloWorldApp open.
• The Navigator window, which you can use to quickly navigate between elements within the selected class.
NetBeans IDE with the HelloWorldApp project open.
Add JDK 6 to the Platform List (if necessary)
It may be necessary to add JDK 6 to the IDE's list of available platforms. To do this, choose Tools | Java Platform Manager as shown in the following figure:
Selecting the Java Platform Manager from the Tools Menu
If you don't see JDK 6 (which might appear as 1.6 or 1.6.0) in the list of installed platforms, click "Add Platform", navigate to your JDK 6 install directory, and click "Finish". You should now see this newly added platform:
The Java Platform Manager
To set this JDK as the default for all projects, you can run the IDE with the --jdkhome switch on the command line, or by entering the path to the JDK in the netbeans_j2sdkhome property of your INSTALLATION_DIRECTORY/etc/netbeans.conf file.
To specify this JDK for the current project only, select Hello World App in the Projects pane, choose File | "Hello World App" Properties, click on Libraries, then select JDK 6 under the Java Platform pulldown menu. You should see a screen similar to the following:
The IDE is now configured for JDK 6.
Add Code to the Generated Source File
When you created this project, you left the Create Main Class checkbox selected in the New Project wizard. The IDE has therefore created a skeleton class for you. You can add the "Hello World!" message to the skeleton code by replacing the line:
// TODO code application logic here
with the line:
System.out.println("Hello World!"); // Display the string.
Optionally, you can replace these four lines of generated code:
/**
*
* @author
*/
with these lines:
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
These four lines are a code comment and do not affect how the program runs. Later sections of this tutorial explain the use and format of code comments.
Be Careful When You Type
Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are case-sensitive, so you must capitalize consistently.
HelloWorldApphelloworldapp
Save your changes by choosing File | Save.
The file should look something like the following:
/*
* HelloWorldApp.java
*
* Created on February 5, 2006, 6:43 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package helloworldapp;
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
public class HelloWorldApp {
/** Creates a new instance of HelloWorldApp */
public HelloWorldApp() {
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Compile the Source File into a .class File
To compile your source file, choose Build | Build Main Project from the IDE's main menu.
The Output window opens and displays output similar to what you see in the following figure:
Output window showing results of building the HelloWorld project.
If the build output concludes with the statement BUILD SUCCESSFUL, congratulations! You have successfully compiled your program!
If the build output concludes with the statement BUILD FAILED, you probably have a syntax error in your code. Errors are reported in the Output window as hyper-linked text. You double-click such a hyper-link to navigate to the source of an error. You can then fix the error and once again choose Build | Build Main Project.
When you build the project, the bytecode file HelloWorldApp.class is generated. You can see where the new file is generated by opening the Files window and expanding the Hello World App/build/classes/helloworldapp node as shown in the following figure.
Files window, showing the generated .class file.
Now that you have built the project, you can run your program.
Run the Program
From the IDE's menu bar, choose Run | Run Main Project.
The next figure shows what you should now see.
The program prints "Hello World!" to the Output window (along with other output from the build script).
Congratulations! Your program works!
Continuing the Tutorial with the NetBeans IDE
The next few pages of the tutorial will explain the code in this simple application. After that, the lessons go deeper into core language features and provide many more examples. Although the rest of the tutorial does not give specific instructions about using the NetBeans IDE, you can easily use the IDE to write and run the sample code. The following are some tips on using the IDE and explanations of some IDE behavior that you are likely to see:
•Once you have created a project in the IDE, you can add files to the project using the New File wizard. Choose File | New File, and then select a template in the wizard, such as the Empty Java File template.
•You can compile and run an individual file (as opposed to a whole project) using the IDE's Compile File (F9) and Run File (Shift-F6) commands. If you use the Run Main Project command, the IDE will run the file that the IDE associates as the main class of the main project. Therefore, if you create an additional class in your HelloWorldApp project and then try to run that file with the Run Main Project command, the IDE will run the HelloWorldApp file instead.
•You might want to create separate IDE projects for sample applications that include more than one source file.
•As you are typing in the IDE, a code completion box might periodically appear. You can either ignore the code completion box and keep typing, or you can select one of the suggested expressions. If you would prefer not to have the code completion box automatically appear, you can turn off the feature. Choose Tools | Options, click the Editor tab, and clear the Auto Popup Completion Window checkbox.
•If you try to rename the node for a source file in the Projects window, the IDE prompts you with the Rename dialog box to lead you through the options of renaming the class and the updating of code that refers to that class. Click Next to display the Refactoring window, which contains a tree view of changes to be made. Then click Do Refactoring to apply the changes. This sequence of clicks might seem unnecessary if you have just a single class in your project, but it is very useful when your changes affect other parts of your code in larger projects.
•For a more thorough guide to the features of the NetBeans IDE, see the NetBeans IDE Docs and Support page or explore the documentation available from the IDE's Help menu.
"Hello World!" for Microsoft Windows
It's time to write your first application! The following instructions are for users of Windows XP Professional, Windows XP Home, Windows Server 2003, Windows 2000 Professional, and Windows Vista. Instructions for other platforms are in "Hello World!" for Solaris OS and Linux and "Hello World!" for the NetBeans IDE.
If you encounter problems with the instructions on this page, consult the Common Problems (and Their Solutions).
•A Checklist
•Creating Your First Application
Create a Source File
Compile the Source File into a .class File
Run the Program
A Checklist
To write your first program, you'll need:
1.The Java SE Development Kit 6 (JDK 6)
You can download the Windows version now. (Make sure you download the JDK, not the JRE.) Consult the installation instructions.
2.A text editor
In this example, we'll use Notepad, a simple editor included with the Windows platforms. You can easily adapt these instructions if you use a different text editor.
These two items are all you'll need to write your first application.
Creating Your First Application
Your first application, HelloWorldApp, will simply display the greeting "Hello world!". To create this program, you will:
•Create a source file
A source file contains code, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files.
•Compile the source file into a .class file
The Java programming language compiler (javac) takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this file are known as bytecodes.
•Run the program
The Java application launcher tool (java) uses the Java virtual machine to run your application.
Create a Source File
To create a source file, you have two options:
•You can save the file HelloWorldApp.java on your computer and avoid a lot of typing. Then, you can go straight to Compile the Source File into a .class File.
•Or, you can use the following (longer) instructions.
First, start your editor. You can launch the Notepad editor from the Start menu by selecting Programs > Accessories > Notepad. In a new document, type in the following code:
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Be Careful When You Type
Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are case-sensitive, so you must capitalize consistently.
HelloWorldApphelloworldapp
Save the code in a file with the name HelloWorldApp.java. To do this in Notepad, first choose the File > Save As menu item. Then, in the Save As dialog box:
1.Using the Save in combo box, specify the folder (directory) where you'll save your file. In this example, the directory is java on the C drive.
2.In the File name text field, type "HelloWorldApp.java", including the quotation marks.
3.From the Save as type combo box, choose Text Documents (*.txt).
4.In the Encoding combo box, leave the encoding as ANSI.
When you're finished, the dialog box should look like this.
The Save As dialog just before you click Save.
Now click Save, and exit Notepad.
Compile the Source File into a .class File
Bring up a shell, or "command," window. You can do this from the Start menu by choosing Command Prompt (Windows XP), or by choosing Run... and then entering cmd. The shell window should look similar to the following figure.
A shell window.
The prompt shows your current directory. When you bring up the prompt, your current directory is usually your home directory for Windows XP (as shown in the preceding figure).
To compile your source file, change your current directory to the directory where your file is located. For example, if your source directory is java on the C drive, type the following command at the prompt and press Enter:
cd C:\java
Now the prompt should change to C:\java>.
Note: To change to a directory on a different drive, you must type an extra command: the name of the drive. For example, to change to the java directory on the D drive, you must enter D:, as shown in the following figure.
Changing directory on an alternate drive.
If you enter dir at the prompt, you should see your source file, as the following figure shows.
Directory listing showing the .java source file.
Now you are ready to compile. At the prompt, type the following command and press Enter.
javac HelloWorldApp.java
The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type dir to see the new file that was generated, as shown in the following figure.
Directory listing, showing the generated .class file
Now that you have a .class file, you can run your program.
If you encounter problems with the instructions in this step, consult the Common Problems (and Their Solutions).
Run the Program
In the same directory, enter the following command at the prompt:
java HelloWorldApp
The next figure shows what you should now see:
The program prints "Hello World!" to the screen.
Congratulations! Your program works!
If you encounter problems with the instructions in this step, consult the Common Problems (and Their Solutions).
"Hello World!" for Solaris OS and Linux
It's time to write your first application! These detailed instructions are for users of Solaris OS and Linux. Instructions for other platforms are in "Hello World!" for Microsoft Windows and "Hello World!" for the NetBeans IDE.
If you encounter problems with the instructions on this page, consult the Common Problems (and Their Solutions).
• A Checklist
• Creating Your First Application
Create a Source File
Compile the Source File into a .class File
Run the Program
A Checklist
To write your first program, you'll need:
1.The Java SE Development Kit 6 (JDK 6)
You can download the Solaris OS or Linux version now. (Make sure you download the JDK, not the JRE.) Consult the installation instructions .
2.A text editor
In this example, we'll use Pico, an editor available for many UNIX-based platforms. You can easily adapt these instructions if you use a different text editor, such as vi or emacs.
These two items are all you'll need to write your first application.
Creating Your First Application
Your first application, HelloWorldApp, will simply display the greeting "Hello world!". To create this program, you will:
•Create a source file
A source file contains code, written in the Java programming language, that you and other programmers can understand. You can use any text editor to create and edit source files.
•Compile the source file into a .class file
The Java programming language compiler (javac) takes your source file and translates its text into instructions that the Java virtual machine can understand. The instructions contained within this .class file are known as bytecodes.
•Run the program
The Java application launcher tool (java) uses the Java virtual machine to run your application.
Create a Source File
To create a source file, you have two options:
•You can save the file HelloWorldApp.java on your computer and avoid a lot of typing. Then, you can go straight to Compile the Source File.
•Or, you can use the following (longer) instructions.
First, open a shell, or "terminal," window.
A new terminal window.
When you first bring up the prompt, your current directory will usually be your home directory. You can change your current directory to your home directory at any time by typing cd at the prompt and then pressing Return.
The source files you create should be kept in a separate directory. You can create a directory by using the command mkdir. For example, to create the directory java in your home directory, use the following commands:
cd
mkdir java
To change your current directory to this new directory, you then enter:
cd java
Now you can start creating your source file.
Start the Pico editor by typing pico at the prompt and pressing Return. If the system responds with the message pico: command not found, then Pico is most likely unavailable. Consult your system administrator for more information, or use another editor.
When you start Pico, it'll display a new, blank buffer. This is the area in which you will type your code.
Type the following code into the new buffer:
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Be Careful When You Type
Type all code, commands, and file names exactly as shown. Both the compiler (javac) and launcher (java) are case-sensitive, so you must capitalize consistently.
HelloWorldApphelloworldapp
Save the code in a file with the name HelloWorldApp.java. In the Pico editor, you do this by typing Ctrl-O and then, at the bottom where you see the prompt File Name to write:, entering the directory in which you wish to create the file, followed by HelloWorldApp.java. For example, if you wish to save HelloWorldApp.java in the directory /home/jdoe/java, then you type /home/jdoe/java/HelloWorldApp.java and press Return.
You can type Ctrl-X to exit Pico.
Compile the Source File into a .class File
Bring up another shell window. To compile your source file, change your current directory to the directory where your file is located. For example, if your source directory is /home/jdoe/java, type the following command at the prompt and press Return:
cd /home/jdoe/java
If you enter pwd at the prompt, you should see the current directory, which in this example has been changed to /home/jdoe/java.
If you enter ls at the prompt, you should see your file.
Results of the ls command, showing the .java source file.
Now are ready to compile the source file. At the prompt, type the following command and press Return.
javac HelloWorldApp.java
The compiler has generated a bytecode file, HelloWorldApp.class. At the prompt, type ls to see the new file that was generated: the following figure.
Results of the ls command, showing the generated .class file.
Now that you have a .class file, you can run your program.
If you encounter problems with the instructions in this step, consult the Common Problems (and Their Solutions).
Run the Program
In the same directory, enter at the prompt:
java HelloWorldApp
The next figure shows what you should now see.
The output prints "Hello World!" to the screen.
Congratulations! Your program works!
A Closer Look at the "Hello World!" Application
Now that you've seen the "Hello World!" application (and perhaps even compiled and run it), you might be wondering how it works. Here again is its code:
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
The "Hello World!" application consists of three primary components: source code comments, the HelloWorldApp class definition, and the main method. The following explanation will provide you with a basic understanding of the code, but the deeper implications will only become apparent after you've finished reading the rest of the tutorial.
Source Code Comments
The following bold text defines the comments of the "Hello World!" application:
/**
* The HelloWorldApp class implements an application that
* simply prints "Hello World!" to standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
Comments are ignored by the compiler but are useful to other programmers. The Java programming language supports three kinds of comments:
/* text */
The compiler ignores everything from /* to */.
/** documentation */
This indicates a documentation comment (doc comment, for short). The compiler ignores this kind of comment, just like it ignores comments that use /* and */. The javadoc tool uses doc comments when preparing automatically generated documentation. For more information on javadoc, see the JavadocTM tool documentation .
// text
The compiler ignores everything from // to the end of the line.
The HelloWorldApp Class Definition
The following bold text begins the class definition block for the "Hello World!" application:
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
}
}
As shown above, the most basic form of a class definition is:
class name {
. . .
}
The keyword class begins the class definition for a class named name, and the code for each class appears between the opening and closing curly braces marked in bold above. Chapter 2 provides an overview of classes in general, and Chapter 4 discusses classes in detail. For now it is enough to know that every application begins with a class definition.
The main Method
The following bold text begins the definition of the main method:
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!"); //Display the string.
}
}
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above. You can name the argument anything you want, but most programmers choose "args" or "argv".
The main method is similar to the main function in C and C++; it's the entry point for your application and will subsequently invoke all the other methods required by your program.
The main method accepts a single argument: an array of elements of type String.
public static void main(String[] args)
This array is the mechanism through which the runtime system passes information to your application. For example:
java MyApp arg1 arg2
Each string in the array is called a command-line argument. Command-line arguments let users affect the operation of the application without recompiling it. For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:
-descending
The "Hello World!" application ignores its command-line arguments, but you should be aware of the fact that such arguments do exist.
Finally, the line:
System.out.println("Hello World!");
uses the System class from the core library to print the "Hello World!" message to standard output. Portions of this library (also known as the "Application Programming Interface", or "API") will be discussed throughout the remainder of the tutorial.
No comments:
Post a Comment