The First Program

Lets create our first program. It will just print to the console.

Copy the following code to a file and save the file as "HelloWorld.java"

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!! Welcome to Java.");
    }
}

Now go to console and compile the program with the following command :

javac HelloWorld.java

If the above command doesnt work, you need to configure the path and the classpath in your environment. Instructions for the same can be found here.

Once the program compiles successfully, it generates a .class file. In this case, it will be HelloWorld.class. This is actually the bytecode that JVM will execute. This is not an executable.

To run the program, use the following command :

java HelloWorld

This should print "Hello World!! Welcome to Java." on the console.

Understanding the program
1. The class name and the file name are identical i.e. HelloWorld. This is not a coincidence. By       convention, the name of the main class should match the name of the file that holds the program.

2. The line public class HelloWorld declares a new class with the name HelloWorld. All program activity occurs within a class in Java.

3. The line public static void main(String[] args) {
- The public keyword is the access modifier that allows the code to be accessed from outside the class it is declared in. If you change it to private, the code will compile but not run.
- The static keyword allows main() to be called without having to instantiate the class. If you remove this keyword, code will compile but not run.
- The void keyword tells the compiler that this method will not return any value. If you remove this, code will not compile as it is invalid method signature. If you change it to some other return type, say int, it will compile but not run.
- main() is the method called when Java application begins. Also Java is case-sensitive, so Main will not work instead of main.
- Lastly, String args[] stores all the command-line arguments that were passed while running the program into an array.

Try different permutations with the keywords as see the results.

You can find the source code for the program on github here.



Comments

Popular posts from this blog

Collection Framework - HashSet And LinkedHashSet class

Collection Framework - Cursors in Java

Hashed data structures