Java syntax

From Wikipedia, the free encyclopedia

This is an old revision of this page, as edited by Mzanime (talk | contribs) at 06:10, 9 March 2006 (no merge). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

The syntax of the Java programming language is a set of rules that defines how a Java program will be 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 java.lang.Object.

Simple data types

Integers

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

Floating-points

float    32-bit signed
double   64-bit signed
  • Floating-point math never throws an exception
  • Dividing by 0 equals Inf (Infinity)
  • Dividing by Inf equals 0

Characters

char     16-bit unicode

Booleans

boolean  true and false (only two possible values)
  • Can't represent false as 0 or null
  • Can't represent true as nonzero
  • Can't cast from boolean to non-boolean, or vice versa

Wrapper Classes

Integer
Long
Float
Double
Boolean
Character
  • Can be used to convert values from one type to another
  • Can be used to pass simple data types by reference

Misc

  • A simple data type always uses the same amount of memory, regardless of compiler, processor, or platform.
  • 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]*
Long             245L, [0..9]*

Floating-points

Exponent         419E-2, 72E3
Float            23.5F,  17.2f
Double           8.75D,  5.6d

Characters

\u275            \u[0..9]*  (hexadecimal unicode character)

Tab              \t
Back space       \b
Carriage return  \r
Form feed        \f
Backslash        \\
Single quote     \'
Double quote     \"

Strings

String

  • String objects are read-only
  • String objects must be initialized when created
  • When the compiler encounters a series of characters enclosed in double quotes, it creates a String object
  • "+" is overloaded for use in string concatenation
String str1 = "alpha"; 
String str2 = new String("alpha");

StringBuffer

  • StringBuffer objects can be edited
  • Neither String nor StringBuffer are a descendant of one another
StringBuffer str1 = "beta";
StringBuffer str2 = new StringBuffer("beta");
StringBuffer str3 = new StringBuffer(50);

Arrays

  • Java implicitly creates an array class for each class that is defined, and for the simple data types.
  • All array classes descend from the class Object, and mirror the hierarchy of the classes they contain.
// Declare the array
SomeClass[] myArray;

// Create a reference for each element
myArray = new SomeClass[10];

// Or Combine the declaration and reference 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 Java 5, 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 哈嘍世界 {
    private String 文本 = "哈嘍世界";
}

Operators

Arithmetic

Binary operators

+     Addition
-     Subtraction
*     Multiplication
/     Division
%     Modulus; returns the integer remainder

Unary operators

-     Unary negation (reverses the sign)
++    Increment (can be prefix or postfix)
--    Decrement (can be prefix or postfix)

Assignment

=     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

==    Equal
!=    Not equal
>     Greater than
>=    Greather than or equal to
<     Less than
<=    Less than or equal to

Conditional

? :   Ternary comparison operator

      condition ? val1 : val2   (Evaluates val1 if condition is true; otherwise, evaluates val2)

Boolean

  • Short-circuit logical operations
  • Evaluates the minimal number of expressions necessary
  • Partial evaluation (rather than full evaluation)
&&    and
||    or
!     not (logical negation)

Bitwise

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

<<    Shift left  (zero fill)
>>    Shift right (sign-propogating); copies of the leftmost bit (sign bit) are shifted in from the left.
>>>   Shift right (zero fill)

     For positive numbers, >> and >>> yield the same result.

Unary operators

~    Not (inverts the bits)

String

=    Assignment
+    Concatenation

Control structures

If ... else

if (expr) {
    statements;
}
else if (expr) {
    statements;
}
else {
    statements;
}

Switch statement

switch (expr) {
    case VALUE: 
        statements;
        break;
    case VALUE: 
        statements;
        break;
    default:
        statements;
        break;
}
  • The expr value must be a byte, short, int, or char.
  • Each case value must be a unique literal value; variables cannot be used.

For loop

for (initial-expr; cond-expr; incr-expr) {
    statements;
}

New for loop for Iterable elements, added in J2SE 5.0. This iterates through Iterable Iterable_name, values are stored in variable variable_name.

 for (element_type variable_name: Iterable_name) {
     someFunction(variable_name);
 }

While loop

while (expr) {
    statements;
}

Do ... while

do {
    statements;
} while (expr);

Jump statements

  • break; - Break from the loop immediately.
  • continue; - Continue on to the next iteration of the loop.
  • break LABEL; - Jump to the statement immediately after the labeled statement (terminate the labeled statement).
  • continue LABEL; - Jump to the labeled statement (restart a labeled statement or continue execution of a labeled loop)
int sum = 0;
int i = 1;
while (i < 10) {
    if (i == 3) {
        continue;  // Skip the rest of this loop iteration.
    }
    sum += i;
                          
    if (sum > 15) {
        break;  // Exit the loop.
    }
}

Labels

  • Consists of an identifier followed by a colon
  • Used to identify the statement or block of code that the jump statements refer to
  • If the label is omitted, the jump statements refer to the innermost enclosing loop

Examples

  • LABEL1: statement;
  • LABEL2: { statements; }

Objects

Data members

  • final - value cannot be changed. Must be initialized.
  • static - belongs to the class, rather than to an instance of the class.
  • sychronized - only one object or class can access the data at a time (causes the object to be locked).
  • transient - not a part of the persistent state of an object. Should not be saved and later restored.
  • volatile - informs the compiler that it may be accessed by separate threads asynchronously.

Constants

  • final - use to declare a data member as a constant value.

Global constants

class MyClass {
    public static final int x = 10;
}

Static Initializers

static int i;
static { i = 20; } // a block of code
  • Use after the declaration of the static data.

Methods

  • abstract - the method is undefined in the class, and must be defined by any concrete subclass that will be instantiated.
  • final - the method cannot be redefined in a subclass (non-dynamic). The compiler may expand the method (similar to an inline function) if the method is small enough.
  • native - the method links to native machine-dependent code. Declared without a body. Cannot be abstract.
  • static - belongs to the class, rather than to an instance of the class.
  • sychronized - only one object or class can access the method at a time (causes the class to be locked).
  • Can't override an abstract method with another abstract method.
  • A private method can't be abstract.
  • All methods are implicitly virtual, and can be redefined in a child class, unless they are declared as final.

Constructors

  • When possible, the object should be a valid, meaningful object once it is constructed, as opposed to relying on an Init method.
  • Copy constructor: accepts an object of it's own type as a parameter and copies the data members.
  • The implicit default constructor is only available if no explicit constructors are defined.
  • Constructors can be overloaded.
  • The first statement in a subclass constructor may invoke a superclass constructor: super(...);
  • If there is no explicit call to the superclass constructor, the default superclass constructor will be called.
  • The first statement in a subclass constructor may invoke another subclass constructor: this(...);

Finalize method

  • Performs cleanup when the object goes out of scope; useful for closing resources.
  • The finalize method is called before the garbage collector frees the object; the object is not immediately freed afterwards.
  • 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 interpreter 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 protected.
protected void finalize() { ... }

Classes

Class access

  • public - accessible outside the package in which it's defined.
  • default - accessible only within the package in which it's defined.

Member access

  • public - accessible by any class.
  • protected - accessible within the class and by any derived class.
  • private - accessible only within the class.
  • default - accessible by any class within the package.
  • Can't override a public method to protected or private (can't make it more private than it already is).
  • Can override a protected method to public.
  • Can't override a private or final method (causes a private method to be redefined in the subclass).

Inheritance

class ChildClass extends ParentClass { ... }  // ChildClass inherits from ParentClass
  • The default parent of a class is class Object.
  • A class can only extend a single parent class (no multiple inheritance).

Abstract classes

abstract class ClassA {
    abstract ... functName(...);
    ...
}
  • A class is abstract if it contains one or more abstract methods.
  • Abstract classes cannot be instantiated.
  • Derived classes can be instantiated if they define a method for any abstract methods inherited.

Scope

  • this - reference to the current subclass (assumed by default) (i.e. this.someMethod()).
  • super - reference to the parent class (i.e. super.someMethod()).

Interfaces

An interface is like a class with no implementation details. Its only purpose is to define how a set of classes will be used. Classes that implement a common interface can be used somewhat interchangeably. 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 data. Interface methods are abstract by default (unimplemented), and interface data is static and final by default. If an interface is public, it must be in it's own .java file.

Interfaces are the result of compromise. The designers of Java decided not to support full multiple inheritance because of the difficulty of C++'s multiple inheritance. By separating interface from implementation, interfaces offer much of the benefit of multiple inheritance with less complexity. The price of no multiple inheritance is 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

A class can implement one or more interfaces, in addition to extending another class.

interface MyInterface {
    void foo();
}

interface Interface2 {
    void bar();
}

class MyClass implements MyInterface {
    void foo() {...}
    ...
}

class ChildClass extends ParentClass implements MyInterface, Interface2 {
    void foo() {...}
    void bar();
    ...
}

In the following example...

public interface Deleteable {
    void delete();
}

...any class that implements the Deleteable interface must have a method named delete() that has no parameters and a void return type. The exact 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 {
    // This method satisfies the Deleteable interface
    public void delete() {
        // Code implementation goes here
    }
    public void someOtherMethod() {
    }
}
public void deleteAll(Deleteable[] list) {
    for (int i = 0; i < list.length; i++) {
        list[i].delete();
    }
}

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

An interface can extend another interface.

interface ChildInterface extends ParentInterface {
    ...
}

A class that implements the resulting interface must define the combined set of methods.

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

Misc

  • Clone() method allocates and copies a new object. Returns the object as class Object.

Input/Output

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 {
    public static void main(String[] args) {...}
    ...
}

Applets

Main article: Java applet
  • Java code that runs in a web browser, in a designated display area
  • init and destroy are only called once, but start and stop are called as many times as the user visits the web page.
// MyApplet.java

import java.applet.*;
...

public class MyApplet extends Applet {
    init() {...}     // 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.
}
<!-- MyApplet.html -->
...
<applet code="MyApplet" width=200 height=200>
</applet>
...

Embedding the applet tag

  • The HTML applet tag can be embedded in the applet source code.
  • Inclusion of the applet tag allows the applet to be run directly by a simple applet viewer, without the need for an .html file.
  • Typically, the applet tag immediately follows the import statements.
  • It must be enclosed by /* */ comments.
// MyApplet.java
...
/*
<applet code="MyApplet" width="200" height="200">
</applet> 
*/
...

Servlets

Main article: Java servlet
  • Java code that runs on a web server, with the output (generally HTML or XML) typically sent to a web browser.
  • Servlets are the Java equivalent to CGI programming.

JSP (JavaServer Pages)

Main article: JSP
  • Java code that's embedded in a web page
  • JSP tags are processed on a web server; the resulting output (generally HTML or XML) is sent to the client.
  • JSP code is compiled into a Java Servlet before it's run.
  • JSP is an extension of Java Servlets.
  • The usage of JSP tags is comparable to the usage of PHP or ASP tags.

JSP tags

<%  java-expressions %>                          Scriptlet
<%= single-java-expression-to-output %>          Expression
<%! java-declaration-expressions %>              Declaration
<%@ [page, include, taglib] jsp-directive %>     Directive

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

  • James Gosling, Bill Joy, Guy Steele, and Gilad Bracha, The Java language specification, third edition. Addison-Wesley, 2005. ISBN 0321246780.
  • Patrick Naughton, Herbert Schildt. Java 2: The Complete Reference, third edition. The McGraw-Hill Companies, 1999. ISBN 0-07-211976-4
  • Vermeulen, Ambler, Bumgardner, Metz, Misfeldt, Shur, Thompson. The Elements of Java Style. Cambridge University Press, 2000. ISBN 0-521-77768-2

External links

Sun

Template:Major programming languages small