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
classwhich is declaredpublicis required to follow this convention. (In this case, the class isHello, 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
voidindicates that the main method does not return any value to the caller. - The main method must accept an array of
Stringobjects. By convention, it is referenced asargsalthough any other legal identifier name can be used. Since Java 5, the main method can also use variable arguments, in the form ofpublic static void main(String... args), allowing the main method to be invoked with an arbitrary number ofStringarguments. The effect of this alternate declaration is semantically identical (theargsparameter is still an array ofStringobjects), but allows an alternate syntax for creating and passing the array. - The keyword
staticindicates that the method is a static method, associated with the class rather than object instances. - The keyword
publicdenotes 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. TheString[] argsparameter is an array ofStringobjects containing any arguments passed to the class. The parameter tomainare 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 amain()method. - The printing facility is part of the Java standard library: The
Systemclass defines a public static field calledout. Theoutobject is an instance of thePrintStreamclass and provides the methodprintln(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 . Hellowill 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
JOptionPaneclass from thejavax.swingpackage. - The
OddEvenclass declares a singleprivatefield of typeintnamedinput. Every instance of theOddEvenclass has its own copy of theinputfield. The private declaration means that no other class can access (read or write) theinputfield. OddEven()is apublicconstructor. 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 theinputfield to the value entered into aJOptionPaneinput dialog. The dialog returns aStringwhich is converted to anintby theInteger.parseInt(String)method.- The
calculate()method is declared without thestatickeyword. This means that the method is invoked using a specific instance of theOddEvenclass. (The reference used to invoke the method is passed as an undeclared parameter of typeOddEvennamedthis.) The method tests the expressioninput % 2 == 0using theifkeyword to see if the remainder of dividing theinputfield 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. (Theinputfield can be equivalently accessed asthis.input, which explicitly uses the undeclaredthisparameter.) OddEven number = new OddEven();declares a local object reference variable in themainmethod namednumber. This variable can hold a reference to an object of typeOddEven. The declaration initializesnumberby instantiating an instance of theOddEvenclass using thenewkeyword and then calling theOddEven()constructor to initialize the newly created object.- The statement
number.calculate();calls the calculate method. The instance ofOddEvenobject referenced by thenumberlocal variable is used to invoke the method and passed as the undeclaredthisparameter to thecalculatemethod. - 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
NumberFormatExceptionthrown byInteger.parseInt(String).

No comments:
Post a Comment