Thursday, November 3, 2011

Hello World!

The first things most people who are just learning programming do is the pervasive "Hello World!" program. This short program's prevalence is so extensive because it demonstrates a language's structure and syntax. Specifically it shows how to print something to the screen and how to run a program.

Python


print "Hello World!"


C++


#include <iostream>
using namespace std;

int main()
{
    cout << "Hello World!" << endl;
}


Java


class HelloWorld {

    public static void main(String[] args) {

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

}

  • As you can see, Python's syntax is the simplest. There is no necessary structure, and all you have to do is type "print [thing to be printed (in single or double quotes)]"
  • C++'s syntax is more complicated, but it is by no means convoluted. 
    • In order to use cout (the C++ equivalent of print) you must include the iostream library. 
    • However, just including the library isn't enough. You have to tell the pre-processor which part of iostream it needs to look in to use cout. This is why we include the "using namespace std;" line. 
    • Finally, because C++ is an object-oriented program, every script you write must have a main function.  The convention is for main to have a return type of int and for all of the Also, every functions' code is contained within curly braces.
  • Java is based on C++, so it has a lot of the same conventions (such as ending every statement in a semi-colon). However, it is even more object-oriented (in that every script is a class, which creates an object when compiled). 
    • Because everything in Java is a class, everything that can be done in Java is accomplished through method calls to a class.
    • When printing, System is a class (first letter is upper case and multiple words written with camel case by convention), which contains an out method and a println method.
    • You'll recognize that main is still required, but now you have to declare it with public, static, and void, rather than just int. It also contains two parameters: String[] and args. 

No comments:

Post a Comment