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 java.lang.Object
.
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
- 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
Byte
Short
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
- 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-point values
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 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
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 = new StringBuffer("beta"); StringBuffer str2 = 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. - Array classes have a read-only
length
attribute that contains the number of elements in the array. - Java arrays have a single dimension; support for mutli-dimension arrays is provided by the language, but multi-dimension arrays are implemented as arrays of arrays.
// 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 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 哈嘍世界 { private String 文本 = "哈嘍世界"; }
Operators
Arithmetic
+ Addition - Subtraction * Multiplication / Division % Modulus; returns the integer remainder
- 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 (evaluate operands from left-to-right until result can be determined)
- Evaluates the minimal number of expressions necessary
- Partial evaluation (rather than full evaluation)
&& 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 << 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 += Concatenation + assignment
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 innermost enclosing 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.
- Members that are declared private are not inherited by subclasses.
- Can't override a public method to protected or private (can't make access more restrictive than it already is).
- Can override a protected method to public.
- Can't override final methods.
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 of implementation).
Abstract classes
abstract class ClassA { abstract ... functName(...); ... }
- A class must be declared as abstract if it contains one or more abstract methods.
- Abstract classes cannot be instantiated.
- Non-abstract derived classes can be instantiated. A non-abstract class that extends an abstract class must override any inherited abstract methods with non-abstract methods.
Scope
this
– Reference to the current subclass (assumed by default) (i.e. this.someMethod()).super
– Reference to the parent class (i.e. super.someMethod()). 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 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 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 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
A class can implement one or more interfaces using the implements
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-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 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 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 { foo(); } public interface Interface2 extends MyInterface { bar(); } public class MyClass implements MyInterface { void foo() {...} void bar() {...} ... }
Misc
- The
clone()
method allocates and copies a new object. Classes must implement the marker interfaceCloneable
to indicate that they can be cloned.
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
- Java code that runs in a stand-alone virtual machine (not in a Web browser)
- A
main
method must be defined as follows:
public class MyClass { public static void main (String[] args) {...} ... }
Applets
- Java code that runs in a web browser, in a designated display area
init
anddestroy
are only called once, butstart
andstop
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. }
<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
- 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)
- 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
- Official Java home site
- The Java Language Specification, Third edition Authoritative description of the Java language
- Java SE 19 API Javadocs