Opentopia Directory Encyclopedia Tools

Java syntax

Encyclopedia : J : JA : JAV : Java syntax


The syntax of the Java programming language is a set of rules that defines how a Java program is written and interpreted.

Data structures

Although the language has special syntax for them, arrays and strings are not primitive types: they are reference types that can be assigned to .

Simple data types

Integer types
byte 8-bit signed
short 16-bit signed
int 32-bit signed
long 64-bit signed

Floating-point types
float 32-bit signed
double 64-bit signed

Notes
Characters
char 16-bit unsigned Unicode

Boolean
boolean true or false

Notes
Primitive wrapper classes
Uses
  • Can be used to convert values from one type to another
  • Can be used to pass simple data types by reference
  • Misc
  • Passed by value to methods.
  • Initialized by default to 0, null, or false.
  • Literals

    Integers
    octal 0365, 0[0..7]*
    hexadecimal 0xF5, 0x[0..9, A..F, a..f]*
    decimal 245, [1..9][0..9]*
    Floating-point values
    float 23.5F, 23.5f; 1.72E3F, 1.72E3f, 1.72e3F, 1.72e3f
    double 23.5, 23.5D, 23.5d; 1.72E3, 1.72E3D, ...
    Character literals
    char 'a', 'Z'
    String literals
    String "Hello, world"
    Characters escapes in strings
    Unicode character \u followed by the hexadecimal unicode code point
    Tab \t
    Backspace \b
    Carriage return \r
    Form feed \f
    Backslash \
    Single quote \'
    Double quote \"
    Line feed \n

    Strings

    String

    String str1 = "alpha";
    String str2 = new String("alpha");
    
    StringBuffer and StringBuilder
    StringBuffer str1 = new StringBuffer("beta");
    StringBuffer str2 = new StringBuffer(50);
    

    Arrays

    // Declare the array - name is "myArray", element type is references to "SomeClass"
    SomeClass[] myArray;
    
    // Allocate the array
    myArray = new SomeClass[10]
    
    // Or Combine the declaration and array creation
    SomeClass[] myArray = new SomeClass[10]
    
    // Allocate the elements of the array (not needed for simple data types)
    for (int i = 0; i < myArray.length; i++)
    myArray[i] = new SomeClass();
    

    International language support

    The language distinguishes between bytes and characters. Characters are stored internally using UCS-2, although as of J2SE 5.0, the language also supports using UTF-16 and its surrogates. Java program source may therefore contain any Unicode character.

    The following is thus perfectly valid Java code; it contains Chinese characters in the class and variable names as well as in a string literal:

    public class 哈嘍世界 
    

    Operators

    Arithmetic

    Binary operators
    Syntax Meaning
    + Addition
    - Subtraction
    * Multiplication
    / Division
    % Modulus (returns the integer remainder)
    Unary operators
    Syntax Meaning
    - Unary negation (reverses the sign)
    ++ Increment (can be prefix or postfix)
    -- Decrement (can be prefix or postfix)

    Assignment

    Syntax Meaning
    = Assign
    += Add and assign
    -= Subtract and assign
    *= Multiply and assign
    /= Divide and assign
    %= Modulus and assign
    &= Bitwise AND and assign
    |= Bitwise OR and assign
    ^= Bitwise XOR and assign
    <<= Left shift (zero fill) and assign
    >>= Right shift (sign-propogating and assign)
    >>>= Right shift (zero fill) and assign

    Comparison

    Syntax Meaning
    == Equals
    != Not equal
    > Greater than
    >= Greater than or equal to
    < Less than
    <= Less than or equal to

    When used with reference types, the equality operators (== and !=) compare the reference values, not the contents of the referenced objects—the comparison tests whether the two references refer to the same object (or null), not whether the two objects have equivalent value. The method is used to compare the contents of objects.

    Conditional expressions

    Conditional expressions use the compound ?: operator. Syntax:

    condition ? expression1 : expression2
    
    This evaluates condition, and if it is true then the conditional expression has the value of expression1; otherwise the conditional expression has the value of expression2.

    Example:

    String answer = (p < 0.05)? "reject" : "keep";
    
    // This is equivalent to the following code fragment:
    String answer;
    if (p < 0.05)
    answer = "reject";
    else
    answer = "keep";
    

    Boolean

    Syntax Meaning
    && AND (if the first operand is false, then the result of the expression is false and the second operand is not evaluated)
    || OR (if the first operand is true, then the result of the expression is true and the second operand is not evaluated)
    ! NOT (logical negation)

    Bit wise

    Binary operators
    & AND (can also be used as a boolean operator for full evaluation)
    | OR (can also be used as a boolean operator for full evaluation)
    ^ XOR
    << Left shift (zero fill)
    >> Right shift (sign-propagating)
    >>> Right shift (zero fill)
    Unary operators
    ~ NOT (inverts the bits)

    String operators

    Control structures

    If ... else

    if (expr) 
    else if (expr) 
    else 
    

    Switch statement

    switch (expr) 
    

    For loop

    for (initial-expr; cond-expr; incr-expr) 
    

    For-each loop

    J2SE 5.0 added an new feature called the [for-each loop], which greatly simplifies the task of iterating through every element in a collection. Without the loop, iterating over a collection would require a explicitly declaring an iterator:
    public int sumLength(Set stringSet)
    
    
    The for-each loop greatly simplfies this method:

    public int sumLength(Set stringSet)
    
    
    This loop is read as, for each in stringSet, add the length to sum.

    While loop

    while (expr) 
    

    Do ... while

    do  while (expr);
    

    Jump statements

    Example:

    int sum = 0;
    int i = 1;
    while (i < 10) 
    sum += i;

    if (sum > 15) }

    Labels

    Examples
    LABEL1: statement;
    LABEL2: 
    

    Note about the \"goto\" statement

    The "goto" statement is a reserved keyword in Java, however, it does not have any function in the Java Programming Language.

    Objects

    Classes

    Java has nested classes that are declared within the body of another class or interface. A class that is not a nested class is called a top level class. An inner class is a non-static nested class.

    Classes can be declared with the following modifiers:

    Note that Java classes do not need to be terminated by a semicolon (";"), which is required in C++ syntax.

    Inheritance

    class ChildClass extends ParentClass   // ChildClass inherits from ParentClass
    

    Scope

    Interfaces

    An interface is an abstract class with no implementation details. Its purpose is to define how a set of classes will be used. Classes that implement a common interface can be used interchangeably within the context of the interface type. Interfaces also help to enforce the concept of abstraction—hiding the details of how a class is implemented.

    An interface can only contain abstract methods and static final fields. Interface methods are public and abstract by default (unimplemented), and interface fields are public, static and final by default.

    Java does not support full orthogonal multiple inheritance. Multiple inheritance in C++ has complicated rules to disambiguate fields and methods inherited from multiple superclasses and types inherited multiple times. By separating interface from implementation, interfaces offer much of the benefit of multiple inheritance with less complexity and ambiguity. The price of no multiple inheritance is some code redundancy; since interfaces only define the signature of a class but cannot contain any implementation, every class inheriting an interface must provide the implementation of the defined methods, unlike in pure multiple inheritance, where the implementation is also inherited.

    Java interfaces behave much like the concept of the Objective-C protocol.

    Implementing interfaces

    A class can implement one or more interfaces using the implements keyword, in addition to extending another class.

    interface MyInterface 
    
    interface Interface2 
    
    class MyClass implements MyInterface 
    ...
    }
    
    class ChildClass extends ParentClass implements MyInterface, Interface2 
    void bar();
    ...
    }
    
    In the following example,

    public interface Deleteable 
    
    any non-abstract class that implements the Deleteable interface must define a non-abstract method named delete that has no parameters and a void return type. The implementation and function of the method are determined by each class. There are many uses for this concept, for example:

    public class Fred implements Deleteable 
    public void someOtherMethod() 
    }
    
    public void deleteAll(Deleteable[] list) 
    }
    
    Because any objects in the above array are guaranteed to have the delete() method, the deleteAll() method needn't differentiate between the Fred objects or any other Deleteable objects.

    Extending interfaces

    An interface can extend one or more interfaces using the extends keyword.

    interface ChildInterface extends ParentInterface, AnotherInterface 
    
    A class that implements the resulting interface must define the combined set of methods.

    public interface MyInterface 
    
    public interface Interface2 extends MyInterface 
    
    public class MyClass implements Interface2 
    void bar() 
    ...
    }
    

    Access modifiers

    Access modifiers determine which code may access classes and class members.

    Top level class access

    Class member access

    Class members are fields, methods, constructors and nested classes declared within the body of a class. In order of increasing restrictions on access, the access modifiers for class members are: When overriding a method, the method access modifier can't be made more restrictive—to do so would break the interface contract of the parent class. Thus when overridden, a public method must be declared public and a protected method cannot be given default access. However, it is permissible to override a method to make it more accessible. Thus when overriding, a default (package) access method can be declared as protected or public and a protected method can be declared as public.

    Fields

    In addition to the access modifiers, data fields may be declared with the following modifiers:

    Constants

    Fields that are declared as both static and final are effectively constants; static means there is one occurrence of the field associated with the class, and final means that the field is assigned a value exactly once.

    Initializers

    Initializers are blocks of code that are executed at the same time as initializers for fields.

    Static initializers

    Static initializers are blocks of code that are executed at the same time as initializers for static fields. Static field initializers and static initializers are executed in the order declared. The static initialization is executed after the class is loaded.

    static int count = 20;
    static int[] squares;
    static 
    static int x = squares[5]  // x is assigned the value 25
    

    Instance initializers

    Instance initializers are blocks of code that are executed at the same time as initializers for instance (non-static) fields. Instance field initializers and instance initializers are executed in the order declared.

    Both instance initializers and instance field initializers are executed during the invocation of a constructor. The initializers are executed immediately after the superclass constructor and before the body of the constructor.

    Methods

    In addition to the access modifiers, methods may be declared with the following modifiers: Note that a private method can't be abstract and is implicitly final.

    Varargs

    Java 1.5.0 added Varargs [link], which simplifies the usage of methods requiring a variable amount of arguments. The last parameter can be followed with ..., and Java will box all the arguments into an array:

    public void drawPolygon(... points) 
    
    When calling the method, a programmer can simply separate the points by commas, without having to explicitly create an array of Point objects. Within the method, the points can be referenced as points[0], points[1], etc. If no points are passed, the array has a length of zero. To require the programmer to use a minimum number of parameters, those parameters can be specified before the variable argument:

    //A polygon needs at least 3 points.
    public void drawPolygon(Point p1, Point p2, Point p3, Point... otherPoints) 
    

    Constructors

    A constructor is called to initialize an object immediately after the object has be allocated. Typically, a constructor is invoked using the new keyword, although constructors can also be invoked using reflection provided by the java.lang.reflect package.

    The access modifiers are the only modifiers that may be used for declaring constructors.

    Methods in the Object class

    Methods in the class are inherited, and thus shared in common, by all classes.

    The clone method

    The method returns a new object that is a copy of the current object. Classes must implement the marker interface to indicate that they can be cloned.

    The equals method

    The method compares the object to another object and returns a boolean result indicating if the two objects are equal. Semantically, this method compares the contents of the objects whereas the equality comparison operator "==" compares the object references. The equals method is used by many of the data structure classes in the package. Some of these data structure classes also rely on the Object.hashCode method—see the hashCode method for details on the contract between equals and hashCode.

    The finalize method

    The method is called exactly once before the garbage collector frees the memory for object. A class overrides finalize to perform any clean up that must be performed before an object is reclaimed. Most objects do not need to override finalize.

    There is no guarantee when the finalize method will be called, or the order in which the finalize method will be called for multiple objects. If the JVM exits without performing garbage collection, the OS may free the objects, in which case the finalize method doesn't get called.

    The finalize method should always be declared protected to prevent other classes from calling the finalize method.

    protected void finalize() throws Throwable 
    

    The getClass method

    The method returns the object for the class that was used to instantiate the object. The class object is the base class of reflection in Java. Additional reflection support is provided in the java.lang.reflect package.

    The hashCode method

    The method returns an integer (int) that is used as a hash code for storing the object in an associative array. Classes that implement the interface provide associative arrays and rely on the hashCode method. A good hashCode implementation will return a hash code that is stable (does not change) and evenly distributed (the hash codes of unequal objects tend to be unequal and the hash codes are evenly distributed across integer values).

    Because associative arrays depend on both the equals and hashCode methods, there is an important contract between these two methods that must be maintained if the objects are to be inserted into a Map:

    For two objects a and b
    * a.equals(b) == b.equals(a)
    * if a.equals(b) then a.hashCode() == b.hashCode()
    In order to maintain this contract, a class that overrides the equals method must also override the hashCode method, and vice versa, so that hashCode is based on the same properties (or a subset of the properties) as equals.

    A further contract that the map has with the object is that the results of the hashCode and equals methods will not change once the object has been inserted into the map. For this reason, it is generally a good practice to base the hash function on immutable properties of the object.

    The toString method

    The method returns a that contains a text representation of the object. The toString method is implicitly called by the compiler when an object operand is used with the string concatenation operators (+ and +=).

    The wait and notify thread signaling methods

    Every object has two wait lists for threads associated with it. One wait list is used by the synchronized keyword to acquire the mutex lock associated with the object. If the mutex lock is currently held by another thread, the current thread is added to the list of blocked threads waiting on the mutex lock. The other wait list is used for signaling between threads accomplished through the wait and notify and notifyAll methods.

    Use of wait/notify allows efficient coordination of tasks between threads. When one thread needs to wait for another thread to complete an operation, or needs to wait until an event occurs, the thread can suspend its execution and wait to be notified when the event occurs. This is in contrast to polling, where the thread repeatedly sleeps for a short period of time and then checks a flag or other condition indicator. Polling is both more computationally expensive, as the thread has to continue checking, and less responsive since the thread won't notice the condition has changed until the next time to check.

    The wait methods
    There are three overloaded versions of the wait method to support different ways to specify the timeout value: , and . The first method uses a timeout value of zero (0), which means that the wait does not timeout; the second method takes the number of milliseconds as a timeout; the third method takes the number of nanoseconds as a timeout, calculated as 1000000 * timeout + nanos.

    The thread calling wait is blocked (removed from the set of executable threads) and added to the object's wait list. The thread remains in the object's wait list until one of three events occurs:

    1. another thread calls the object's notify or notifyAll method (see the notify methods below for details);
    2. another thread calls the thread's method; or
    3. a non-zero timeout that was specified in the call to wait expires.
    The wait method must be called inside of a block or method synchronized on the object. This insures that there are no race conditions between wait and notify. When the thread is placed in the wait list, the thread releases the object's mutex lock. After the thread is removed from the wait list and added to the set of executable thread, it must acquire the object's mutex lock before continuing execution.

    The notify and notifyAll methods
    The and methods remove one or more threads from an object's wait list and add them to the set of executable threads. notify removes a single thread from the wait list, while notifyAll removes all threads from the wait list. Which thread is removed by notify is unspecified and dependent on the JVM implementation.

    The notify methods must be called inside of a block or method synchronized on the object. This insures that there are no race conditions between wait and notify.

    Input / Output

    See also: Java Platform, Standard Edition#java.io and New I/O
    Versions of Java prior to J2SE 1.4 only supported stream-based blocking I/O. This required a thread per stream being handled, as no other processing could take place while the active thread blocked waiting for input or output. This was a major scalability and performance issue for anyone needing to implement any Java network service. Since the introduction of NIO (New I/O) in J2SE 1.4, this scalability problem has been rectified by the introduction of a non-blocking I/O framework (though there are a number of open issues in the NIO API as implemented by Sun).

    The non-blocking IO framework, though considerably more complex than the original blocking IO framework, allows any number of "channels" to be handled by a single thread. The framework is based on the Reactor Pattern.

    Running code

    Apps

    public class MyClass 
    ...
    }
    

    Applets

    // MyApplet.java
    
    import java.applet.*;
    
    public class MyApplet extends Applet      // Called when the browser first loads the applet.
    destroy()   // Called when the user quits the browser.
    start()     // Called when the applet starts running.
    stop()      // Called when the user leaves the web page,
    // reloads it, or quits the browser.
    }
    
    
    
    
    

    Embedding the applet tag

    // MyApplet.java
    ...
    /*
    
    
    */
    ...
    

    Servlets

    JSP (JavaServer Pages)

    JSP tags

    Miscellaneous

    Case sensitivity

    Java is case sensitive.

    Comments

    // Single-line comment
    
    /* Multiple-line
    comment */
    
    /**
    * These lines are used before the declaration of a class, method,
    * or data member.   This type of comment can be extracted by a utility
    * to automatically create the documentation for a class.
    */
    

    See also

    References

    External links

    Sun

     


    From Wikipedia, the Free Encyclopedia. Original article here. Support Wikipedia by contributing or donating.
    All text is available under the terms of the GNU Free Documentation License See Wikipedia Copyrights for details.

    Search Titles
    0123456789
    ABCDEFGHIJ
    KLMNOPQRST
    UVWXYZ?

    E-mail this article to:

    Personal Message: