Thursday, March 22, 2007

Syntax

The syntax of Java is largely derived from C++. However, unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built from the ground up as an object oriented language. As a result, almost everything is an object and all code is written inside a class. The exceptions are the intrinsic data types (ordinal and real numbers, boolean values, and characters), which are not classes for performance reasons.

[edit] Hello world

For an explanation of the tradition of programming "Hello World" see: Hello world program.

[edit] Stand-alone application

This is a minimal usage of Java, but it does not demonstrate object-oriented programming well. No object is explicitly created since the keyword new is never used.

// Hello.java
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

To execute this program, one first saves the above code as a file named Hello.java. One then compiles it to bytecode:

$ javac Hello.java

which produces a file named Hello.class . This class is then launched with the java launcher (usually named java, java.exe, or some variant depending on the operating system).

$ java Hello
Hello, World!

$

The above example merits a bit of explanation.

  • All executable statements in Java are written inside a class, including stand-alone programs.
  • Source files are by convention named the same as the class they contain, appending the mandatory suffix .java. A class which is declared public is required to follow this convention. (In this case, the class is Hello, therefore the source must be stored in a file called Hello.java).
  • The compiler will generate a class file for each class defined in the source file. The name of the class file is the name of the class, with .class appended. For class file generation, anonymous classes are treated as if their name was the concatenation of the name of their enclosing class, a $, and an integer.
  • The keyword void indicates that the main method does not return any value to the caller.
  • The main method must accept an array of String objects. By convention, it is referenced as args although any other legal identifier name can be used. Since Java 5, the main method can also use variable arguments, in the form of public static void main(String... args), allowing the main method to be invoked with an arbitrary number of String arguments. The effect of this alternate declaration is semantically identical (the args parameter is still an array of String objects), but allows an alternate syntax for creating and passing the array.
  • The keyword static indicates that the method is a static method, associated with the class rather than object instances.
  • The keyword public denotes that a method can be called from code in other classes, or that a class may be used by classes outside the class hierarchy.
  • The Java launcher launches Java by loading a given class (specified on the command line) and starting its public static void main(String[]) method. Stand-alone programs must declare this method explicitly. The String[] args parameter is an array of String objects containing any arguments passed to the class. The parameter to main are often passed by means of a command line.
  • The method name "main" is not a keyword in the Java language. It is simply the name of the method the Java launcher calls to pass control to the program. Java classes that run in managed environments such as applets and Enterprise Java Beans do not use or need a main() method.
  • The printing facility is part of the Java standard library: The System class defines a public static field called out. The out object is an instance of the PrintStream class and provides the method println(String) for displaying data to the screen while creating a new line (standard out).
  • Standalone programs are run by giving the Java runtime the name of the class whose main method is to be invoked. For example, at a Unix command line java -cp . Hello will start the above program (compiled into Hello.class) from the current directory. The name of the class whose main method is to be invoked can also be specified in the MANIFEST of a Java archive (Jar) file (see Classpath).

An example that better demonstrates object-oriented programming:

// OddEven.java
import javax.swing.JOptionPane;

public class OddEven {
private int input;

public OddEven() {
input = Integer.parseInt(JOptionPane.showInputDialog("Please Enter A Number"));
}

public void calculate() {
if (input % 2 == 0)
System.out.println("Even");
else
System.out.println("Odd");
}

public static void main(String[] args) {
OddEven number = new OddEven();
number.calculate();
}
}
  • The import statement imports the JOptionPane class from the javax.swing package.
  • The OddEven class declares a single private field of type int named input. Every instance of the OddEven class has its own copy of the input field. The private declaration means that no other class can access (read or write) the input field.
  • OddEven() is a public constructor. Constructors have the same name as the enclosing class they are declared in, and unlike a method, have no return type. A constructor is used to initialize an object that is a newly created instance of the class. In this case, the constructor initializes the input field to the value entered into a JOptionPane input dialog. The dialog returns a String which is converted to an int by the Integer.parseInt(String) method.
  • The calculate() method is declared without the static keyword. This means that the method is invoked using a specific instance of the OddEven class. (The reference used to invoke the method is passed as an undeclared parameter of type OddEven named this.) The method tests the expression input % 2 == 0 using the if keyword to see if the remainder of dividing the input field belonging to the instance of the class by two is zero. If this expression is true, then it prints Even; if this expression is false it prints Odd. (The input field can be equivalently accessed as this.input, which explicitly uses the undeclared this parameter.)
  • OddEven number = new OddEven(); declares a local object reference variable in the main method named number. This variable can hold a reference to an object of type OddEven. The declaration initializes number by instantiating an instance of the OddEven class using the new keyword and then calling the OddEven() constructor to initialize the newly created object.
  • The statement number.calculate(); calls the calculate method. The instance of OddEven object referenced by the number local variable is used to invoke the method and passed as the undeclared this parameter to the calculate method.
  • For simplicity, error handling has been ignored in this example. Entering a value that is not a number will cause the program to crash. This can be avoided by catching and handling the NumberFormatException thrown by Integer.parseInt(String).

No comments: