Tuesday 12 November 2013

Writing your first program

It has become a convention to write a program that prints "Hello, World" to the screen as your first program in any programming language. So let's just stick to it. I'm assuming that you've gone thru steps in the previous step, if not you might have some problems writing the program. Open up BlueJ and create a new project. You can choose any name you want, let's say "Project0". Then create a new class and name it "Main". The word Main is a convention that specifies this class is the starting class of your application, even though it may not be. However, it's always good to stick to standard naming conventions. When you double click open your created class you'll probably see that BlueJ has already written some stuff for you. At this stage we'll just ignore everything it says and delete all lines in this class and copy-paste the following code:


class Main {

  public static void main(String[] args) {

    System.out.println("Hello, World!");

  }
} 

Name of the class has to be the same as the one you gave when creating it.

 public static void main(String[] args) 
is called the entry to point to the program. In other words, this is the place where your program will start executing code. Those keywords will always be the same, this way JVM (Java virtual machine) will always know where to start executing the program. Finally, as you've probably guessed
 System.out.println("Hello, World!"); 
will print Hello, World! to the screen, to the standard terminal output to be more precise. This is a very important line of code to remember, because you'll be using it countless number of times to print something to terminal, mainly to know the state of your program, i.e. what's going on in the program.

No comments:

Post a Comment