Java syntax
Encyclopedia
The syntax
of the Java programming language
is a set of rules which defines how a Java program is written and interpreted.
The syntax is mostly derived from C
and C++
. Unlike C++, Java is almost exclusively an object-oriented language. There are no global functions or variables, all code belongs to class
es and all values are object
s. The only exception is the primitive type
s, which are not represented by a class instance due to performance reasons (though can be automatically converted to objects and vice-versa via autoboxing). Some features like operator overloading
or unsigned integer types are omitted to simplify the language and to avoid possible programming mistakes.
Java syntax is constantly improved in major JDK releases
. The last significant addition happened in J2SE 5.0, which introduced such features as generics and annotations. Project Coin will update the syntax in Java 7, and will introduce several small changes to the syntax.
. There are certain standard naming conventions
to follow when selecting names for elements. Identifiers in Java are case-sensitive
.
An identifier can contain:
An identifier cannot:
Integer literals are of
are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.
Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.
Inside of method bodies you can use the braces to create new scopes like so:
Traditional comments start with
End-of-line comments start with
Documentation comments are processed by Javadoc
tool to generate documentation from source files. This type of comments is identical to traditional comments, except it starts with
Whether it is a console or a graphical interface application the program must have an entrypoint of some sort. The entrypoint of the Java application is the
). The method must be
or C# it never returns a value and must return
A package is declared at the start of the file like this:
Classes must be placed in the files with the same name and java extension and put into nested folders corresponding to the package name. The above class myapplication.mylibrary.MyClass will have the following path: "myapplication/mylibrary/MyClass.java".
The
Since J2SE 5.0 it is allowed to do static imports, which allows to access members (fields and methods) defined in the imported class as
. However, there is no
mechanisms in Java, and there are no operations on pointers since Java does not support them. Another difference is that Java has an unsigned right shift operator (
.
if statements in Java are similar to those in C and use the same syntax:
Like C, else-if construction does not involve any special keywords, it is formed as a sequence of separate if-then-else statements:
Also, note that the ?:
operator can be used in place of simple if statement, for example
Switch statement
s in Java can use
. Starting with J2SE 7.0, it is possible to use Strings. Other reference types cannot be used in
Possible values are listed using
Code for each label ends with the
In the
In the
Like C, all three expressions are optional; the following loop will be infinite:
Enhanced
Enhanced
The
It is possible to break out of the outer loop using labels:
The
Labels can be specified in
The
Exceptions are managed within
The statements within the
If no
until a matching
The statements within the
The
. For the purposes of thread synchronization
the
To make a code block synchronized, it is preceded by the
lock, executes the block, then releases the lock. No threads may enter this block until the lock is released. Any non-null reference type may be used as the lock.
s in the source code, which can be turned on and off during execution for specific classes or packages. To declare an assertion the
Example:
A reference variable is
Due to the nature of the multi-dimensional arrays, sub-arrays may vary in length, so multi-dimensional arrays are not bound to be rectangular unlike C:
are fundamentals of an object-oriented language such as Java. They contain members that store and manipulate data. Classes are divided into top-level and nested. Nested classes include member classes, local classes and anonymous classes.
Accessing an instance member
Instance members can be accessed through the name of a variable.
Accessing a static class member
Static members are accessed by using the name of the class or any other type. This does not require the creation of a class instance. Static members are declared using the
The access modifiers, or inheritance modifiers, set the accessibility of classes, methods, and other members. Members marked as
The following table shows whether code within a class has access to the class or method depending on the accessing class location and the modifier for the accessed class or class member:
is a special method which is called when an object is initialized. Its purpose is to initialize the members of the object. The main differences between constructors and ordinary methods are that constructors are called only when an instance of the class is created and never return anything. Constructors are declared as common methods, but they are named after the class and no return type is specified:
Initializers are blocks of code which are executed when a class or an instance of a class is created. There are two kinds of initializers, static initializers and instance initializers.
The purpose of static initializers is to initialize static fields when the class is created. They are declared using
Any class is created by only once, therefore static initializers aren't called more than once. On the contrary, instance initializers are automatically called before the call to a constructor every time an instance of the class is created. Unlike constructors instance initializers can't take any arguments and generally they can't throw any checked exceptions (except in several special cases). Instance initializers are declared in a block without any keywords:
Since Java has a garbage collection mechanism, there are no destructors
. However, every object has a
A method is called using
Methods throwing exceptions use
This language feature was introduced in J2SE 5.0. The last argument of the method may be declared as a variable arity parameter, in which case the method becomes a variable arity method (as opposed to fixed arity methods) or simply varargs method. This allows to pass a variable number of value of declared type to the method as parameters - including no parameters. These values will be available inside the method as an array.
Fields can be initialized directly when declared.
from one class. A class may derive from any class that is not marked as
If a class does not specify the superclass, it implicitly inherits from
Unlike C++, all non-
and can be overridden by the inheriting classes.
Abstract classes are classes that only serve as templates and cannot be instantiated. Otherwise it is just like an ordinary class.
Only abstract classes are allowed to have abstract methods. Abstract methods do not have any implementation and must be overridden by a subclass unless it is abstract itself.
The
Enum constants are allowed to have constructors, which are called when the class is loaded:
Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class:
into code. This language feature was introduced in J2SE 5.0.
Java has a set of predefined annotation types, but it is allowed to define new ones. An annotation type declaration is a special type of an interface declaration. They are declared in the same way as the interfaces, except the
Annotations may have the same declarations in the body as the common interfaces, in addition they are allowed to include enums and annotations. The main difference is that abstract methods declarations must not have any parameters or throw any exceptions. Also they may have a default value, which is declared using the
Annotations may be used in any kind of declaration, whether it is package, class (including enums), interface (including annotations), field, method, parameter, constructor, or local variable. Also they can be used with enum constants. Annotations are declared using the
Besides the generic form, there are two other forms to declare an annotation, which are shorthands. Marker annotation is a short form, it is used when no values are assigned to elements:
The other short form is called single element annotation. It is used with annotations types containing only one element or in the case when multiple elements are present, but only one elements lacks a default value. In single element annotation form the element name is omitted and only value is written instead:
, or parameterized types, or parametric polymorphism is one of the major features introduced in J2SE 5.0. Before generics were introduced, it was required to declare all the types explicitly. With generics it became possible to work in a similar manner with different types without declaring the exact types. The main purpose of generics is to ensure type safety and to detect runtime errors during compilation. Unlike C#, information on the used parameters is not available at runtime due to type erasure
.
It is possible to limit a type variable to a subtype of some specific class or declare an interface that must be implemented by the type. In this case the type variable is appended by the
When a variable of a parametrized type is declared or an instance is created, its type is written exactly in the same format as in the class header, except actual type is written in the place of the type variable declaration.
When declaring a variable for a parametrized type, it is possible to use wildcards instead of explicit type names. Wildcards are expressed by writing
Syntax
In linguistics, syntax is the study of the principles and rules for constructing phrases and sentences in natural languages....
of the Java programming language
Java (programming language)
Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities...
is a set of rules which defines how a Java program is written and interpreted.
The syntax is mostly derived from C
C (programming language)
C is a general-purpose computer programming language developed between 1969 and 1973 by Dennis Ritchie at the Bell Telephone Laboratories for use with the Unix operating system....
and C++
C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
. Unlike C++, Java is almost exclusively an object-oriented language. There are no global functions or variables, all code belongs to class
Class (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
es and all values are object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...
s. The only exception is the primitive type
Primitive type
In computer science, primitive data type is either of the following:* a basic type is a data type provided by a programming language as a basic building block...
s, which are not represented by a class instance due to performance reasons (though can be automatically converted to objects and vice-versa via autoboxing). Some features like operator overloading
Operator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
or unsigned integer types are omitted to simplify the language and to avoid possible programming mistakes.
Java syntax is constantly improved in major JDK releases
Java version history
The Java language has undergone several changes since JDK 1.0 as well as numerous additions of classes and packages to the standard library. Since J2SE 1.4, the evolution of the Java language has been governed by the Java Community Process , which uses Java Specification Requests to propose and...
. The last significant addition happened in J2SE 5.0, which introduced such features as generics and annotations. Project Coin will update the syntax in Java 7, and will introduce several small changes to the syntax.
Identifier
An identifier is the name of an element in the codeSource code
In computer science, source code is text written using the format and syntax of the programming language that it is being written in. Such a language is specially designed to facilitate the work of computer programmers, who specify the actions to be performed by a computer mostly by writing source...
. There are certain standard naming conventions
Naming conventions (programming)
In computer programming, a naming convention is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types and functions etc...
to follow when selecting names for elements. Identifiers in Java are case-sensitive
Case sensitivity
Text sometimes exhibits case sensitivity; that is, words can differ in meaning based on differing use of uppercase and lowercase letters. Words with capital letters do not always have the same meaning when written with lowercase letters....
.
An identifier can contain:
- Any Unicode character that is a letter (including numeric letters like Roman numeralsRoman numeralsThe numeral system of ancient Rome, or Roman numerals, uses combinations of letters from the Latin alphabet to signify values. The numbers 1 to 10 can be expressed in Roman numerals as:...
) or digit. - Currency signCurrency signA currency sign is a graphic symbol used as a shorthand for a currency's name, especially in reference to amounts of money. They typically employ the first letter or character of the currency, sometimes with minor changes such as ligatures or overlaid vertical or horizontal bars...
(such as $Dollar signThe dollar or peso sign is a symbol primarily used to indicate the various peso and dollar units of currency around the world.- Origin :...
). - Connecting punctuation character (such as UnderscoreThe underscore [ _ ] is a character that originally appeared on the typewriter and was primarily used to underline words...
).
An identifier cannot:
- start with a digit.
- be equal to a reserved keyword, null literal or boolean literal.
Keywords
abstract | continue | for | new | switch |
assertKeyword was introduced in J2SE 1.4 | default | gotoKeyword is not used | package | synchronized |
boolean | do | if | private | this |
break | double | implements | protected | throw |
byte | else | import | public | throws |
case | enumKeyword was introduced in J2SE 5.0 | instanceof | return | transient |
catch | extends | int | short | try |
char | final Final (Java) In the Java programming language, the final keyword is used in several different contexts to define an entity which cannot later be changed.- Final classes :... |
interface | static | void |
class | finally | long | strictfpKeyword was introduced in J2SE 1.2 | volatile |
const | float | native | super | while |
Literals
Integers | |
---|---|
binary Binary - Mathematics :* Binary numeral system, a representation for numbers using only two digits * Binary function, a function in mathematics that takes two arguments- Computing :* Binary file, composed of something other than human-readable text... (starting J2SE 7.0) |
0b11110101, 0b[0..1, _]* |
octal Octal The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7. Numerals can be made from binary numerals by grouping consecutive binary digits into groups of three... |
0365, 0[0..7, _]* |
hexadecimal Hexadecimal In mathematics and computer science, hexadecimal is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 0–9 to represent values zero to nine, and A, B, C, D, E, F to represent values ten to fifteen... |
0xF5, 0x[0..9, A..F, a..f, _]+ |
decimal Decimal The decimal numeral system has ten as its base. It is the numerical base most widely used by modern civilizations.... |
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', '\u0231' |
Boolean literals | |
boolean | true, false |
null literal | |
null reference | null |
String literals | |
String | "Hello, world" |
Characters escapes in strings | |
Unicode Unicode Unicode is a computing industry standard for the consistent encoding, representation and handling of text expressed in most of the world's writing systems... character |
\u followed by the hexadecimal unicode code point (up to \uFFFF ) |
Octal Octal The octal numeral system, or oct for short, is the base-8 number system, and uses the digits 0 to 7. Numerals can be made from binary numerals by grouping consecutive binary digits into groups of three... escape |
Octal number not exceeding 377, preceded by backslash (e.g. \352) |
Line feed | \n |
Carriage return Carriage return Carriage return, often shortened to return, refers to a control character or mechanism used to start a new line of text.Originally, the term "carriage return" referred to a mechanism or lever on a typewriter... |
\r |
Form feed | \f |
Backslash Backslash The backslash is a typographical mark used mainly in computing. It was first introduced to computers in 1960 by Bob Bemer. Sometimes called a reverse solidus or a slosh, it is the mirror image of the common slash.... |
\\ |
Single quote | \' |
Double quote | \" |
Tab Tab Tab or tabs may refer to:* Tab, a British Army term for a loaded march* Tab , by Monster Magnet* Tab , a small protective covering for the fingers* Tab , the mechanism for opening a beverage can... |
\t |
Backspace Backspace Backspace is the keyboard key that originally pushed the typewriter carriage one position backwards, and in modern computer displays moves the cursor one position backwards, deletes the preceding character, and shifts back the text after it by one position.... |
\b |
Integer literals are of
int
type by default unless long
type is specified by appending L
or l
suffix to the literal, e.g. 367L
.Variables
VariablesVariable (programming)
In computer programming, a variable is a symbolic name given to some known or unknown quantity or information, for the purpose of allowing the name to be used independently of the information it represents...
are identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.
Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.
Code blocks
The operators{ ... }
are used to signify a code block and a new scope. Class members and the body of a method are examples of what can live inside these braces in various contexts.Inside of method bodies you can use the braces to create new scopes like so:
Comments
Java has three kinds of comments: traditional comments, end-of-line comments and documentation comments.Traditional comments start with
/*
and end with */
, they may span across multiple lines. This type of comments was derived from C and C++.End-of-line comments start with
//
and extend to the end of the current line. This comment type is also present in C++ and in modern C.Documentation comments are processed by Javadoc
Javadoc
Javadoc is a documentation generator from Sun Microsystems for generating API documentation in HTML format from Java source code.The "doc comments" format used by Javadoc is the de facto industry standard for documenting Java classes. Some IDEs, such as Netbeans and Eclipse automatically generate...
tool to generate documentation from source files. This type of comments is identical to traditional comments, except it starts with
/**
and follows conventions defined by the Javadoc tool. Technically these comments are a special kind of traditional comments and they are not specifically defined in the language specification.Program structure
A Java application consists of classes and their members. Classes exist in packages but can also be nested inside other classes.main
method
Whether it is a console or a graphical interface application the program must have an entrypoint of some sort. The entrypoint of the Java application is the main
method. There can be more than one class with main
method, but the main class is always defined externally (e.g. in a manifest fileManifest file
On the Java platform, a Manifest file is a specific file contained within a JAR archive. It is used to define extension and package-related data. It is a metadata file that contains name-value pairs organized in different sections. If a JAR file is intended to be used as an executable file, the...
). The method must be
static
and is passed command-line arguments as an array of strings. Unlike C++C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
or C# it never returns a value and must return
void
.Packages
Packages are a part of a class name and they are used to group and/or distinguish named entities from other ones. Another purpose of packages is to govern code access together with access modifiers.A package is declared at the start of the file like this:
Classes must be placed in the files with the same name and java extension and put into nested folders corresponding to the package name. The above class myapplication.mylibrary.MyClass will have the following path: "myapplication/mylibrary/MyClass.java".
import
statement
The import
statement loads a specific class or classes from a referenced package. It must be placed at the top of a code file after the package declaration.Since J2SE 5.0 it is allowed to do static imports, which allows to access members (fields and methods) defined in the imported class as
public static
without specifying the class name:Operators
Operators in Java are similar to those in C++C++
C++ is a statically typed, free-form, multi-paradigm, compiled, general-purpose programming language. It is regarded as an intermediate-level language, as it comprises a combination of both high-level and low-level language features. It was developed by Bjarne Stroustrup starting in 1979 at Bell...
. However, there is no
delete
operator due to garbage collectionGarbage collection (computer science)
In computer science, garbage collection is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program...
mechanisms in Java, and there are no operations on pointers since Java does not support them. Another difference is that Java has an unsigned right shift operator (
>>>
). Operators in Java cannot be overloadedOperator overloading
In object oriented computer programming, operator overloading—less commonly known as operator ad-hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments...
.
Precedence | Operator | Description | Associativity |
---|---|---|---|
1 |
|
Method invocation | Left-to-right |
[] |
Array access | ||
. |
Class member selection | ||
2 | ++ -- |
Postfix increment and decrement | |
3 | ++ -- |
Prefix increment and decrement | Right-to-left |
+ - |
Unary plus and minus | ||
! ~ |
Logical NOT and bitwise NOT | ||
(type) val |
Type cast | ||
new |
Class instance or array creation | ||
4 | * / % |
Multiplication, division, and modulus (remainder) | Left-to-right |
5 | + - |
Addition and subtraction | |
+ |
String concatenation | ||
6 | << >> >>> |
Bitwise Bitwise operation A bitwise operation operates on one or more bit patterns or binary numerals at the level of their individual bits. This is used directly at the digital hardware level as well as in microcode, machine code and certain kinds of high level languages... left shift, signed right shift and unsigned right shift |
|
7 | < <= |
Relational Relational operator In computer science, a relational operator is a programming language construct or operator that tests or defines some kind of relation between two entities. These include numerical equality and inequalities... “less than” and “less than or equal to” |
|
> >= |
Relational “greater than” and “greater than or equal to” | ||
instanceof |
Type comparison | ||
8 | != |
Relational “equal to” and “not equal to” | |
9 | & |
Bitwise and logical AND | |
10 | ^ |
Bitwise and logical XOR (exclusive or) | |
11 | Bitwise and logical OR (inclusive or) | ||
12 | && |
Logical conditional-AND | |
13 |
|
Logical conditional-OR | |
14 | c ? t : f |
Ternary conditional (see ?: ?: In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages... ) |
Right-to-left |
15 | = |
Simple assignment | |
+= -= |
Assignment by sum and difference | ||
*= /= %= |
Assignment by product, quotient, and remainder | ||
<<= >>= >>>= |
Assignment by bitwise left shift, signed right shift and unsigned right shift | ||
&= ^=
|
Assignment by bitwise AND, XOR, and OR |
if
statement
if statements in Java are similar to those in C and use the same syntax:if
statement may include optional else
block, in which case it becomes an if-then-else statement:Like C, else-if construction does not involve any special keywords, it is formed as a sequence of separate if-then-else statements:
Also, note that the ?:
?:
In computer programming, ?: is a ternary operator that is part of the syntax for a basic conditional expression in several programming languages...
operator can be used in place of simple if statement, for example
switch
statement
Switch statementSwitch statement
In computer programming, a switch, case, select or inspect statement is a type of selection control mechanism that exists in most imperative programming languages such as Pascal, Ada, C/C++, C#, Java, and so on. It is also included in several other types of languages...
s in Java can use
byte
, short
, char
, and int
(note: not long
) primitive data types or their corresponding wrapper types. Starting with J2SE 5.0, it is possible to use enum typesEnumerated type
In computer programming, an enumerated type is a data type consisting of a set of named values called elements, members or enumerators of the type. The enumerator names are usually identifiers that behave as constants in the language...
. Starting with J2SE 7.0, it is possible to use Strings. Other reference types cannot be used in
switch
statements.Possible values are listed using
case
labels. These labels in Java may contain only constants (including enum constants and string constants). Execution will start after the label corresponding to the expression inside the brackets. An optional default
label may be present to declare that the code following it will be executed if none of the case labels correspond to the expression.Code for each label ends with the
break
keyword. It is possible to omit it causing the execution to proceed to the next label, however, a warning will usually be reported during compilation.Iteration statements
Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true. Since J2SE 5.0 Java has four forms of such statements.while
loop
In the while
loop the test is done before each iteration.do ... while
loop
In the do ... while
loop the test is done after each iteration. Consequently, the code is always executed at least once.for
loop
for
loops in Java include an initializer, a condition and a counter expression. It is possible to include several expressions of the same kind using comma as delimiter (except in the condition). However, unlike C, comma is just a delimiter and not an operator.Like C, all three expressions are optional; the following loop will be infinite:
Enhanced for
loop
Enhanced for
loops have been available since J2SE 5.0. This type of loop uses built-in iterators over arrays and collections to return each item in the given collection. Every element will be returned and reachable in the context of the code block. When the block has been executed the next item will be returned until there are no items remaining. Unlike C# this kind of loop does not involve a special keyword but instead uses a different notation style.Labels
Labels are given points in code used bybreak
and continue
statements. Despite the presence of the goto
keyword, it cannot be used to jump to specific points in the code.break
statement
The break
statement breaks out of the closest loop or switch
statement. Execution continues in the statement after the terminated statement, if any.It is possible to break out of the outer loop using labels:
continue
statement
The continue
statement discontinues the current iteration of the current control statement and begins the next iteration. The following while
loop in the code above reads characters by calling getChar
, skipping the statements in the body of the loop if the characters are spaces:Labels can be specified in
continue
statements, as they can in break
statements:return
statement
The return
statement is used to end method execution and to return a value. A value returned by the method is written after the return
keyword. If the method returns anything but void
, it must use the return
statement to return some value.return
statement ends execution immediately, except for one case: if the statement is encountered within a try
block and it is complemented by a finally
, control is passed to the finally
block.try
... catch
... finally
statements
Exceptions are managed within try
... catch
blocks.The statements within the
try
block are executed, and if any of them throws an exception, execution of the block is discontinued and the exception is handled by the catch
block. There may be multiple catch
blocks, in which case the first block with an exception variable whose type matches the type of the thrown exception is executed.If no
catch
block matches the type of the thrown exception, the execution of the outer block (or method) containing the try
... catch
statement is discontinued, and the exception is passed up and outside the containing block (or method). The exception is propagated upwards through the call stackCall stack
In computer science, a call stack is a stack data structure that stores information about the active subroutines of a computer program. This kind of stack is also known as an execution stack, control stack, run-time stack, or machine stack, and is often shortened to just "the stack"...
until a matching
catch
block is found within one of the currently active methods. If the exception propagates all the way up to the top-most main
method without a matching catch
block being found, a textual description of the exception is written to the standard output stream.The statements within the
finally
block are always executed after the try
and catch
blocks, whether or not an exception was thrown and even if a return
statement was reached. Such blocks are useful for providing clean-up code that is guaranteed to always be executed.The
catch
and finally
blocks are optional, but at least one or the other must be present following the try
block.throw
statement
throw
statement is used to throw an exception and end method execution. Thrown exception instance is written after the throw
statement.Thread concurrency control
Unlike C++, Java has built-in tools for multi-thread programmingThread (computer science)
In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. The implementation of threads and processes differs from one operating system to another, but in most cases, a thread is contained inside a process...
. For the purposes of thread synchronization
Synchronization (computer science)
In computer science, synchronization refers to one of two distinct but related concepts: synchronization of processes, and synchronization of data. Process synchronization refers to the idea that multiple processes are to join up or handshake at a certain point, so as to reach an agreement or...
the
synchronized
statement is included in Java language.To make a code block synchronized, it is preceded by the
synchronized
keyword followed by the lock object inside the brackets. When the executing thread reaches the synchronized block, it acquires a mutual exclusionMutual exclusion
Mutual exclusion algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections. A critical section is a piece of code in which a process or thread accesses a common resource...
lock, executes the block, then releases the lock. No threads may enter this block until the lock is released. Any non-null reference type may be used as the lock.
assert
statement
assert
statements have been available since J2SE 1.4. These types of statements are used to make assertionAssertion
The term assertion has several meanings:* Assertion , a computer programming technique* Logical assertion, logical assertion of a statement* Proof by assertion, an assertion as opposed to an argument...
s in the source code, which can be turned on and off during execution for specific classes or packages. To declare an assertion the
assert
keyword is used followed by a conditional expression. If it evaluates to false
during when the statement is executed, an exception is thrown. This statement may include a colon followed by another expression, which will act as the exception's detail message.Primitive types
Primitive types in Java include integer types, floating-point numbers, UTF-16 code units and a boolean type. There are no unsigned types in Java exceptchar
type, which is used to represent UTF-16 code units. The lack of unsigned types is offset by introducing unsigned right shift operation (>>>
), which is not present in C++. Nevertheless, criticisms have been levelled about the lack of compatibility with C and C++ this causes. Primitive Types | |||||
---|---|---|---|---|---|
Type Name | Wrapper class | Value | Range | Size | Default Value |
byte |
java.lang.Byte |
integer | −128 through +127 | 8-bit (1-byte) | 0 |
short |
java.lang.Short |
integer | −32,768 through +32,767 | 16-bit (2-byte) | 0 |
int |
java.lang.Integer |
integer | −2,147,483,648 through +2,147,483,647 | 32-bit (4-byte) | 0 |
long |
java.lang.Long |
integer | −9,223,372,036,854,775,808 through +9,223,372,036,854,775,807 |
64-bit (8-byte) | 0 |
float |
java.lang.Float |
floating point number | ±1.401298E−45 through ±3.402823E+38 | 32-bit (4-byte) | 0.0 |
double |
java.lang.Double |
floating point number | ±4.94065645841246E−324 through ±1.79769313486232E+308 |
64-bit (8-byte) | 0.0 |
boolean |
java.lang.Boolean |
Boolean | true or false |
1-bit (1-bit) | false |
char |
java.lang.Character |
UTF-16 code unit (BMP character or a part of a surrogate pair) |
'\u0000' through '\uFFFF' |
16-bit (2-byte) | '\u0000' |
char
does not necessarily correspond to a single character. It may represent a part of a surrogate pair, in which case Unicode code point is represented by a sequence of two char
values.Boxing and unboxing
This language feature was introduced in J2SE 5.0. Boxing is the operation of converting a value of a primitive type into a value of a corresponding reference type, which serves as a wrapper for this particular primitive type. Unboxing is the reverse operation of converting a value of a reference type (previously boxed) into a value of a corresponding primitive type. Neither operation requires an explicit conversion.Example:
Reference types
Reference types include class types, interface types, and array types. When the constructor is called an object is created on the heap and a reference is assigned to the variable. When a variable of an object gets out of scope the reference is broken and when there are no references left the object gets marked as garbage. The garbage collector will then soon collect and destroy it.A reference variable is
null
when it does not reference any object.Arrays
Arrays in Java are created at runtime, just like class instances. Array length is defined at creation and cannot be changed.Initializers
Multi-dimensional arrays
In Java multi-dimensional arrays are represented as arrays of arrays. Technically they are represented by arrays of references to other arrays.Due to the nature of the multi-dimensional arrays, sub-arrays may vary in length, so multi-dimensional arrays are not bound to be rectangular unlike C:
Classes
ClassesClass (computer science)
In object-oriented programming, a class is a construct that is used as a blueprint to create instances of itself – referred to as class instances, class objects, instance objects or simply objects. A class defines constituent members which enable these class instances to have state and behavior...
are fundamentals of an object-oriented language such as Java. They contain members that store and manipulate data. Classes are divided into top-level and nested. Nested classes include member classes, local classes and anonymous classes.
Declaration
Top-level class | |
---|---|
Member class | |
Local class | |
Anonymous class |
Initialization
To use non-static members of the class it must be instantiated. It is done by using thenew
keyword and calling the class constructor.Accessing members
Members of both instances and static classes are accessed with the.
operator.Accessing an instance member
Instance members can be accessed through the name of a variable.
Accessing a static class member
Static members are accessed by using the name of the class or any other type. This does not require the creation of a class instance. Static members are declared using the
static
modifier.Modifiers
Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers.-
abstract
- Specifies that a class only serves as a base class and cannot be instantiated.
-
static
- Used only for member classes, specifies that the member class does not belong to a specific instance of the containing class.
-
final
- Classes marked asfinal
cannot be extended from and cannot have any subclasses.
-
strictfp
- Specifies that all floating-point operations must be carried out conforming to IEEE 754 and forbids using enhanced precision to store intermediate results.
Access modifiers
The access modifiers, or inheritance modifiers, set the accessibility of classes, methods, and other members. Members marked as
public
can be reached from anywhere. If a class or its member does not have any modifiers, default access is assumed.The following table shows whether code within a class has access to the class or method depending on the accessing class location and the modifier for the accessed class or class member:
Modifier | Same class | Other class inside the same package | Subclass inside another package | Non-subclass inside another package |
---|---|---|---|---|
private |
yes | no | no | no |
default (package private) | yes | yes | no | no |
protected |
yes | yes | yes | no |
public |
yes | yes | yes | yes |
Constructors and initializers
A constructorConstructor (computer science)
In object-oriented programming, a constructor in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created...
is a special method which is called when an object is initialized. Its purpose is to initialize the members of the object. The main differences between constructors and ordinary methods are that constructors are called only when an instance of the class is created and never return anything. Constructors are declared as common methods, but they are named after the class and no return type is specified:
Initializers are blocks of code which are executed when a class or an instance of a class is created. There are two kinds of initializers, static initializers and instance initializers.
The purpose of static initializers is to initialize static fields when the class is created. They are declared using
static
keyword:Any class is created by only once, therefore static initializers aren't called more than once. On the contrary, instance initializers are automatically called before the call to a constructor every time an instance of the class is created. Unlike constructors instance initializers can't take any arguments and generally they can't throw any checked exceptions (except in several special cases). Instance initializers are declared in a block without any keywords:
Since Java has a garbage collection mechanism, there are no destructors
Destructor (computer science)
In object-oriented programming, a destructor is a method which is automatically invoked when the object is destroyed...
. However, every object has a
finalize
method called prior to garbage collection which could be overridden to implement finalization.Methods
All the statements in Java must reside within methods. Methods are similar to functions except they belong to classes. A method has a return value, a name and usually some parameters initialized when it is called with some arguments. Similar to C++, methods which return nothing have return type declared asvoid
. Unlike in C++, methods in Java are not allowed to have default argument values and methods are usually overloaded instead.A method is called using
.
notation on an object, or in the case of a static method, the name of a class.Methods throwing exceptions use
throws
keyword to indicate that. All checked exceptions are mandatory to be declared.Modifiers
-
abstract
- Abstract methods can be present only in abstract classes, such methods have no body and must be overridden in a subclass unless it is abstract itself. -
static
- Makes the method static and accessible without creation of a class instance. However static methods cannot access non-static members in the same class. -
final
- Declares that the method cannot be overridden in a subclass. -
native
- Indicates that this method is implemented through JNI in platform-dependent code. Actual implementation happens outside Java code, and such methods have no body. -
strictfp
- Declares strict conformance to IEEE 754 in carrying out floating-point operations. -
synchronized
- Declares that a thread executing this method must acquire monitor. Forsynchronized
methods the monitor is the class instance or java.lang.Class if the method is static. - Access modifiers - Identical to those used with classes.
Varargs
This language feature was introduced in J2SE 5.0. The last argument of the method may be declared as a variable arity parameter, in which case the method becomes a variable arity method (as opposed to fixed arity methods) or simply varargs method. This allows to pass a variable number of value of declared type to the method as parameters - including no parameters. These values will be available inside the method as an array.
Fields
Fields, or class variables, can be declared inside the class body to store data.Fields can be initialized directly when declared.
Modifiers
-
static
- Makes the field a static member. -
final
- Allows the field to be initialized only once in a constructor or inside initialization block or during its declaration which ever is earlier. -
transient
- Indicates that this field will not be stored during serializationSerializationIn computer science, in the context of data storage and transmission, serialization is the process of converting a data structure or object state into a format that can be stored and "resurrected" later in the same or another computer environment...
. -
volatile
- If a field is declaredvolatile
, it is ensured that all threads see a consistent value for the variable. - Access modifiers - Identical to those used with classes
Inheritance
Classes in Java may only inheritInheritance (computer science)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...
from one class. A class may derive from any class that is not marked as
final
. Inheritance is declared using extends
keyword. A class may reference itself using this
keyword and its direct superclass using super
keyword.If a class does not specify the superclass, it implicitly inherits from
java.lang.Object
class. Thus all classes in Java are subclasses of Object
class.Overriding methods
Unlike C++, all non-
final
methods in Java are virtualVirtual function
In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature...
and can be overridden by the inheriting classes.
Abstract classes
Abstract classes are classes that only serve as templates and cannot be instantiated. Otherwise it is just like an ordinary class.
Only abstract classes are allowed to have abstract methods. Abstract methods do not have any implementation and must be overridden by a subclass unless it is abstract itself.
final
classes
The
final
modifier can be an optional modifier for classes to make them uninheritable.Enumerations
This language feature was introduced in J2SE 5.0. Technically enumerations are a kind of class which contains enum constants in its body. Each enum constant defines an instance of the enum type. Enumeration classes cannot be instantiated anywhere except in the enumeration class itself.Enum constants are allowed to have constructors, which are called when the class is loaded:
Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class:
Interfaces
Interfaces are data structures that contain member definitions and not actual implementation. They are useful to define a contract between members in different types that have different implementations. Every interface is implicitly abstract. The only modifier allowed to use with interfaces apart from access modifiers isstrictfp
, which has the same effect as for classes.Implementing an interface
An interface is implemented by a class using theimplements
keyword. It is allowed to implement more than one interface, in which case they are written after implements
keyword in a comma-separated list. Class implementing an interface must override all its methods, otherwise it must be declared as abstract.Inheritance
Interfaces can inherit from other interfaces just like classes. Unlike classes it is allowed to inherit from multiple interfaces. However, it is possible that several interfaces have a field with the same name, in which case it becomes a single ambiguous member, which cannot be accessed.Annotations
Annotations in Java are a way to embed metadataMetadata
The term metadata is an ambiguous term which is used for two fundamentally different concepts . Although the expression "data about data" is often used, it does not apply to both in the same way. Structural metadata, the design and specification of data structures, cannot be about data, because at...
into code. This language feature was introduced in J2SE 5.0.
Annotation types
Java has a set of predefined annotation types, but it is allowed to define new ones. An annotation type declaration is a special type of an interface declaration. They are declared in the same way as the interfaces, except the
interface
keyword is preceded by the @
sign. All annotations are implicitly extended from java.lang.annotation.Annotation
and cannot be extended from anything else.Annotations may have the same declarations in the body as the common interfaces, in addition they are allowed to include enums and annotations. The main difference is that abstract methods declarations must not have any parameters or throw any exceptions. Also they may have a default value, which is declared using the
default
keyword after the method name:Usage of annotations
Annotations may be used in any kind of declaration, whether it is package, class (including enums), interface (including annotations), field, method, parameter, constructor, or local variable. Also they can be used with enum constants. Annotations are declared using the
@
sign preceding annotation type name, after which element-value pairs are written inside brackets. All elements with no default value must be assigned a value.Besides the generic form, there are two other forms to declare an annotation, which are shorthands. Marker annotation is a short form, it is used when no values are assigned to elements:
The other short form is called single element annotation. It is used with annotations types containing only one element or in the case when multiple elements are present, but only one elements lacks a default value. In single element annotation form the element name is omitted and only value is written instead:
Generics
GenericsGeneric programming
In a broad definition, generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters...
, or parameterized types, or parametric polymorphism is one of the major features introduced in J2SE 5.0. Before generics were introduced, it was required to declare all the types explicitly. With generics it became possible to work in a similar manner with different types without declaring the exact types. The main purpose of generics is to ensure type safety and to detect runtime errors during compilation. Unlike C#, information on the used parameters is not available at runtime due to type erasure
Type erasure
In programming languages, type erasure refers to the compile-time process by which explicit type annotations are removed from a program, before it is executed at run-time. An operational semantics that does not require programs to be accompanied by types is called a type-erasure semantics, to be...
.
Generic classes
Classes can be parameterized by adding a type variable inside angle brackets (<
and >
) following the class name. It makes possible the use of this type variable in class members instead of actual types. There can be more than one type variable, in which case they are declared in a comma-separated list.It is possible to limit a type variable to a subtype of some specific class or declare an interface that must be implemented by the type. In this case the type variable is appended by the
extends
keyword followed by a name of the class or the interface. If the variable is constrained by both class and interface or if there are several interfaces, the class name is written first, followed by interface names with &
sign used as the delimiter.When a variable of a parametrized type is declared or an instance is created, its type is written exactly in the same format as in the class header, except actual type is written in the place of the type variable declaration.
When declaring a variable for a parametrized type, it is possible to use wildcards instead of explicit type names. Wildcards are expressed by writing
?
sign instead of the actual type. It is possible to limit possible types to the subclasses or superclasses of some specific class by writing the extends
keyword or the super
keyword correspondingly followed by the class name.Generic methods and constructors
Usage of generics may be limited to some particular methods, this concept applies to constructors as well. To declare a parametrized method, type variables are written before the return type of the method in the same format as for the generic classes. In the case of constructor, type variables are declared before the constructor name.Generic interfaces
Interfaces can be parametrized in the similar manner as the classes.External links
- The Java Language Specification, Third edition Authoritative description of the Java language