rss
Twitter Delicious Facebook Digg Stumbleupon Favorites

Simple Program

Hello World

Generally when you first start programming in any language, you'll start with the traditional Hello World example. That said, let's start building your first Java program. You guessed it, it's Hello World! Before starting this exercise, make sure you know how to compile and run Java programs.
Open your IDE and write the following text. Pay close attention to capitalization, as Java is case sensitive.
public class HelloWorld {  

public static void main(String[] args) {
System.out.println("Hello, world!");
}
}


Save it as HelloWorld.java. Again, make sure that the filename is the same case as the class name. Compile and run it:
javac HelloWorld.java

java HelloWorld
Your computer should display
Hello, world!

Line-by-line Analysis

The first line of the class,
public class HelloWorld {

declares a Java class named HelloWorld. This class is declared public - it is available to any other class. The next line,
public static void main(String[] args) {

begins a Java method named main. The main method is where Java will start executing the program. args is a method parameter which will contain the command line arguments used to run the program. The method must be both public and static for the program to run correctly. For more information on modifiers such as public and static, see Access Modifiers, though at this level, you don't need to know a whole lot about them.
The
System.out.println("Hello, world!");

statement sends the text Hello, world! to the console (with a line terminator). The final two braces mark the end of the main method and the end of the class.

Modifying the Program

Now, we will modify this program to print the first command line argument, if there is one, along with the greeting. For example, if you invoke the program as
java HelloWorld Dehan

it will print
Hello, Dehan!

Go back to the program, and modify it to read
public class Dehan {  

public static void main(String[] args) {
String who;
if (args.length > 0) {
who = args[0];
} else {
who = "World";
}
System.out.println("Hello, " + who + "!");
}
}
Run it again. It should display
Hello, Dehan!

or, if you do not pass a command line parameter, it will simply print
Hello, World!

0 comments:

Post a Comment

Powered by Blogger.