The syntax of Java is the set of rules defining how a Java program is written and interpreted.
The syntax is mostly derived from C and C++. Unlike in C++, in Java there are no global functions or variables, but there are data members which are also regarded as global variables. All code belongs to classes and all values are objects. The only exception is the primitive types, which are not considered to be objects for 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.
The Java syntax has been gradually extended in the course of numerous major JDK releases, and now supports capabilities such as generic programming and function literals (called lambda expressions in Java). Since 2017, a new JDK version is released twice a year, with each release bringing incremental improvements to the language.
An identifier is the name of an element in the code. 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:
See main article: List of Java keywords.
abstract | continue | for | new | switch | |
assert | default | goto | package | synchronized | |
boolean | do | if | private | this | |
break | double | implements | protected | throw | |
byte | else | import | public | throws | |
case | enum | instanceof | return | transient | |
catch | extends | int | short | try | |
char | final | interface | static | var | |
class | finally | long | strictfp | void | |
const | float | native | super | volatile | |
while |
Integers | ||
---|---|---|
binary (introduced in Java SE 7) | (followed by a binary number) | |
octal | (followed by an octal number) | |
hexadecimal | (followed by a hexadecimal number) | |
decimal | (decimal number) | |
Floating-point values | ||
float | ,, (decimal fraction with an optional exponent indicator, followed by) | |
, (followed by a hexadecimal fraction with a mandatory exponent indicator and a suffix) | ||
double | ,, (decimal fraction with an optional exponent indicator, followed by optional) | |
, (followed by a hexadecimal fraction with a mandatory exponent indicator and an optional suffix) | ||
Character literals | ||
char | ,, (character or a character escape, enclosed in single quotes) | |
Boolean literals | ||
boolean | , | |
null literal | ||
null reference | ||
String literals | ||
String | (sequence of characters and character escapes enclosed in double quotes) | |
Characters escapes in strings | ||
Unicode character | (followed by the hexadecimal unicode code point up to U+FFFF) | |
Octal escape | (octal number not exceeding 377, preceded by backslash) | |
Line feed | ||
Carriage return | ||
Form feed | ||
Backslash | ||
Single quote | ||
Double quote | ||
Tab | ||
Backspace |
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
. Since Java SE 7, it is possible to include underscores between the digits of a number to increase readability; for example, a number can be written as .
Variables 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.
See main article: Type inference. Since Java 10, it has become possible to infer types for the variables automatically by using var
.
// An equivalent declaration with an explicit typeFileOutputStream stream = new FileOutputStream("file.txt");
The separators and 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, braces may be used to create new scopes, as follows:
Java has three kinds of comments: traditional comments, end-of-line comments and documentation comments.
Traditional comments, also known as block comments, start with /*
and end with */
, they may span across multiple lines. This type of comment 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 in the source files are processed by the Javadoc tool to generate documentation. This type of comment 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 comment and they are not specifically defined in the language specification.
Classes in the package java.lang are implicitly imported into every program, as long as no explicitly-imported types have the same names. Important ones include:
is Java's top type. Superclass of all classes that do not declare a parent class. All values can be converted to this type, although for primitive values this involves autoboxing.
is Java's basic string type. Immutable. Some methods treat each UTF-16 code unit as a "character", but methods to convert to an int[]
that is effectively UTF-32 are also available.
is supertype of everything that can be thrown or caught with Java's throw
and catch
statements.
Java applications consist of collections of classes. Classes exist in packages but can also be nested inside other classes.
main
methodEvery Java application must have an entry point. This is true of both graphical interface applications and console applications. The entry point is the main
method. There can be more than one class with a main
method, but the main class is always defined externally (for example, in a manifest file). The main
method along with the main class must be declared public
. The method must be static
and is passed command-line arguments as an array of strings. Unlike C++ or C#, it never returns a value and must return void
.
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. For example, java.io.InputStream
is a fully qualified class name for the class InputStream
which is located in the package java.io
.
A package is declared at the start of the file with the package
declaration:
public class MyClass
Classes with the public
modifier must be placed in the files with the same name and 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
.
A type import declaration allows a named type to be referred to by a simple name rather than the full name that includes the package. Import declarations can be single type import declarations or import-on-demand declarations. Import declarations must be placed at the top of a code file after the package declaration.
import java.util.Random; // Single type declaration
public class ImportsTest
Import-on-demand declarations are mentioned in the code. A "type import" imports all the types of the package. A "static import" imports members of the package.
See main article: Static import.
This type of declaration has been available since J2SE 5.0. Static import declarations allow access to static members defined in another class, interface, annotation, or enum; without specifying the class name:
public class HelloWorld
Import-on-demand declarations allow to import all the fields of the type:
Enum constants may also be used with static import. For example, this enum is in the package called screen
:
It is possible to use static import declarations in another class to retrieve the enum constants:
public class Dots
Operators in Java are similar to those in C++. However, there is no delete
operator due to garbage collection 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 (>>>
), while C's right shift operator's signedness is type-dependent. Operators in Java cannot be overloaded.
Precedence | Operator | Description | Associativity | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1 |
| Method invocation | Left-to-right | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
[] | Array access | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
. | Class member selection | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
2 | ++ -- | Postfix increment and decrement[1] | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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 left shift, signed right shift and unsigned right shift | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
7 | < <= | Relational "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 | <nowiki>|</nowiki> | Bitwise and logical OR (inclusive or)|-! 12| && | Logical conditional-AND|-! 13| <nowiki>||</nowiki> | Logical conditional-OR | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
14 | ''c'' ? ''t'' : ''f'' | Ternary conditional (see) | 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 | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
&= ^= <nowiki>|</nowiki>= | style="border-top-style: none" | Assignment by bitwise AND, XOR, and OR|}Control structuresConditional statements
|
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.0f [4] | |
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.
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 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 then collects and destroys it some time afterwards.
A reference variable is null
when it does not reference any object.
Arrays in Java are created at runtime, just like class instances. Array length is defined at creation and cannot be changed.
In Java, multi-dimensional arrays are represented as arrays of arrays. Technically, they are represented by arrays of references to other arrays.
int[][] numbers2 = ;
Due to the nature of the multi-dimensional arrays, sub-arrays can vary in length, so multi-dimensional arrays are not bound to be rectangular unlike C:
numbers[0] = new int[3];numbers[1] = new int[2];
Classes 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 are classes placed inside another class that may access the private members of the enclosing class. Nested classes include member classes (which may be defined with the static modifier for simple nesting or without it for inner classes), local classes and anonymous classes.
Top-level class | ||
---|---|---|
Inner class | ||
Nested class | ||
Local class | ||
Anonymous class |
Non-static members of a class define the types of the instance variables and methods, which are related to the objects created from that class. To create these objects, the class must be instantiated by using the new
operator and calling the class constructor.
Members of both instances and static classes are accessed with the .
(dot) 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.
// Calling the static methodFoo.doSomething;
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 as final
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.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 or nested class | Other class inside the same package | Extended Class inside another package | Non-extended 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 |
A constructor is a special method 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 that are executed when a class or an instance of a class is created. There are two kinds of initializers, static initializers and instance initializers.
Static initializers initialize static fields when the class is created. They are declared using the static
keyword:
A class is created only once. Therefore, static initializers are not 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 cannot take any arguments and generally they cannot 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 finalize
method called prior to garbage collection, which can be overridden to implement finalization.
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 returning nothing have return type declared as void
. 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, also on the name of a class.
int finalResult = Math.abs(result); // Static method call
The throws
keyword indicates that a method throws an exception. All checked exceptions must be listed in a comma-separated list.
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. For synchronized
methods the monitor is the class instance or java.lang.Class
if the method is static.=
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 one to pass a variable number of values, of the declared type, to the method as parameters - including no parameters. These values will be available inside the method as an array.
// Calling varargs methodprintReport("Report data", 74, 83, 25, 96);
Fields, or class variables, can be declared inside the class body to store data.
Fields can be initialized directly when declared.
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, whichever is earlier.transient
- Indicates that this field will not be stored during serialization.volatile
- If a field is declared volatile
, it is ensured that all threads see a consistent value for the variable.Classes in Java can only inherit from one class. A class can be derived from any class that is not marked as final
. Inheritance is declared using the extends
keyword. A class can reference itself using the this
keyword and its direct superclass using the super
keyword.
class Foobar extends Foo
If a class does not specify its superclass, it implicitly inherits from java.lang.Object
class. Thus all classes in Java are subclasses of Object
class.
If the superclass does not have a constructor without parameters the subclass must specify in its constructors what constructor of the superclass to use. For example:
class Foobar extends Foo
Unlike C++, all non-final
methods in Java are virtual and can be overridden by the inheriting classes.
class NewOperation extends Operation
An Abstract Class is a class that is incomplete, or is to be considered incomplete, so cannot be instantiated.
A class C has abstract methods if any of the following is true:
/** * @author jcrypto */public class AbstractClass
/** * @author jcrypto */public class CustomClass extends AbstractClass
Output:
This language feature was introduced in J2SE 5.0. Technically enumerations are a kind of class containing 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 are types which contain no fields and usually define a number of methods without an actual implementation. They are useful to define a contract with any number of different implementations. Every interface is implicitly abstract. Interface methods are allowed to have a subset of access modifiers depending on the language version, strictfp
, which has the same effect as for classes, and also static
since Java SE 8.
An interface is implemented by a class using the implements
keyword. It is allowed to implement more than one interface, in which case they are written after implements
keyword in a comma-separated list. A class implementing an interface must override all its methods, otherwise it must be declared as abstract.
class ActionHandler implements ActionListener, RequestListener
//Calling method defined by interfaceRequestListener listener = new ActionHandler; /*ActionHandler can be represented as RequestListener...*/listener.requestReceived; /*...and thus is known to implement requestReceived method*/
These features were introduced with the release of Java SE 8. An interface automatically becomes a functional interface if it defines only one method. In this case an implementation can be represented as a lambda expression instead of implementing it in a new class, thus greatly simplifying writing code in the functional style. Functional interfaces can optionally be annotated with the [[@FunctionalInterface]]
annotation, which will tell the compiler to check whether the interface actually conforms to a definition of a functional interface.
// A method which accepts this interface as a parameterint runCalculation(Calculation calculation)
// Using a lambda to call the methodrunCalculation((number, otherNumber) -> number + otherNumber);
// Equivalent code which uses an anonymous class insteadrunCalculation(new Calculation)
Lambda's parameters types don't have to be fully specified and can be inferred from the interface it implements. Lambda's body can be written without a body block and a return
statement if it is only an expression. Also, for those interfaces which only have a single parameter in the method, round brackets can be omitted.[5]
// A functional interface with a method which has only a single parameterinterface StringExtender
// Initializing a variable of this type by using a lambdaStringExtender extender = input -> input + " Extended";
It is not necessary to use lambdas when there already is a named method compatible with the interface. This method can be passed instead of a lambda using a method reference. There are several types of method references:
Reference type | Example | Equivalent lambda | |
---|---|---|---|
Static | Integer::sum | (number, otherNumber) -> number + otherNumber | |
Bound | "LongString"::substring | index -> "LongString".substring(index) | |
Unbound | String::isEmpty | string -> string.isEmpty | |
Class constructor | ArrayList<String>::new | capacity -> new ArrayList<String>(capacity) | |
Array constructor | String[]::new | size -> new String[size] |
The code above which calls runCalculation
could be replaced with the following using the method references:
Java SE 8 introduced default methods to interfaces which allows developers to add new methods to existing interfaces without breaking compatibility with the classes already implementing the interface. Unlike regular interface methods, default methods have a body which will get called in the case if the implementing class doesn't override it.
// This is a valid class despite not implementing all the methodsclass PartialStringManipulator implements StringManipulator
Static methods is another language feature introduced in Java SE 8. They behave in exactly the same way as in the classes.
StringUtils.shortenByOneSymbol("Test");
Private methods were added in the Java 9 release. An interface can have a method with a body marked as private, in which case it will not be visible to inheriting classes. It can be called from default methods for the purposes of code reuse.
See main article: Java annotation. Annotations in Java are a way to embed metadata 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 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 method 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:
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:
@BlockingOperations(true)void openOutputStream
See main article: Generics in Java.
Generics, 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.[6]
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 parameterized type is declared or an instance is created, its type is written exactly in the same format as in the class header, except the actual type is written in the place of the type variable declaration.
Since Java SE 7, it is possible to use a diamond (<>
) in place of type arguments, in which case the latter will be inferred. The following code in Java SE 7 is equivalent to the code in the previous example:
When declaring a variable for a parameterized 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.
/* Will not accept types that use anything buta subclass of Number as the second parameter */void addMapper(Mapper, ? extends Number> mapper)
Usage of generics may be limited to some particular methods, this concept applies to constructors as well. To declare a parameterized 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.
/* This method will accept only arrays of the same type asthe searched item type or its subtype*/static
Interfaces can be parameterized in the similar manner as the classes.
// This class is parameterizedclass Array
// And this is not and uses an explicit type insteadclass IntegerArray implements Expandable