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 declaredpublic
is 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
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 asargs
although 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 ofString
arguments. The effect of this alternate declaration is semantically identical (theargs
parameter is still an array ofString
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. TheString[] args
parameter is an array ofString
objects containing any arguments passed to the class. The parameter tomain
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 amain()
method. - The printing facility is part of the Java standard library: The
System
class defines a public static field calledout
. Theout
object is an instance of thePrintStream
class 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 . 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 thejavax.swing
package. - The
OddEven
class declares a singleprivate
field of typeint
namedinput
. Every instance of theOddEven
class has its own copy of theinput
field. The private declaration means that no other class can access (read or write) theinput
field. OddEven()
is apublic
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 theinput
field to the value entered into aJOptionPane
input dialog. The dialog returns aString
which is converted to anint
by theInteger.parseInt(String)
method.- The
calculate()
method is declared without thestatic
keyword. This means that the method is invoked using a specific instance of theOddEven
class. (The reference used to invoke the method is passed as an undeclared parameter of typeOddEven
namedthis
.) The method tests the expressioninput % 2 == 0
using theif
keyword to see if the remainder of dividing theinput
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. (Theinput
field can be equivalently accessed asthis.input
, which explicitly uses the undeclaredthis
parameter.) OddEven number = new OddEven();
declares a local object reference variable in themain
method namednumber
. This variable can hold a reference to an object of typeOddEven
. The declaration initializesnumber
by instantiating an instance of theOddEven
class using thenew
keyword and then calling theOddEven()
constructor to initialize the newly created object.- The statement
number.calculate();
calls the calculate method. The instance ofOddEven
object referenced by thenumber
local variable is used to invoke the method and passed as the undeclaredthis
parameter to thecalculate
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 byInteger.parseInt(String)
.
No comments:
Post a Comment