Tuesday, November 26, 2013

"Hello Java", because one more just can't hurt

In your favorite editor, create file: HelloJava.java with the following contents:


class HelloJava{
        public static void main(String[] args){
                System.out.println("Hello Java");
        }

}

In the same directory as the file you just created, run the following commands:
>javac HelloJava.java
>java HelloJava


Here are the details explained:

class HelloJava{
    [...]
}

Java is entirely Object Oriented. This mean that everything must be declared inside a class. Unlike languages like PHP or C++ where Object Oriented code can be mixed where desired, in Java, Object Oriented Programming (OOP) is required.

public static void main(String[] args){
    [...]
}

This is a method. A method is like a function or procedure that belongs to a class. 
The public keyword says anybody can run this method. 
The static keyword means this method belongs to the class and is not copied to the object, so there will only ever be one copy of this method. 
void is the return type, this method does not return any data. 
main is the name of the method, this is the required name in this case. When you run a class with the java command it specifically looks for a static method of the name main
This method takes an array of String objects under the local name args.

>javac HellowJava.java

Tell the java compiler to compile this file.

>java HelloJava

Tell java to run the class HelloJava. Note this is the class name, NOT the file name.

No comments:

Post a Comment