Java syntax
1079500
223529308
2008-07-04T13:45:01Z
RCX
787358
/* Note about the "goto" statement */ wikilink
{{copy to wikibooks}}
{{TOCright}}
The '''[[syntax]]''' of the [[Java (programming language)|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, [[array]]s and [[string (computer science)|strings]] are not [[primitive types]]: they are reference types that can be assigned to {{Javadoc:SE|package=java.lang|java/lang|Object}}.
===Primitive data types===
{| class="wikitable"
|-
!colspan="2"|[[Integer (computer science)|Integer]] types
|-
!<tt>[[byte]]</tt>
|8-bit signed
|-
!<tt>[[Short integer|short]]</tt>
|16-bit signed
|-
!<tt>[[Integer (computer science)|int]]</tt>
|32-bit signed
|-
!<tt>[[Long integer|long]]</tt>
|64-bit signed
|}
;Notes:
* Integer [[primitive type]]s silently overflow. For example, adding one to <tt>Integer.MAX_VALUE</tt>, <math>2^{31}-1</math>, will result in <tt>Integer.MIN_VALUE</tt>, <math>-2^{31}</math>.
{| class="wikitable"
|-
!colspan="2"|[[Floating-point]] types
|-
!<tt>[[single precision|float]]</tt>
|32-bit signed
|-
!<tt>[[double precision|double]]</tt>
|64-bit signed
|}
;Notes:
* Floating-point math never throws exceptions
* Dividing a non-zero value by 0 equals infinity
* Dividing a non-infinite value by infinity equals 0
{| class="wikitable"
|-
!colspan="2"|Characters
|-
!<tt>[[Character (computing)|char]]</tt>
|16-bit unsigned [[Unicode]]
|}
{| class="wikitable"
|-
!colspan="2"|Boolean
|-
!<tt>boolean</tt>
|<tt>true</tt> or <tt>false</tt>
|}
;Notes:
* Unlike [[C (programming language)|C]], [[C++]], and similar languages, Java [[Boolean datatype#Java|can't represent false]] as 0 or null
* Can't represent true as non-zero
* Can't cast from boolean to a non-boolean primitive data type, or vice versa
;[[Primitive wrapper class]]es
*{{Javadoc:SE|java/lang|Byte}}
*{{Javadoc:SE|java/lang|Short}}
*{{Javadoc:SE|java/lang|Integer}}
*{{Javadoc:SE|java/lang|Long}}
*{{Javadoc:SE|java/lang|Float}}
*{{Javadoc:SE|java/lang|Double}}
*{{Javadoc:SE|java/lang|Boolean}}
*{{Javadoc:SE|java/lang|Character}}
;Uses:
* Can be used to convert values from one type to another
* Can be used to pass simple data types by reference
;Misc:
<!--I'd have to check, but I'm fairly certain the following statement is not true. The JLS and JVM specifications don't specify internal representation.
* A simple data type always uses the same amount of memory, regardless of compiler, processor, or platform.-->
* Passed by value to methods.
* Non-boolean primitive data types have an initial value of 0; booleans have an initial value of <tt>false</tt>. Wrapper classes (and all subtypes of Object) have an initial value of <tt>null</tt>.
===Literals===
{| class="wikitable"
|-
!colspan="2"|Integers
|-
![[octal]]
|<tt>0365, 0[0..7]*</tt>
|-
![[hexadecimal]]
|<tt>0xF5, 0x[0..9, A..F, a..f]*</tt>
|-
![[decimal]]
|<tt>245, [1..9][0..9]*</tt>
|-
!colspan="2"|[[Floating-point]] values
|-
!float
|<tt>23.5F, 23.5f; 1.72E3F, 1.72E3f, 1.72e3F, 1.72e3f</tt>
|-
!double
|<tt>23.5, 23.5D, 23.5d; 1.72E3, 1.72E3D, ...</tt>
|-
!colspan="2"|Character literals
|-
!char
|<tt>'a', 'Z', '\u0231'</tt>
|-
!colspan="2"|String literals
|-
!String
|<tt>"Hello, world"</tt>
|-
!colspan="2"|Characters escapes in strings
|-
![[Unicode]] character
|<tt>\u</tt> followed by the hexadecimal unicode code point
|-
![[Tab]]
|<tt>\t</tt>
|-
![[Backspace]]
|<tt>\b</tt>
|-
![[Carriage return]]
|<tt>\r</tt>
|-
![[Form feed]]
|<tt>\f</tt>
|-
![[Backslash]]
|<tt>\\</tt>
|-
![[Single quote]]
|<tt>\'</tt>
|-
![[Double quote]]
|<tt>\"</tt>
|-
![[Line feed]]
|<tt>\n</tt>
|}
===Strings===
String
* {{Javadoc:SE|java/lang|String}} objects are [[Immutable object|immutable]]
* String objects must be initialized when created
* When the compiler encounters a [[string literal]] (a series of characters enclosed in double quotes), it creates a String object
* The "+" and "+=" operators are overloaded for use in string concatenation
<source lang="java">
String str1 = "alpha";
String str2 = new String("alpha");
</source>
[[StringBuffer and StringBuilder]]
* Because {{Javadoc:SE|java/lang|StringBuffer}} and {{Javadoc:SE|java/lang|StringBuilder}} objects are mutable, they are more flexible for building and modifying strings without object creation overhead. The difference between StringBuffer and StringBuilder is that StringBuffer is [[Thread safety|thread-safe]]; StringBuilder is not.
* Neither String nor StringBuffer are a descendant of one another
<source lang="java">
StringBuffer str1 = new StringBuffer("alpha");
str1.append("-meta");
str1.setCharAt(str1.indexOf("m"), 'b');
System.out.println(str1); //calls str1.toString() and prints
//"alpha-beta"
</source>
===Arrays===
* Java has array types for each type, including arrays of primitive types, class and interface types, as well as higher-dimensional arrays of array types.
* All elements of an array must descend from the same type.
* All array classes descend from the class <code>java.lang.Object</code>, and mirror the hierarchy of the types they contain.
* Array objects have a read-only <code>length</code> attribute that contains the number of elements in the array.
* Arrays are allocated at runtime, so the specified size in an array creation expression may be a variable (rather than a constant expression as in C).
* Java arrays have a single dimension. Multi-dimensional arrays are supported by the language, but are treated as arrays of arrays.
<source lang="java">
// Declare the array - name is "myArray", element type is references to "SomeClass"
SomeClass[] myArray = null;
// 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();
</source>
===International language support===
The language distinguishes between [[byte]]s and [[character (computing)|character]]s. Characters are stored internally using [[UCS-2]], although as of J2SE 5.0, the language also supports using [[UTF-16]] and its [[surrogate (Unicode)|surrogate]]s. 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:
<source lang="java">
public class 哈嘍世界 {
private String 文本 = "哈嘍世界";
}
</source>
==Operators==
===Arithmetic===
{| class="wikitable"
|-
!colspan="2"|[[Binary operator]]s
|-
!Syntax!!Meaning
|-
!<tt>+</tt>
|[[Addition]]
|-
!<tt>-</tt>
|[[Subtraction]]
|-
!<tt>*</tt>
|[[Multiplication]]
|-
!<tt>/</tt>
|[[Division (mathematics)|Division]]
|-
!<tt>%</tt>
|[[Modulo operation|Modulus]] (returns the integer remainder)
|-
!colspan="2"|[[Unary operator]]s
|-
!Syntax!!Meaning
|-
!<tt>-</tt>
|Unary negation (reverses the sign)
|-
!<tt>++</tt>
|Increment (can be prefix or postfix)
|-
!<tt>--</tt>
|Decrement (can be prefix or postfix)
|-
!<tt>!</tt>
|Boolean complement operator
|-
!<tt>~</tt>
|Bitwise inversion
|-
!<tt>(type)</tt>
|Casting
|}
===Assignment===
{| class="wikitable"
|-
!Syntax!!Meaning
|-
!<tt>=</tt>
|Assign
|-
!<tt>+=</tt>
|Add and assign
|-
!<tt>-=</tt>
|Subtract and assign
|-
!<tt>*=</tt>
|Multiply and assign
|-
!<tt>/=</tt>
|Divide and assign
|-
!<tt>%=</tt>
|Modulus and assign
|-
!<tt>&=</tt>
|[[Bitwise AND]] and assign
|-
!<tt>|=</tt>
|[[Bitwise OR]] and assign
|-
!<tt>^=</tt>
|[[Bitwise operation|Bitwise XOR]] and assign
|-
!<tt><<=</tt>
|Left shift (zero fill) and assign
|-
!<tt>>>=</tt>
|Right shift (sign-propagating) and assign
|-
!<tt>>>>=</tt>
|Right shift (zero fill) and assign
|}
===Comparison===
{| class="wikitable"
|-
!Syntax!!Meaning
|-
!<tt>==</tt>
|Equals
|-
!<tt>!=</tt>
|Not equal
|-
!<tt>></tt>
|Greater than
|-
!<tt>>=</tt>
|Greater than or equal to
|-
!<tt><</tt>
|Less than
|-
!<tt><=</tt>
|Less than or equal to
|-
!<tt>instanceof</tt>
|Instance of
|}
When used with reference types, the equality operators (<tt>==</tt> and <tt>!=</tt>) compare the reference values, not the contents of the referenced objects—the comparison tests whether the two references refer to the same object (or <code>null</code>), not whether the two objects have equivalent value. The {{Javadoc:SE|name=.equals(Object)|java/lang|Object|equals(java.lang.Object)}} method is used to compare the contents of objects. The <tt>instanceof</tt> operator is used to determine if an object is an instance of a class.
===Conditional expressions===
Conditional expressions use the compound <code>[[?:]]</code> operator. Syntax:
<source lang="java">condition ? expression1 : expression2</source>
This evaluates <code>condition</code>, and if it is <code>true</code> then the conditional expression has the value of <code>expression1</code>; otherwise the conditional expression has the value of <code>expression2</code>.
Example:
<source lang="java">String answer = (p < 0.05)? "reject" : "keep";</source>
This is equivalent to the following code fragment:
<source lang="java">
String answer;
if (p < 0.05) {
answer = "reject";
}
else {
answer = "keep";
}
</source>
===Boolean===
*Short-circuit logical operations (evaluate operands from left-to-right until result can be determined)
*Evaluates the minimal number of expressions necessary
*Partial evaluation (rather than full evaluation)
{| class="wikitable"
|-
!Syntax!!Meaning
|-
!<tt>&&</tt>
|AND (if the first operand is false, then the result of the expression is false and the second operand is not evaluated)
|-
!<tt>||</tt>
|OR (if the first operand is true, then the result of the expression is true and the second operand is not evaluated)
|-
!<tt>!</tt>
|NOT (logical negation)
|}
===[[Bitwise operation]]s===
{| class="wikitable"
|-
!colspan="2"|[[Binary operator]]s
|-
!<tt>&</tt>
|AND (can also be used as a boolean operator for full evaluation)
|-
!<tt>|</tt>
|OR (can also be used as a boolean operator for full evaluation)
|-
!<tt>^</tt>
|XOR
|-
!<tt><<</tt>
|Left shift (zero fill)
|-
!<tt>>></tt>
|Right shift (sign-propagating)
|-
!<tt>>>></tt>
|Right shift (zero fill)
|-
!colspan="2"|[[Unary operator]]s
|-
!<tt>~</tt>
|NOT (inverts the bits)
|}
===String operators===
{| class="wikitable"
!Syntax!!Meaning
|-
!<tt>+</tt>
|Concatenation
|-
!<tt>+=</tt>
|Concatenation and assignment
|}
==Control structures==
===If ... else===
<source lang="java">
if (expr) {
statements;
}
else if (expr) {
statements;
}
else {
statements;
}
</source>
*The expr value must evaluate to a boolean value so for example "if(String a1 == String a2)" will not evaluate to true even if they are equal, but instead it will compare values, not its boolean equivalent.
Instead use "if(String a1.equals(String a2))" or an instance of comparison.
And also a shortcut for assignment:
<source lang="java">
result = (boolean condition) ? (if boolean is true) : (if boolean is false);
</source>
eg.
<source lang="java">
int m1 = 5;
int m2 = 10;
...
int max = (m1 > m2) ? m1 : m2;
</source><ref>Adapted from [http://forum.java.sun.com/thread.jspa?threadID=339664&messageID=1395790 Re: the Question Mark in Java Syntax]</ref>
===Switch statement===
<source lang="java">
switch (expr) {
case VALUE1:
statements;
break;
case VALUE2:
statements;
break;
default:
statements;
break;
}
</source>
* The expr value must be a <code>byte</code>, <code>short</code>, <code>int</code>, or <code>char</code>.
* Each case value must be a unique literal value; variables cannot be used.
===For loop===
<source lang="java">
for (initial-expr; cond-expr; incr-expr) {
statements;
}
</source>
====For-each loop====
J2SE 5.0 added a new feature called the [http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html 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 explicitly declaring an iterator:
<source lang="java">
int sumLength(Set<String> stringSet) {
int sum = 0;
Iterator<String> itr = stringSet.iterator();
while (itr.hasNext())
sum += itr.next().length();
return sum;
}
</source>
The for-each loop greatly simplifies this method:
<source lang="java5">
int sumLength(Set<String> stringSet) {
int sum = 0;
for (String s : stringSet)
sum += s.length();
return sum;
}
</source>
This loop is read as, for each {{Javadoc:SE|java/lang|String}} in <tt>stringSet</tt>, add the length to <tt>sum</tt>.
===While loop===
<source lang="java">
while (expr) {
statements;
}
</source>
===Do ... while===
<source lang="java">
do {
statements;
} while (expr);
</source>
===Jump statements===
{| class="wikitable"
|-
!Syntax!!Meaning
|-
!<tt>break;</tt>
|Break from the innermost enclosing loop immediately.
|-
!<tt>continue;</tt>
|Continue on to the next iteration of the loop.
|-
!<tt>break LABEL</tt>
|Jump to the statement immediately after the labeled statement (terminate the labeled statement).
|-
!<tt>continue LABEL</tt>
|Jump to the labeled statement (restart a labeled statement or continue execution of a labeled loop)
|}
====Example:====
<source lang="java">
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.
}
}
</source>
<!-- Needs an example of labeled break, labeled continue -->
===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 (programming language)|label]] is omitted, the jump statements refer to the innermost enclosing loop
Examples
LABEL1: statement;
LABEL2: { statements; }
===Note about the "goto" statement===
Although the "<code>[[goto]]</code>" statement is a reserved keyword in Java it does not, however, 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:
* <code>abstract</code> – cannot be instantiated. Only interfaces and <code>abstract</code> classes may contain <code>abstract</code> methods. A concrete (non-<code>abstract</code>) subclass that extends an <code>abstract</code> class must override any inherited <code>abstract</code> methods with non-<code>abstract</code> methods. Cannot be <code>final</code>.
* <code>final</code> – cannot be subclassed. All methods in a final class are implicitly <code>final</code>. Cannot be <code>abstract</code>.
* <code>strictfp</code> – all floating-point operations within the class and any enclosed nested classes use strict floating-point semantics. Strict floating-point semantics guarantee that floating-point operations produce the same results on all platforms.
Note that Java classes do not need to be terminated by a semicolon (";"), which is required in C++ syntax.
====Inheritance====
// ChildClass inherits from ParentClass
class ChildClass extends ParentClass { ... }
* The default parent of a class is the <code>Object</code> class.
* A class can only extend a single parent class (no multiple inheritance of implementation).
====Scope====
* <code>this</code> – Reference to the current subclass (assumed by default) (i.e. <code>this.someMethod()</code>).
* <code>super</code> – Reference to the parent class (i.e. <code>super.someMethod()</code>). Can be used in a subclass to access inherited methods that the subclass has overridden or inherited fields that the subclass has hidden.
===Interfaces===
An [[interface (Java)|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 <code>public</code> and <code>abstract</code> by default (unimplemented), and interface fields are <code>public</code>, <code>static</code> and <code>final</code> 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 <code>implements</code> keyword, 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 non-<code>abstract</code> class that implements the <code>Deleteable</code> interface must define a non-abstract method named <code>delete</code> that has no parameters and a <code>void</code> 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 {
// 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 <code>delete()</code> method, the <code>deleteAll()</code> method needn't differentiate between the <code>Fred</code> objects or any other <code>Deleteable</code> objects.
====Extending interfaces====
An interface can extend one or more interfaces using the <code>extends</code> keyword.
interface ChildInterface extends ParentInterface, AnotherInterface {
...
}
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 Interface2 {
void foo() {...}
void bar() {...}
...
}
===Access modifiers===
Access modifiers determine which code may access classes and class members.
====Top level class access====
By default, Java classes are accessible only within their own [[Java package]]. This enables a package of classes to provide an API which performs functions behind the scenes. Hidden classes support the work of publicly accessible classes.
* default – accessible only within the package in which it's defined.
* <code>public</code> – extends access to classes outside the package
====Class member access====
''Class members'' are fields, methods, constructors and nested classes declared within the body of a class. In order of increasing scope of access, the access modifiers for class members are:
# <code>private</code> – accessible only within the class
# package-private (no modifier) – accessible to other classes in the same package
# <code>protected</code> – extends access to subclasses outside the package
# <code>public</code> – accessible by any class.
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 <code>public</code> method must be declared <code>public</code> and a <code>protected</code> 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 <code>protected</code> or <code>public</code> and a <code>protected</code> method can be declared as <code>public</code>.
===Fields===
In addition to the access modifiers, data fields may be declared with the following modifiers:
* <code>final</code> – the value cannot be changed. Must be initialized exactly once. A final field declared without an initializer is a ''blank final'' field—a <code>static</code> blank final field must be definitively initialized by a static initializer; a non-<code>static</code> blank final field must be initialized during the execution of each and every constructor. Cannot be <code>volatile</code>.
* <code>static</code> – belongs to the class, rather than to an instance of the class.
* <code>transient</code> – not a part of the persistent state of an object. The value should not be saved and later restored.
* <code>volatile</code> – informs the compiler that it may be accessed by separate threads asynchronously. Cannot be <code>final</code>.
====Constants====
Fields that are declared as both <code>static</code> and <code>final</code> are effectively constants; <code>static</code> means there is one occurrence of the field associated with the class, and <code>final</code> 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 { // a static initializer
squares = new int[count];
for (int i = 0; i < count; i++)
squares[i] = i * i;
}
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-<code>static</code>) 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:
* <code>abstract</code> – the method is undefined in the class, and must be defined by any concrete (non-<code>abstract</code>) subclass. Cannot be <code>static</code>, <code>final</code> or <code>native</code>.
* <code>final</code> – the method cannot be redefined in a subclass. For instance (non-<code>static</code>) methods, this allows the compiler to expand the method (similar to an inline function) if the method is small enough. Cannot be <code>abstract</code>.
* <code>native</code> – the method links to native machine-dependent code. Declared without a body. Cannot be <code>abstract</code>.
* <code>static</code> – belongs to the class, rather than to an instance of the class. Cannot be <code>abstract</code>.
* <code>strictfp</code> – all floating-point operations in the method and enclosed inner classes use strict floating-point semantics. Strict floating-point semantics guarantee that floating-point operations produce the same results on all platforms.
* <code>synchronized</code> – causes the current thread to acquire the lock for the associated object before executing the body of the method. If the lock is currently held by another thread, the current thread will block until the lock is released and the thread is able to obtain the lock. The associated object is the {{Javadoc:SE|java/lang|Class}} object for <code>static</code> methods and the object instance for non-<code>static</code> methods. While it is allowed to declare an <code>abstract</code> method as <code>synchronized</code>, it is meaningless to do so since synchronization is an aspect of the implementation, not the declaration, and abstract methods do not have an implementation.
Note that a <code>private</code> method can't be <code>abstract</code> and is implicitly <code>final</code>.
====Varargs====
Java SE 5.0 added syntactic support for methods with a variable number of arguments ([[varargs]]) [http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html], which simplifies the [[typesafe]] usage of methods requiring a variable number of arguments. The last parameter can be followed with <tt>...</tt>, and Java will box all the arguments into an array:
public void drawPolygon ({{Javadoc:SE|java/awt|Point}}... points) {…}
When calling the method, a programmer can simply separate the points by commas, without having to explicitly create an [[array]] of <code>Point</code> objects. Within the method, the points can be referenced as <tt>points[0]</tt>, <tt>points[1]</tt>, 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 been allocated. Typically, a constructor is invoked using the <code>new</code> keyword, although constructors can also be invoked using [[reflection (computer science)|reflection]] provided by the [[Java Platform, Standard Edition#java.lang.reflect|java.lang.reflect]] package.
* The access modifiers are the only modifiers that may be used for declaring constructors.
* When possible, the object should be a valid, meaningful object once it is constructed, as opposed to relying on a separate initialization method.
* By convention, a ''copy constructor'' is a constructor that accepts an object of its own type as a parameter and copies the data members.
* If no explicit constructor is defined, then the compiler provides an implicit empty default constructor that takes no parameters.
* Constructors can be overloaded.
* The first statement in a constructor may invoke a superclass constructor: <code>super(...);</code> or another constructor in the same class: <code>this(...);</code>
* If there is no explicit call to <code>super(...)</code> or <code>this(...)</code>, then the default superclass constructor <code>super();</code> is called before the body of the constructor is executed.
===Methods in the <code>Object</code> class===
Methods in the {{Javadoc:SE|java/lang|Object}} class are inherited, and thus shared in common by all classes.
====The <code>clone</code> method====
{{main|Clone (Java method)}}
The {{Javadoc:SE|java/lang|Object|clone()}} method returns a new object that is a copy of the current object. Classes must implement the [[marker interface]] {{Javadoc:SE|java/lang|Cloneable}} to indicate that they can be cloned.
====The <code>equals</code> method====
The {{Javadoc:SE|name=Object.equals(Object)|java/lang|Object|equals(java.lang.Object)}} method compares the object to another object and returns a <code>boolean</code> result indicating if the two objects are equal. Semantically, this method compares the contents of the objects whereas the equality comparison operator "<code>==</code>" compares the object references. The <code>equals</code> method is used by many of the data structure classes in the {{Javadoc:SE|java/util|package=java.util}} package. Some of these data structure classes also rely on the <code>Object.hashCode</code> method—see [[#The hashCode method|the <code>hashCode</code> method]] for details on the contract between <code>equals</code> and <code>hashCode</code>. Implementing equals() isn't always as easy as it seems, see '[http://www.angelikalanger.com/Articles/JavaSolutions/SecretsOfEquals/Equals.html Secrets of equals()]' for more information.
====The <code>finalize</code> method====
{{main|Finalizer}}
The {{Javadoc:SE|java/lang|Object|finalize()}} method is called exactly once before the [[garbage collection (computer science)|garbage collector]] frees the memory for object. A class overrides <code>finalize</code> to perform any clean up that must be performed before an object is reclaimed. Most objects do not need to override <code>finalize</code>.
There is no guarantee when the <code>finalize</code> method will be called, or the order in which the <code>finalize</code> method will be called for multiple objects. If the [[Java Virtual Machine|JVM]] exits without performing garbage collection, the OS may free the objects, in which case the <code>finalize</code> method doesn't get called.
The <code>finalize</code> method should always be declared <code>protected</code> to prevent other classes from calling the <code>finalize</code> method.
protected void finalize() throws Throwable { ... }
====The <code>getClass</code> method====
The {{Javadoc:SE|java/lang|Object|getClass()}} method returns the {{Javadoc:SE|java/lang|Class}} object for the class that was used to instantiate the object. The class object is the base class of [[reflection (computer science)|reflection]] in Java. Additional reflection support is provided in the <code>[[Java Platform, Standard Edition#java.lang.reflect|java.lang.reflect]]</code> package.
====The <code>hashCode</code> method====
The {{Javadoc:SE|java/lang|Object|hashCode()}} method returns an integer (<code>int</code>) that is used as a ''hash code'' for storing the object in an [[associative array]]. Classes that implement the {{Javadoc:SE|java/util|package=java.util|Map}} interface provide associative arrays and rely on the <code>hashCode</code> method. A good <code>hashCode</code> 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 <code>equals</code> and <code>hashCode</code> methods, there is an important contract between these two methods that must be maintained if the objects are to be inserted into a <code>Map</code>:
: For two objects ''a'' and ''b''
:* <code>a.equals(b) == b.equals(a)</code>
:* if <code>a.equals(b)</code> then <code>a.hashCode() == b.hashCode()</code>
In order to maintain this contract, a class that overrides the <code>equals</code> method must also override the <code>hashCode</code> method, and vice versa, so that <code>hashCode</code> is based on the same properties (or a subset of the properties) as <code>equals</code>.
A further contract that the map has with the object is that the results of the <code>hashCode</code> and <code>equals</code> 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.
Two equal objects must have the same hashcode. However, 2 different objects are NOT required to have different hashcodes.
====The <code>toString</code> method====
The {{Javadoc:SE|java/lang|Object|toString()}} method returns a {{Javadoc:SE|java/lang|String}} that contains a text representation of the object. The <code>'''''toString'''''</code> method is implicitly called by the compiler when an object operand is used with the string concatenation operators (<code>+</code> and <code>+=</code>).
====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 <code>synchronized</code> 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 <code>wait</code> and <code>notify</code> and <code>notifyAll</code> 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 (computer science)|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 <code>wait</code> methods=====
There are three overloaded versions of the <code>wait</code> method to support different ways to specify the timeout value: {{Javadoc:SE|name=wait()|java/lang|Object|wait()}}, {{Javadoc:SE|name=wait(long timeout)|java/lang|Object|wait(long)}} and {{Javadoc:SE|name=wait(long timeout, int nanos)|java/lang|Object|wait(long,%20int)}}. 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 [[millisecond]]s as a timeout; the third method takes the number of [[nanosecond]]s as a timeout, calculated as <code>1000000 * timeout + nanos</code>.
The thread calling <code>wait</code> 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:
# another thread calls the object's <code>notify</code> or <code>notifyAll</code> method (see [[#The notify and notifyAll methods|the notify methods]] below for details);
# another thread calls the thread's {{Javadoc:SE|name=interrupt()|java/lang|Thread|interrupt}} method; or
# a non-zero timeout that was specified in the call to <code>wait</code> expires.
The <code>wait</code> method must be called inside of a block or method synchronized on the object. This insures that there are no race conditions between <code>wait</code> and <code>notify</code>. 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 threads, it must acquire the object's mutex lock before continuing execution.
=====The <code>notify</code> and <code>notifyAll</code> methods=====
The {{Javadoc:SE|java/lang|Object|notify()}} and {{Javadoc:SE|java/lang|Object|notifyAll()}} methods remove one or more threads from an object's wait list and add them to the set of executable threads. <code>notify</code> removes a single thread from the wait list, while <code>notifyAll</code> removes all threads from the wait list. Which thread is removed by <code>notify</code> 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 <code>wait</code> and <code>notify</code>.
==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 (computing)|stream-based]] [[blocking I/O]]. This required a [[thread (computer science)|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===
*Java code that runs in a stand-alone [[Java virtual machine|virtual machine]] (not in a [[Web browser]])
*A <code>main</code> method must be defined as follows:
<source lang="java">public class MyClass {
public static void main(String[] args) {...}
...
}</source>
It could also be declared using [[varargs]]:
<source lang="java">public class MyClass {
public static void main(String... args) {...}
...
}</source>
===Applets===
{{main|Java applet}}
*Java code that runs in a [[web browser]], in a designated display area
*<code>init</code> and <code>destroy</code> are only called once, but <code>start</code> and <code>stop</code> 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 ag immediately follows the import statements.
*It must be enclosed by /* */ comments.
// MyApplet.java
...
/*
<applet code="MyApplet.class"> </applet>
*/
...
===Servlets===
{{main|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 applications.
===JSP (JavaServer Pages)===
{{main|JavaServer Pages}}
*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 [[Active Server Pages|ASP]] tags.
====JSP tags====
{| class="wikitable"
|-
!Syntax!!Meaning
|-
!<tt><% java-expressions %></tt>
|Scriptlet
|-
!<tt><%= single-java-expression-to-output %></tt>
|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, interface, method,
* or data member. This type of comment can be extracted by a utility
* to automatically create the [[Javadoc|documentation]] for a class.
*/
== Java keywords and reserved terms ==
{|
|
<tt>
abstract<br/>
assert</tt> (JDK 1.4)<tt><br/>
break<br/>
case<br/>
catch<br/>
class<br/>
const</tt> (not used)<tt><br/>
continue<br/>
default<br/>
do</tt>
||
<tt>
else<br/>
enum</tt> (JDK 1.5)<tt><br/>
extends<br/>
final<br/>
finally<br/>
for<br/>
goto</tt> (not used)<tt><br/>
if<br/>
implements<br/>
import</tt>
||
<tt>
instanceof<br/>
interface<br/>
native<br/>
new<br/>
package<br/>
private<br/>
protected<br/>
public<br/>
return<br/>
static</tt>
||
<tt>
strictfp<br/>
super<br/>
switch<br/>
synchronized<br/>
this<br/>
throw<br/>
throws<br/>
transient<br/>
try<br/>
volatile</tt>
||
<tt>
while<br/>
boolean<br/>
byte<br/>
char<br/>
double<br/>
float<br/>
int<br/>
long<br/>
short<br/>
void</tt>
||
<tt>
false<br/>
null<br/>
true<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</tt>
|}
==See also==
* [[Java (programming language)|Java programming language]]
* [[Java keywords]]
* [[Java Platform, Standard Edition]]
==References==
<references />
* [[James Gosling]], [[Bill Joy]], [[Guy L. Steele, Jr.|Guy Steele]], and [[Gilad Bracha]], ''The Java language specification'', third edition. Addison-Wesley, 2005. ISBN 0-321-24678-0.
* [[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===
* [http://java.sun.com/ Official Java home site]
* [http://java.sun.com/docs/books/jls/ The Java Language Specification, Third edition] Authoritative description of the Java language
* {{Javadoc:SE}}
* [http://java.sun.com/docs/books/tutorial/index.html The Java Tutorial]
* [http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html New features in J2SE 1.5.0]
{{Java (Sun)}}
[[Category:Java programming language]]
[[de:Java-Syntax]]
[[ja:Javaの文法]]