Java Chapter 2 - Hello World
2.1 First Java Program
Below is the source code for a "Hello World" Java program. You can use any text editor to create it. Save the file as hello.java
hello.java |
// This
is a Java Hello World Program public class hello { public static void main (String[] args) { System.out.println("Hello World!"); } } |
Output Hello World! |
Compiling and Executing
Open a command prompt and go to the directory where you saved your hello.java file. If you saved this file in the Java directory under the E: prompt, then do the following:
E:\Java> javac
hello.java // this creates an intermediate file named
hello.class
E:\Java> java hello // this executes class file using the Java run-time
Important: The file name you use must be the same as the class name (hello).
Analyzing Hello World
All Java programs must be part of a class. The above program is
within the class named hello.
The Java application must have a main() method which is the entry point.
The content between the parenthesis, (String[] args), allows you to
pass command-line values to the application.
The word static is used to insure that the method will be accessible
even though no instances of the class exist.
The word void means that the main method does not return any value.
2.2
Printing Text
You can print text to the console screen with System.out.print or System.out.println. The latter puts a newline at the end of the output. The table below shows special characters (escape sequences) used in printing text.
Code | Output | Comments |
System.out.print("First Line\nSecond Line"); |
First Line Second Line |
\n is a newline |
System.out.print("1\t2\t3"); | 1 2 3 | \t is a tab |
System.out.print("C:\\"); | C:\ | You need to backslashes to print one |
System.out.print("\"To be or not to be\""); | "To be or not to be" | Since quotations are used to contain the text, you use \" to print a quotation |
2.3 Comments
Comments allow you to write messages (document) your program.
Comments are not compiled and do not affect how your program executes. There are two types of comments that can be used in Java
programs:
// Line comments can be added at the end of
any line
/* Block comments are good for
commenting long passages or for
commenting out a section of
code for testing. */
1. Create a program named face.java that prints the following:
/"""""\
| o o |
| & |
\ --- /