Saturday, January 31, 2015

Hello World in Java

This post will help you to write your first Java program,the function of this program is to display Hello World on your command prompt.

Open Notepad And Type The Following

Open the notepad on your PC and type in the following code, don't worry if you don't understand it I have Explained every line below.

public class HelloWorld

  public static void main(String[]args)
   {

//Prints Hello Word

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

}

Saving the File


Now save the file as HelloWorld.java,remember to change the save as type to All Files otherwise  even though you add .java to the end the file will be saved as a .txt file so don't forget to change it.
Now that you have a .java file all you need to do is run the program,if you don't know how you can check my post on How to Compile And Run a Java Program.

Explanation

Line 1 (public class HelloWorld)

This line is where the class is declared, public class are keywords in the java library and HelloWorld is the name of the class.

Line 3 (public static void main(String[]args))

This line is declaring the main method , this method is what the JVM(Java Virtual Machine) will run, anything outside of this method will not work unless it has been referenced inside this method.The Key words have Meanings, these meanings can be found from the following site.


Line 8 (  System.out.println("Hello World");)

This line is part of the code that displays Hello World on the screen, This is an in-build method in java and don't forget the semi colon at the end it is the full stop in programming.This method can be used to print any form of text or numbers on the screen.

Other parts that are not explained

1.The parenthesis

    These represent the boundary of the method and class,that means the first parenthesis is opening the class and the second is opening the method third is closing the method and fourth is closing the class.

2.Comments
  
   Anything after // symbol in a given line is not read by compiler therefore you can add any comments like this so it will explain what the program does.There are a few other ways to add comments as well,You can find these from the site I have mentioned above.

3. The blank Lines

  These lines play no part in the program but it is to increase the readability of the program.If you want the whole code may be typed in one except the comments of course,but it is not advisable. 


Important Java is a Case sensitive language therefore your code should be identical to what I have given,I advice you not to copy paste but to type the code your self it will help you remember it better.

For more Information on this you can visit http://docs.oracle.com/javase/8/

No comments:

Post a Comment