The syntax of Java is largely derived from C++. Unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built almost exclusively as an object-oriented language. All code is written inside a class, and everything is an object, with the exception of the primitive data types (integers, floating-point numbers, boolean values, and characters), which are not classes for performance reasons.
Unlike C++, Java does not support operator overloading or multiple inheritance for classes. This simplifies the language and aids in preventing potential errors and anti-pattern design.
Java uses similar commenting methods to C++. There are three different styles of comments: a single line style marked with two slashes (
//), a multiple line style opened with /* and closed with */, and the Javadoc commenting style opened with /** and closed with */. The Javadoc style of commenting allows the user to run the Javadoc executable to compile documentation for the program.Example:
Hello world
class HelloWorldApp { public static void main(String[] args) { System.out.println("Hello World!"); // Display the string. } }
To compare this to other programming languages see the list of hello world program examples.
Source files must be named after the public class they contain, appending the suffix
.java, for example, HelloWorldApp.java. It must first be compiled into bytecode, using a Java compiler, producing a file named HelloWorldApp.class. Only then can it be executed, or 'launched'. The Java source file may only contain one public class but can contain multiple classes with less than public access and any number of public inner classes.A
class that is not declared public may be stored in any .java file. 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 were the concatenation of the name of their enclosing class, a $, and an integer.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 class hierarchy is related to the name of the directory in which the .java file is located.The keyword
static in front of a method indicates a static method, which is associated only with the class and not with any specific instance of that class. Only static methods can be invoked without a reference to an object. Static methods cannot access any class members that are not also static.The keyword
void indicates that the main method does not return any value to the caller. If a Java program is to exit with an error code, it must call System.exit() explicitly.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 JavaBean do not use or need a main() method. A Java program may contain multiple classes that have main methods, which means that the VM needs to be explicitly told which class to launch from.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 alternative syntax for creating and passing the array.The Java launcher launches Java by loading a given class (specified on the command line or as an attribute in a JAR) 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 parameters to main are often passed by means of a command line.Printing is part of a 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 many methods for printing data to standard out, including println(String) which also appends a new line to the passed string.The string "Hello, world!" is automatically converted to a String object by the compiler.
A more comprehensive example
// OddEven.java import javax.swing.JOptionPane; public class OddEven { // "input" is the number that the user gives to the computer private int input; // a whole number("int" means integer) /* * This is the constructor method. It gets called when an object of the OddEven type * is being created. */ public OddEven() { /* * In most Java programs constructors can initialize objects with default values, or create * other objects that this object might use to perform its functions. In some Java programs, the * constructor may simply be an empty function if nothing needs to be initialized prior to the * functioning of the object. In this program's case, an empty constructor would suffice, even if * it is empty. A constructor must exist, however if the user doesn't put one in then the compiler * will create an empty one. */ } // This is the main method. It gets called when this class is run through a Java interpreter. public static void main(String[] args) { /* * This line of code creates a new instance of this class called "number" (also known as an * Object) and initializes it by calling the constructor. The next line of code calls * the "showDialog()" method, which brings up a prompt to ask you for a number */ OddEven number = new OddEven(); number.showDialog(); } public void showDialog() { /* * "try" makes sure nothing goes wrong. If something does, * the interpreter skips to "catch" to see what it should do. */ try { /* * The code below brings up a JOptionPane, which is a dialog box * The String returned by the "showInputDialog()" method is converted into * an integer, making the program treat it as a number instead of a word. * After that, this method calls a second method, calculate() that will * display either "Even" or "Odd." */ input = Integer.parseInt(JOptionPane.showInputDialog("Please Enter A Number")); calculate(); } catch (NumberFormatException e) { /* * Getting in the catch block means that there was a problem with the format of * the number. Probably some letters were typed in instead of a number. */ System.err.println("ERROR: Invalid input. Please type in a numerical value."); } } /* * When this gets called, it sends a message to the interpreter. * The interpreter usually shows it on the command prompt (For Windows users) * or the terminal (For *nix users).(Assuming it's open) */ private void calculate() { if (input % 2 == 0) { System.out.println("Even"); } else { System.out.println("Odd"); } } }
- 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.- 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 first creating an instance of theOddEvenclass, using thenewkeyword and theOddEven()constructor, and then assigning this instance to the variable.- The statement
number.showDialog();calls the calculate method. The instance ofOddEvenobject referenced by thenumberlocal variable is used to invoke the method and passed as the undeclaredthisparameter to thecalculatemethod. input = Integer.parseInt(JOptionPane.showInputDialog("Please Enter A Number"));is a statement that converts the type of String to the primitive data type int by using a utility function in the primitive wrapper class Integer.
No comments:
Post a Comment