Java syntax: Difference between revisions

Content deleted Content added
m Keep, per RfD
Moved most of the syntax of "Java programming language" into this article
Line 1:
#REDIRECTThe 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 {{Javadoc:SE|package=java.lang|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
<pre>
Octal 0365, 0[0..7]*
Hexadecimal 0xF5, 0x[0..9, A..F]*
Long 245L, [0..9]*
</pre>
 
Floating-points
<pre>
Exponent 419E-2, 72E3
Float 23.5F, 17.2f
Double 8.75D, 5.6d
</pre>
 
Characters
<pre>
\u275 \u[0..9]* (hexadecimal unicode character)
 
Tab \t
Back space \b
Carriage return \r
Form feed \f
Backslash \\
Single quote \'
Double quote \"
</pre>
 
===International language support===
The language distinguishes between [[byte]]s and [[character (computing)|character]]s. Characters are stored internally using [[UCS-2]], although as of Java 5, 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:
 
public class 哈嘍世界 {
private String 文本 = "哈嘍世界";
}
 
==Operators==
===Arithmetic===
Binary operators
<pre>
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus; returns the integer remainder
</pre>
 
Unary operators
<pre>
- Unary negation (reverses the sign)
++ Increment (can be prefix or postfix)
-- Decrement (can be prefix or postfix)
</pre>
 
===Assignment===
<pre>
= 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
</pre>
 
===Comparison===
<pre>
== Equal
!= Not equal
> Greater than
>= Greather than or equal to
< Less than
<= Less than or equal to
</pre>
 
===Conditional===
<pre>
? : Ternary comparison operator
 
condition ? val1 : val2 (Evaluates val1 if condition is true; otherwise, evaluates val2)
</pre>
 
===Boolean===
*Short-circuit logical operations
*Evaluates the minimal number of expressions necessary
*Partial evaluation (rather than full evaluation)
 
<pre>
&& and
|| or
! not (logical negation)
</pre>
 
===Bitwise===
Binary operators
<pre>
& 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.
</pre>
 
Unary operators
<pre>
~ Not (inverts the bits)
</pre>
 
===String===
<pre>
= Assignment
+ Concatenation
</pre>
 
==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 <code>Iterable</code> elements, added in J2SE 5.0.
This iterates through <code>Iterable '''Iterable_name'''</code>, values are stored in variable '''<code>variable_name</code>'''.
 
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
*<code>LABEL1: statement;</code>
*<code>LABEL2: { statements; }</code>
 
==Interfaces and classes==
Java accommodates creation of interfaces which classes can implement. For example, an interface can be created like this:
 
public interface Deleteable {
void delete();
}
 
This code says that any class that implements the <code>'''interface Deleteable'''</code> will have a method named <code>'''delete()'''</code> that has no parameters and a <code>'''void'''</code> return type. The exact implementation and function of the method are determined by each class. There are many uses for this concept; for example, the following could be a class:
 
public class Fred implements Deleteable {
//Must include the delete() method to satisfy the Deleteable interface
public void delete() { //code implementation goes here
}
//Can also include other methods
public void doOtherStuff() {
}
}
 
Then, in another class, the following is possible
 
public void deleteAll(Deleteable[] list) {
for (int i = 0; i < list.length; i++) {
list[i].delete();
}
}
 
because any objects in the array are guaranteed to have the <code>delete()</code> method. The <code>'''Deleteable[]'''</code> array may contain references to <code>'''Fred'''</code> objects, and the <code>'''deleteAll()'''</code> method needn't differentiate between the <code>Fred</code> objects and other <code>Deleteable</code> objects.
 
The purpose is to separate the details of the implementation of the interface from the code that uses the interface. For example, the {{Javadoc:SE|java/util|Collection}} interface contains methods that any collection of objects might want to implement, like retrieving or storing objects, but a specific collection could be a resizeable array, a [[linked list]], or any of a number of different implementations.
 
The feature is a 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 give much of the benefit of multiple inheritance with less complexity. The price of no multiple inheritance of implementation 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.
 
==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 (computer science)|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]].
 
==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==
*[[Java programming language]]
*[[Java keywords]]
 
==References==
* [[James Gosling]], [[Bill Joy]], [[Guy L. Steele, Jr.|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===
*[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}}
 
{{Major programming languages small}}
 
[[Category:Java programming language]]