Friday, May 6, 2011

3. Hello, world!



It's an old programming tradition to start learning a new language with a simple program that prints out 'Hello, world!' to the screen. So let us keep the tradition alive, and get down to the dirty work!
_____________________________________________________________________
NOTE: Before we start, I would like to make one thing clear: Java is a hard-core Object Oriented Programming language, and may seem a little daunting at first. But trust me, once you get the hang of it, it is VERY simple to do stuff.
_____________________________________________________________________


The Hello World Code:
[In BlueJ, click on 'New Class', and name it 'hello'. Double click on this new class, and replace all the bullsh*t with the code written below.]



Follow these steps to run your program:
1. Click on 'Compile'.
2. Close the class, and right-click on it.
3. Click on void main(String args[])

Breaking the Code- Line by Line:

Line 1- import java.io.*;
This line 'imports' properties of all the 'classes' that have been specified. Here, all the classes in the folder Java\io have been imported. '*' stands for 'ALL'.

Line 2- class hello
In Java, every program is stored within a 'class'. A class thus contains two kinds of assets:
1. Data
2. Methods/Functions (to work on the data)
IMPORTANT: The name of the file in which the program is saved should be the same as the name of the class.

Line 4- public static void main(String args[])
This is called a 'method declaration'. As we have discussed above, every program has two components: data, and methods. Here, a method called 'main' has been created.
As every program is split into a number of methods, there should be a specific method from where the program should start running. This is what the 'main' method is for. A program without a 'main' method will NOT work.
We'll come back to this line later.

Line 6- System.out.print("Hello, world!");
This line is self explanatory, i think.
It calls the 'print()' method located in the class: System\out.
The 'print()' method, in turn, prints out whatever you've written inside it to the screen.
____________________________________________________________________

Well, that was certainly a good start! We'll continue in the next post. Feel free to ask any questions you want to!

5 comments:

  1. give me some time... will definitely post it by tomorrow :D

    ReplyDelete
  2. if i omit 'static' from the method declaration why does it not work?

    ReplyDelete
  3. I still have to explain what 'static' means. Anyways, it is COMPULSARY to declare the main method of every program as static.
    You will understand the importance of this a little later.

    ReplyDelete