Java syntax: Difference between revisions

Content deleted Content added
 
(223 intermediate revisions by 95 users not shown)
Line 1:
{{Short description|Rules defining correctly structured Java programs}}
{{more footnotes|date=January 2014}}
{{See also|Java (programming language)#Syntax}}
[[File:Java keywords highlighted.png|thumb|300px|A snippet of Java code with keywords highlighted in bold blue font]]
{{More footnotes|date=January 2014}}
{{Use mdy dates|date=April 2025}}
{{Use American English|date=April 2025}}
[[File:Java keywords highlighted.svg|thumb|300px|A snippet of Java code with keywords highlighted in bold blue font]]
 
The [['''syntax]] of theJava''' is [[Java (programming language)syntax|Java programming language]] is the set of rules]] defining how a [[Java (programming language)|Java]] program is written and interpreted.
 
The [[Syntax (programming languages)|syntax]] is mostly derived from [[C (programming language)|C]] and [[C++]]. Unlike C++, Java ishas almostno exclusivelyglobal anfunctions [[object-orientedor language]].variables, Therebut has data members which are noalso globalregarded functionsas or[[global variables,variable]]s. allAll code belongs to [[classClass (computer scienceprogramming)|classclasses]]es and all values are [[objectObject (computer science)|objectobjects]]s. The only exception is the [[primitive typedata types]]s, which are not representedconsidered byto abe classobjects instance due tofor performance reasons (though can be automatically converted to objects and vice versa via [[#Boxing and unboxing|autoboxing]]). Some features like [[operator overloading]] or [[unsigned integer]] types[[data type]]s are omitted to simplify the language and to avoid possible programming mistakes.
 
'''The Java syntax''' ishas been constantlygradually improvedextended in the course of numerous major [[JDK]] [[Java version history|releases]]., Theand latestnow improvementssupports toabilities thesuch languageas happened[[generic inprogramming]] Javaand SE[[anonymous function]]s 8(function literals, called lambda expressions in Java). SESince 72017, introduceda suchnew languageJDK featuresversion asis [[#try-with-resourcesreleased twice a year, statements|<code>try</code>-with-resources statements]]each andrelease [[#Literals|binaryimproving literals]])the language incrementally.
 
==Basics==
The Java [["Hello, World!" program]] program is as follows:
<syntaxhighlight lang="java">
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
</syntaxhighlight>
 
Since Java 25, a simplified Hello World program without an explicit class may be written:
<syntaxhighlight lang="java">
void main() {
IO.println("Hello World!");
}
</syntaxhighlight>
 
===Identifier===
Line 15 ⟶ 34:
An identifier can contain:
* Any Unicode character that is a letter (including numeric letters like [[Roman numerals]]) or digit.
* [[Currency sign]] (such as [[Dollar sign|$]]¥).
* Connecting punctuation character (such as [[Underscore|_]]).
 
An identifier cannot:
* startStart with a digit.
* beBe equal to a reserved keyword, null literal or boolean[[Boolean data type|Boolean]] literal.
 
===Keywords===
{{Main|List of Java keywords}}
====Keywords====
{| style="width:75%" align="center" class="wikitable"
The following words are keywords and cannot be used as identifiers under any circumstances.
|--
{{div col|colwidth=15em}}
| abstract
* <code>_</code>
| continue
* <code>abstract</code>
| for
* <code>assert</code>
| new
* <code>boolean</code>
| switch
* <code>break</code>
|-
* <code>byte</code>
| assert<ref group="Note">Keyword was introduced in [[J2SE 1.4]]</ref>
* <code>case</code>
| default
* <code>catch</code>
| goto<ref group="Note" name="Unused">Keyword is not used</ref>
* <code>char</code>
| package
* <code>class</code>
| synchronized
* <code>continue</code>
|-
* <code>default</code>
| boolean
* <code>do</code>
| do
* <code>double</code>
| if
* <code>else</code>
| private
* <code>enum</code>
| this
* <code>extends</code>
|-
* <code>final</code>
| break
* <code>finally</code>
| double
* <code>float</code>
| implements
* <code>for</code>
| protected
* <code>if</code>
| throw
* <code>implements</code>
|-
* <code>import</code>
| byte
* <code>instanceof</code>
| else
* <code>int</code>
| import
* <code>interface</code>
| public
* <code>long</code>
| throws
* <code>native</code>
|-
* <code>new</code>
| case
* <code>package</code>
| enum<ref group="Note">Keyword was introduced in [[J2SE 5.0]]</ref>
* <code>private</code>
| instanceof
* <code>protected</code>
| return
* <code>public</code>
| transient
* <code>return</code>
|-
* <code>short</code>
| catch
* <code>static</code>
| extends
* <code>super</code>
| int
* <code>switch</code>
| short
* <code>synchronized</code>
| try
* <code>this</code>
|-
* <code>throw</code>
| char
* <code>throws</code>
| [[Final (Java)|final]]
* <code>transient</code>
| interface
* <code>try</code>
| static
|* <code>void</code>
* <code>volatile</code>
|-
* <code>while</code>
| class
{{div col end}}
| finally
 
| long
====Reserved identifiers====
| strictfp<ref group="Note">Keyword was introduced in [[J2SE 1.2]]</ref>
The following words are contextual keywords and are only restricted in certain contexts.
| volatile
{{div col|colwidth=15em}}
|-
* <code>exports</code>
| const<ref group="Note" name="Unused"/>
* <code>module</code>
| float
* <code>non-sealed</code>
| native
* <code>open</code>
| super
* <code>opens</code>
| while
* <code>permits</code>
|}
* <code>provides</code>
<references group="Note"/>
* <code>record</code>
* <code>requires</code>
* <code>sealed</code>
* <code>to</code>
* <code>transitive</code>
* <code>var</code>
* <code>when</code>
* <code>with</code>
* <code>yield</code>
{{div col end}}
 
====Reserved words for literal values====
The following words refer to literal values used by the language.
{{div col|colwidth=15em}}
* <code>true</code>
* <code>false</code>
* <code>null</code>
{{div col end}}
 
====Unused====
The following words are reserved as keywords, but currently have no use or purpose.
{{div col|colwidth=15em}}
* <code>const</code>
* <code>goto</code>
* <code>strictfp</code>
{{div col end}}
 
===Literals===
Line 95 ⟶ 140:
|-
![[Binary numeral system|binary]] (introduced in Java SE 7)
|<tt>{{mono|0b11110101</tt>}} (<tt>{{mono|0b</tt>}} followed by a binary number)
|-
![[octal]]
|<tt>{{mono|0365</tt>}} (<tt>{{mono|0</tt>}} followed by an octal number)
|-
![[hexadecimal]]
|<tt>{{mono|0xF5</tt>}} (<tt>{{mono|0x</tt>}} followed by a hexadecimal number)
|-
![[decimal]]
|<tt>{{mono|245</tt>}} (decimal number)
|-
!colspan="2"|[[Floating-point]] values
|-
!rowspan="2" | float
|<tt>{{mono|23.5F</tt>}}, <tt>{{mono|.5f</tt>}}, <tt>{{mono|1.72E3F</tt>}} (decimal fraction with an optional exponent indicator, followed by <tt>{{mono|F</tt>}})
|-
|<tt>{{mono|0x.5FP0F</tt>}}, <tt>{{mono|0x.5P-6f</tt>}} (<tt>{{mono|0x</tt>}} followed by a hexadecimal fraction with a mandatory exponent indicator and a suffix <tt>{{mono|F</tt>}})
|-
!rowspan="2" | double
|<tt>{{mono|23.5D</tt>}}, <tt>{{mono|.5</tt>}}, <tt>{{mono|5.}}, {{mono|1.72E3D</tt>}} (decimal fraction with an optional exponent indicator, followed by optional <tt>{{mono|D</tt>}})
|-
|<tt>{{mono|0x.5FP0</tt>}}, <tt>{{mono|0x.5P-6D</tt>}} (<tt>{{mono|0x</tt>}} followed by a hexadecimal fraction with a mandatory exponent indicator and an optional suffix <tt>{{mono|D</tt>}})
|-
!colspan="2"|Character literals
|-
!char
|<tt>{{mono|'a'</tt>}}, <tt>{{mono|'Z'</tt>}}, <tt>{{mono|'\u0231'</tt>}} (character or a character escape, enclosed in single quotes)
|-
!colspan="2"|Boolean literals
|-
!boolean
|<tt>{{mono|true</tt>}}, <tt>{{mono|false</tt>}}
|-
!colspan="2"|null literal
|-
!null reference
|<tt>{{mono|null</tt>}}
|-
!colspan="2"|String literals
|-
!String
|<tt>{{mono|"Hello, World"</tt>}} (sequence of characters and character escapes enclosed in double quotes)
|-
!colspan="2"|Characters escapes in strings
|-
![[Unicode]] character
|<tt>{{mono|\u3876</tt>}} (<tt>{{mono|\u</tt>}} followed by the hexadecimal unicode code point up to U+FFFF)
|-
![[Octal]] escape
|<tt>{{mono|\352</tt>}} (octal number not exceeding 377, preceded by backslash)
|-
![[Line feed]]
|{{mono|\n}}
|<tt>\n</tt>
|-
![[Carriage return]]
|{{mono|\r}}
|<tt>\r</tt>
|-
![[Form feed]]
|{{mono|\f}}
|<tt>\f</tt>
|-
![[Backslash]]
|{{mono|\\}}
|<tt>\\</tt>
|-
![[Single quote]]
|{{mono|\'}}
|<tt>\'</tt>
|-
![[Double quote]]
|{{mono|\"}}
|<tt>\"</tt>
|-
![[Tab character|Tab]]
|{{mono|\t}}
|<tt>\t</tt>
|-
![[Backspace]]
|{{mono|\b}}
|<tt>\b</tt>
|}
 
Integer literals are of <code>int</code> type by default unless <code>long</code> type is specified by appending <code>L</code> or <code>l</code> suffix to the literal, e.g. <code>367L</code>. Since Java SE 7, it is possible to include underscores between the digits of a number to increase readability,; for example, a number <tt>{{mono|145608987</tt>}} maycan be written as <tt>{{mono|145_608_987</tt>}}.
 
===Variables===
[[Variable (programmingcomputer science)|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.
 
<sourcesyntaxhighlight lang=Java5"java">
int count; // Declaring an uninitialized variable called 'count', of type 'int'
count = 35; //Initializing the variable
int count = 35; // Declaring and initializing the variable at the same time
</syntaxhighlight>
</source>
 
Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.
<sourcesyntaxhighlight lang=Java5"java">
int a, b; // Declaring multiple variables of the same type
int a = 2, b = 3; // Declaring and initializing multiple variables of the same type
</syntaxhighlight>
</source>
 
====Type inference====
{{Main|Type inference}}
Since Java 10, it has become possible to [[type inference|infer types]] for the variables automatically by using <code>var</code>.
 
<syntaxhighlight lang="java">
// stream will have the FileOutputStream type as inferred from its initializer
var stream = new FileOutputStream("file.txt");
 
// An equivalent declaration with an explicit type
FileOutputStream stream = new FileOutputStream("file.txt");
</syntaxhighlight>
 
===Code blocks===
 
The separators <tt>{</tt>{mono|{{(}}}} and <tt>{{mono|{{)}}}}</tt> are used to signify a code block and a new scope. Class members and the body of a [[Method (computer programming)|method]] are examples of what can live inside these braces in various contexts.
 
Inside of method bodies, youbraces canmay usebe the bracesused to create new scopes, likeas sofollows:
 
<syntaxhighlight lang=Java5"java">
void doSomething() {
int a;
Line 204 ⟶ 261:
 
a = 2;
b = 3; // Illegal because the variable b is declared in an inner scope..
}
</syntaxhighlight>
 
===Comments===
Java has three kinds of [[Comment (computer programming)|comments]]: ''traditional comments'', ''end-of-line comments'' and ''documentation comments''.
 
Traditional comments, also known as block comments, start with <code>/*</code> and end with <code>*/</code>, they may span across multiple lines. This type of comment was derived from C and C++.
 
<sourcesyntaxhighlight lang=Java5"java">
/* This is a multi-line comment.
It may occupy more than one line. */
</syntaxhighlight>
</source>
 
End-of-line comments start with <code>//</code> and extend to the end of the current line. This comment type is also present in C++ and in modern C.
<sourcesyntaxhighlight lang=Java5"java">
// This is an end-of-line comment
</syntaxhighlight>
</source>
 
Documentation comments in the source files are processed by the [[Javadoc]] tool to generate documentation from source files. This type of comment is identical to traditional comments, except it starts with <code>/**</code> 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.
<sourcesyntaxhighlight lang=Java5"java">
/**
* This is a documentation comment.
Line 230 ⟶ 287:
* @author John Doe
*/
</syntaxhighlight>
</source>
 
===Universal types===
 
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:
 
===={{mono|java.lang.System}}====
{{code|java.lang.System}} is one of the most fundamental classes in Java. It is a utility class for interacting with the system, containing standard input, output, and error streams, system properties and environment variables, time, and more.
 
===={{mono|java.lang.Object}}====
{{code|java.lang.Object}} is Java's [[top type]]. It is implicitly the superclass of all classes that do not declare any parent class (thus all classes in Java inherent from <code>Object</code>). All values can be converted to this type, although for primitive values this involves [[Object type (object-oriented programming)#Autoboxing|autoboxing]].
 
===={{mono|java.lang.Record}}====
All [[Record (computer science)|records]] implicitly extend {{code|java.lang.Record}}. Thus, a <code>record</code>, while treated as a <code>class</code>, cannot extend any other class.
 
===={{mono|java.lang.Enum}}====
All [[enumerated type]]s (enums) in Java implicitly extend {{code|java.lang.Enum}}. Thus, an <code>enum</code>, while treated as a <code>class</code>, cannot extend any other class.
 
===={{mono|java.lang.Class<T>}}====
{{code|java.lang.Class<T>}} is a class that represents a <code>class</code> or <code>interface</code> in the application at runtime. It cannot be constructed via direct instantiation, but is rather created by the JVM when a class is derived from the bytes of a <code>.class</code> file. A class literal can be obtained through <code>.class</code> on such a class. For instance, <code>String.class</code> returns <code>Class<String></code>. An unknown class being modeled can be represented as <code>Class<?></code> (where <code>?</code> denotes a [[Wildcard (Java)|wildcard]]).
 
===={{mono|java.lang.String}}====
{{code|java.lang.String}} is Java's basic string type. It is [[immutable object|immutable]]. It does not implement {{code|Iterable<Character>}}, so it cannot be iterated over in a for-each loop, but can be converted to <code>char[]</code>. Some methods treat each [[UTF-16]] code unit as a <code>char</code>, but methods to convert to an <code>int[]</code> that is effectively [[UTF-32]] are also available. <code>String</code> implements <code>CharSequence</code>, so <code>char</code>s in the <code>String</code> can be accessed by the method <code>charAt()</code>.
 
===={{mono|java.lang.Throwable}}====
{{code|java.lang.Throwable}} is the supertype of everything that can be [[exception handling|thrown or caught]] with Java's <code>throw</code> and <code>catch</code> statements. Its direct known subclasses are {{code|java.lang.Error}} (for serious unrecoverable errors) and {{code|java.lang.Exception}} (for exceptions that may naturally occur in the execution of a program).
 
====={{mono|java.lang.Error}}=====
{{code|java.lang.Error}} is the supertype of all error classes and extends <code>Throwable</code>. It is used to indicate conditions that a reasonable application should not catch.
 
====={{mono|java.lang.Exception}}=====
{{code|java.lang.Exception}} is the supertype of all exception classes and extends <code>Throwable</code>. It is used to indicate conditions that a reasonable application may have reason to catch.
 
===={{mono|java.lang.Math}}====
{{code|java.lang.Math}} is a utility class containing mathematical functions and mathematical constants (such as <code>Math.sin()</code>, <code>Math.pow()</code>, and <code>Math.PI</code>).
 
===={{mono|java.lang.IO}}====
{{code|java.lang.IO}} is a class introduced in Java 25 (previously residing in <code>java.io</code> as <code>java.io.IO</code>). It allows simpler access to the standard input and output streams over <code>System.in</code> and <code>System.out</code>.
 
====Primitives====
Each primitive type has an associated wrapper class (see [[#Primitive types|primitive types]]).
 
==Program structure==
Java applications consist of collections of classes. Classes exist in packages but can also be nested inside other classes.
 
===<code>Mainmain</code> method===
{{Main|Entry point#Java}}
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 <code>main</code> method. There can be more than one class with <code>main</code> method, but the main class is always defined externally (e.g. in a [[manifest file]]). The method must be <code>static</code> and is passed command-line arguments as an array of strings. Unlike [[C++]] or [[C Sharp (programming language)|C#]] it never returns a value and must return <code>void</code>.
 
<source lang=Java>
Every Java application must have an entry point. This is true of both graphical interface applications and console applications. The entry point is the <code>main</code> method. There can be more than one class with a <code>main</code> method, but the main class is always defined externally (for example, in a [[manifest file]]). The <code>main</code> method along with the main class must be declared <code>public</code>. The method must be <code>static</code> and is passed command-line arguments as an array of strings. Unlike [[C++]] or [[C Sharp (programming language)|C#]], it never returns a value and must return <code>void</code>. However, a return code can be specified to the operating system by calling <code>System.exit()</code>.
<syntaxhighlight lang=Java>
public static void main(String[] args) {
// ...
}
</syntaxhighlight>
</source>
 
===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. For example, <code>java.io.InputStream</code> is a fully qualified class name for the class <code>InputStream</code> which is located in the package <code>java.io</code>.
 
A package is essentially a [[namespace]]. Packages do not have hierarchies, even though the periods may suggest so. A package can be controlled whether it is accessible externally or internally of a project using [[Java Platform Module System|modules]].
 
A package is declared at the start of the file with the <code>package</code> declaration:
 
<sourcesyntaxhighlight lang=Java>
package myapplicationcom.myapp.mylibrary;
 
public class MyClass {
 
}
</syntaxhighlight>
</source>
 
Classes with the <code>public</code> modifier must be placed in the files with the same name and {{mono|java}} extension and put into nested folders corresponding to the package name. The above class <code>com.myapp.mylibrary.MyClass</code> will have the following path: <code>com/myapp/mylibrary/MyClass.java</code>.
 
===Modules===
{{main|Java Platform Module System}}
Modules are used to group packages and tightly control what packages belong to the public API. Contrary to [[JAR (file format)|Jar files]], modules explicitly declare which modules they depend on, and what packages they export.<ref>{{cite web
| url=http://openjdk.java.net/projects/jigsaw/spec/sotms/
| title=The State of the Module System
| publisher=[[Oracle Corporation]]
| author=Mark Reinhold
| date=2016-03-08
| accessdate=2017-02-18}}</ref> Explicit dependency declarations improve the integrity of the code, by making it easier to reason about large applications and the dependencies between software components.
 
The module declaration is placed in a file named {{mono|module-info.java}} at the root of the module’s source-file hierarchy. The JDK will verify dependencies and interactions between modules both at compile-time and runtime.
 
For example, the following module declaration declares that the module {{mono|com.foo.bar}} depends on another {{mono|com.foo.baz}} module, and exports the following packages: {{mono|com.foo.bar.alpha}} and {{mono|com.foo.bar.beta}}:
<syntaxhighlight lang="cpp">
module com.foo.bar {
requires com.foo.baz;
 
exports com.foo.bar.alpha;
exports com.foo.bar.beta;
}
</syntaxhighlight>
The public members of {{mono|com.foo.bar.alpha}} and {{mono|com.foo.bar.beta}} packages will be accessible by dependent modules. Private members are inaccessible even through a means such as [[reflective programming|reflection]]. Note that in [[Java version history|Java versions]] 9 through 16, whether such 'illegal access' is ''de facto'' permitted depends on a command line setting.<ref name="JEP 396: Strongly Encapsulate JDK Internals by Default">{{cite web | url=https://openjdk.java.net/jeps/396 | title=JEP 396: Strongly Encapsulate JDK Internals by Default | access-date=2021-02-06}}</ref>
 
The JDK itself has been modularized in [[Java version history#Java SE 9|Java 9]].<ref>{{cite web
Classes with the <code>public</code> modifier must be placed in the files with the same name and <tt>java</tt> 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".
| url=http://cr.openjdk.java.net/~mr/jigsaw/ea/module-summary.html
| title=JDK Module Summary
| publisher=[[Oracle Corporation]]
| date=2016-06-24
| accessdate=2017-02-18
| archive-date=2015-12-08
| archive-url=https://web.archive.org/web/20151208074800/http://cr.openjdk.java.net/~mr/jigsaw/ea/module-summary.html
| url-status=dead
}}</ref> For example, the majority of the Java standard library is exported by the module <code>java.base</code>.
 
===Import declaration===
An import statement is used to resolve a type belonging to another package (namespace). It can be seen as similar to <code>using</code> in C++.
 
====Type import declaration====
 
A type import declaration allows a named type to be referred to by a simple name rather than the full name includingthat 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.
 
<syntaxhighlight lang="java">
package com.myapp;
 
<source lang=Java5>
import java.util.Random; // Single type declaration
 
Line 269 ⟶ 409:
/* The following line is equivalent to
* java.util.Random random = new java.util.Random();
* It would've have been incorrect without the import declaration */.
*/
Random random = new Random();
}
}
</syntaxhighlight>
</source>
 
Import-on-demand declarations alloware tomentioned import allin the typescode. ofA the"glob package,import" inimports all the casetypes of type import, or members, in the casepackage. ofA "static import," asimports theymembers are mentioned inof the codepackage.
 
<sourcesyntaxhighlight lang=Java5"java">
import java.util.*; /* This form of importing classes makes all classes
in package java.util available by name, could be used instead of the
import declaration in the previous example. */
import java.*; /* This statement is legal, but does nothing, since there
are no classes directly in package java. All of them are in packages
within package java. This doeswill not import all available classes. */
</syntaxhighlight>
</source>
 
====Static import declaration====
{{Main|Static import}}
 
This type of declaration has been available since [[J2SE 5.0]]. [[static imports|Static import]] declarations allow access to static members defined in another class, interface, annotation, or enum; without specifying the class name:
 
<sourcesyntaxhighlight lang=Java5"java">
import static java.lang.System.out; // 'out' is a static field in java.lang.System
 
public class HelloWorld {
public static void main(String[] args) {
/* The following line is equivalent to:
System.out.println("Hi World!");
 
System.out.println("Hello World!");
 
and would have been incorrect without the import declaration. */
out.println("Hello World!");
}
}
</syntaxhighlight>
</source>
 
Import-on-demand declarations allow to import all the fields of the type:
 
<sourcesyntaxhighlight lang=Java5"java">
import static java.lang.System.*;
/* This form of declaration makes all
fields in the java.lang.System class available by name, and may be used instead
of the import declaration in the previous example. */
</syntaxhighlight>
</source>
 
Enum constants may also be used with static import. For example, this enum is in the package called <code>screen</code>:
 
<sourcesyntaxhighlight lang=Java5"java">
public enum ColorName {
RED, BLUE, GREEN
};
</syntaxhighlight>
</source>
 
It is possible to use static import declarations in another class to retrieve the enum constants:
 
<sourcesyntaxhighlight lang=Java5"java">
import screen.ColorName;
import static screen.ColorName.*;
Line 334 ⟶ 474:
 
void shift() {
/* The following line is equivalent to:
 
if (foo == ColorName.RED) foo = ColorName.BLUE; */
if (foo == RED) {
foo = BLUE;
}
}
}
</syntaxhighlight>
</source>
 
====Module import declaration====
Since Java 25, modules can be used in import statements to automatically import all the packages exported by the module.<ref>{{Cite web|url=https://openjdk.org/jeps/494|title=JEP 494: Module Import Declarations (Second Preview)|website=openjdk.org}}</ref> This is done using <code>import module</code>. For example, <syntaxhighlight lang="Java" inline>import module java.sql;</syntaxhighlight> is equivalent to
<syntaxhighlight lang="Java">
import java.sql.*;
import javax.sql.*;
// Remaining indirect exports from java.logging, java.transaction.xa, and java.xml
</syntaxhighlight>
Similarly, <syntaxhighlight lang="Java" inline>import module java.base;</syntaxhighlight>, similarly, imports all 54 packages belonging to <code>java.base</code>.
 
<syntaxhighlight lang="Java">
import module java.base;
 
/**
* importing module java.base allows us to avoid manually importing most classes
* the following classes (outside of java.lang) are used:
* java.text.MessageFormat
* java.util.Date
* java.util.List
* java.util.concurrent.ThreadLocalRandom
*/
public class Example {
public static void main(String[] args) {
List<String> colours = List.of("Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet");
IO.println(MessageFormat.format("My favourite colour is {0} and today is {1,date,long}",
colours.get(ThreadLocalRandom.current().nextInt(colours.size())),
new Date()
));
}
}
</syntaxhighlight>
 
==Operators==
Operators in Java are similar to those in [[C++]]. However, there is no <code>delete</code> operator due to [[Garbage collection (computer science)|garbage collection]] mechanisms in Java, and there are no operations on [[Pointer (computer programming)|pointers]] since Java does not support them. Another difference is that Java has an unsigned right shift operator (<code>>>></code>), while C's right shift operator's signedness is type-dependent. Operators in Java cannot be [[Operator overloading|overloaded]]. The only overloaded operator is <code>operator+</code> for string concatenation.
 
{| class="wikitable"
Line 365 ⟶ 537:
! 2
| style="border-bottom-style: none" | <code>++</code> <code>--</code>
| style="border-bottom-style: none" | Postfix increment and decrement<ref>{{Cite web|title = Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)|url = http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html|website = docs.oracle.com|access-date = June 16, 2015|publisher = Oracle and/or its affiliates|archive-date = June 24, 2015|archive-url = https://web.archive.org/web/20150624161036/http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html|url-status = live}}</ref>
Learning the Java Language > Language Basics)|url = http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html|website = docs.oracle.com|accessdate = 2015-06-16|publisher = Oracle and/or its affiliates}}</ref>
|-
! rowspan=5| 3
Line 403 ⟶ 574:
! rowspan=3| 7
| style="border-bottom-style: none;" | <code>&lt;</code> <code>&lt;=</code>
| style="border-bottom-style: none;" | [[Relational operator|Relational]] “less"less than”than" and “less"less than or equal to”to"
|-
| style="border-bottom-style: none; border-top-style: none" | <code>&gt;</code> <code>&gt;=</code>
| style="border-bottom-style: none; border-top-style: none" | Relational “greater"greater than”than" and “greater"greater than or equal to”to"
|-
| style="border-top-style: none" | <code>instanceof</code>
Line 413 ⟶ 584:
! 8
| <code>==</code> <code>!=</code>
| Relational “equal"equal to”to" and “not"not equal to”to"
|-
! 9
Line 462 ⟶ 633:
 
====<code>if</code> statement====
[[{{Main|Conditional (computer programming)|if statements]] in Java are similar to those in #C-like and use the same syntax:languages}}
 
<syntaxhighlight lang=Java5>
[[Conditional (computer programming)|if statements]] in Java are similar to those in C and use the same syntax:
if (i == 3) doSomething();
<syntaxhighlight lang="java">
if (i == 3) {
doSomething();
}
</syntaxhighlight>
 
<code>if</code> statement may include optional <code>else</code> block, in which case it becomes an if-then-else statement:
<syntaxhighlight lang=Java5"java">
if (i == 23) {
doSomething();
} else {
Line 477 ⟶ 652:
 
Like C, else-if construction does not involve any special keywords, it is formed as a sequence of separate if-then-else statements:
<syntaxhighlight lang=Java5"java">
if (i == 3) {
doSomething();
Line 487 ⟶ 662:
</syntaxhighlight>
 
Also, note that thea [[?:]] operator can be used in place of simple if statement, for example
<sourcesyntaxhighlight lang=Java5"java">
int a = 1;
int b = 2;
int minVal = (a < b) ? a : b;
</syntaxhighlight>
</source>
 
====<code>switch</code> statement====
[[Switch statement]]s in Java can use <code>byte</code>, <code>short</code>, <code>char</code>, and <code>int</code> (note: not <code>long</code>) primitive data types or their corresponding wrapper types. Starting with J2SE 5.0, it is possible to use [[Enumerated type|enum types]]. Starting with Java SE 7, it is possible to use Strings.<ref>{{Cite web|title=The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)|url=https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html|access-date=August 15, 2021|website=docs.oracle.com|archive-date=March 15, 2010|archive-url=https://web.archive.org/web/20100315060844/http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html|url-status=live}}</ref> Other [[reference typestype]]s cannot be used in <code>switch</code> statements.
 
Possible values are listed using <code>case</code> 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 <code>default</code> label may be present to declare that the code following it will be executed if none of the case labels correspond to the expression.
Line 501 ⟶ 676:
Code for each label ends with the <code>break</code> 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.
 
<syntaxhighlight lang=Java5"java">
switch (ch) {
case 'A':
Line 514 ⟶ 689:
break;
}
</syntaxhighlight>
 
=====<code>switch</code> expressions=====
 
Since Java 14 it has become possible to use switch expressions, which use the new arrow syntax:
 
<syntaxhighlight lang="java">
enum Result {
GREAT,
FINE,
// more enum values
}
 
Result result = switch (ch) {
case 'A' -> Result.GREAT;
case 'B', 'C' -> Result.FINE;
default -> throw new Exception();
};
</syntaxhighlight>
 
Alternatively, there is a possibility to express the same with the <code>yield</code> statement, although it is recommended to prefer the arrow syntax because it avoids the problem of accidental fall throughs.
 
<syntaxhighlight lang="java">
Result result = switch (ch) {
case 'A':
yield Result.GREAT;
case 'B':
case 'C':
yield Result.FINE;
default:
throw new Exception();
};
</syntaxhighlight>
 
===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. The condition must have type <code>boolean</code> or <code>java.lang.Boolean</code>. Java does not implicitly convert integers or class types to Boolean values.
 
For example, the following code is valid in C but results in a compilation error in Java.
<syntaxhighlight lang="c">
while (1) {
doSomething();
}
</syntaxhighlight>
 
====<code>while</code> loop====
{{Main|While loop}}
In the <code>while</code> loop the test is done before each iteration.
 
In the <code>while</code> loop, the test is done before each iteration.
 
<sourcesyntaxhighlight lang=Java5"java">
while (i < 10) {
doSomething();
}
</syntaxhighlight>
</source>
 
====<code>do ... while</code> loop====
In the <code>do ... while</code> loop, the test is done after each iteration. Consequently, the code is always executed at least once.
 
<sourcesyntaxhighlight lang=Java5"java">
// doSomething() is called at least once
do {
doSomething();
} while (i < 10);
</syntaxhighlight>
</source>
 
====<code>for</code> loop====
<code>for</code> 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, the comma is just a delimiter and not an operator.
 
<sourcesyntaxhighlight lang=Java5"java">
for (int i = 0; i < 10; i++) {
doSomething();
Line 550 ⟶ 766:
doSomething();
}
</syntaxhighlight>
</source>
 
Like C, all three expressions are optional;. theThe following loop willnever be infiniteterminates:
<sourcesyntaxhighlight lang=Java5"java">
for (;;) {
doSomething();
}
</syntaxhighlight>
</source>
 
====Enhanced <code>for</code>Foreach loop====
{{Main|Foreach loop}}
[[Foreach loop]]s 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 is returned and reachable in the context of the code block. When the block is executed, the next item is returned until there are no items remaining. This for loop from Java was later added to [[C++11]]. Unlike [[C Sharp (programming language)|C#]], this kind of loop does not involve a special keyword, but instead uses a different notation style.
 
<syntaxhighlight lang="java">
[[enhanced for loop|Enhanced <code>for</code> loop]]s 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 Sharp (programming language)|C#]] this kind of loop does not involve a special keyword but instead uses a different notation style.
 
<source lang=Java5>
for (int i : intArray) {
doSomething(i);
}
</syntaxhighlight>
</source>
 
===Jump statements===
 
====Labels====
Labels are given points in code used by <code>break</code> and <code>continue</code> statements. Despite the presence of theWhile <code>goto</code> is a reserved keyword in Java, it cannot be used to jump to specific points in the code (in fact it has no use at all).
 
<sourcesyntaxhighlight lang=Java5"java">
start:
someMethod();
</syntaxhighlight>
</source>
 
====<code>break</code> statement====
The <code>break</code> statement breaks out of the closest loop or <code>switch</code> statement. Execution continues in the statement after the terminated statement, if any.
 
<sourcesyntaxhighlight lang=Java5"java">
for (int i = 0; i < 10; i++) {
while (true) {
Line 589 ⟶ 805:
// Will break to this point
}
</syntaxhighlight>
</source>
 
It is possible to break out of the outer loop using labels:
 
<sourcesyntaxhighlight lang=Java5"java">
outer:
for (int i = 0; i < 10; i++) {
Line 601 ⟶ 817:
}
// Will break to this point
</syntaxhighlight>
</source>
 
====<code>continue</code> statement====
The <code>continue</code> statement discontinues the current iteration of the current control statement and begins the next iteration. The following <code>while</code> loop in the code below reads characters by calling <code>getChar()</code>, skipping the statements in the body of the loop if the characters are spaces:
 
<sourcesyntaxhighlight lang=Java5"java">
int ch;
while (ch == getChar()) {
if (ch == ' ') {
continue; // Skips the rest of the while-loop
Line 616 ⟶ 832:
doSomething();
}
</syntaxhighlight>
</source>
 
Labels can be specified in <code>continue</code> statements, as they can inand <code>break</code> statements:
 
<sourcesyntaxhighlight lang=Java5"java">
outer:
for (String str : stringsArr) {
Line 633 ⟶ 849:
}
}
</syntaxhighlight>
</source>
 
====<code>return</code> statement====
The <code>return</code> statement is used to end method execution and to return a value. A value returned by the method is written after the <code>return</code> keyword. If the method returns anything but <code>void</code>, it must use the <code>return</code> statement to return some value.
 
<sourcesyntaxhighlight lang=Java5"java">
void doSomething(boolean streamClosed) {
// If streamClosed is true, execution is stopped
Line 651 ⟶ 867:
return result;
}
</syntaxhighlight>
</source>
 
<code>return</code> statement ends execution immediately, except for one case: if the statement is encountered within a <code>try</code> block and it is complemented by a <code>finally</code>, control is passed to the <code>finally</code> block.
 
<sourcesyntaxhighlight lang=Java5"java">
void doSomething(boolean streamClosed) {
try {
Line 668 ⟶ 884:
}
}
</syntaxhighlight>
</source>
 
===Exception handling statements===
Line 675 ⟶ 891:
Exceptions are managed within <code>try</code> ... <code>catch</code> blocks.
 
<syntaxhighlight lang=Java5"java">
try {
// Statements that may throw exceptions
Line 692 ⟶ 908:
Java SE 7 also introduced multi-catch clauses besides uni-catch clauses. This type of catch clauses allows Java to handle different types of exceptions in a single block provided they are not subclasses of each other.
 
<syntaxhighlight lang=Java5"java">
try {
methodThrowingExceptions();
Line 703 ⟶ 919:
If no <code>catch</code> block matches the type of the thrown exception, the execution of the outer block (or method) containing the <code>try</code> ... <code>catch</code> statement is discontinued, and the exception is passed up and outside the containing block (or method). The exception is propagated upwards through the [[call stack]] until a matching <code>catch</code> block is found within one of the currently active methods. If the exception propagates all the way up to the top-most <code>main</code> method without a matching <code>catch</code> block being found, a textual description of the exception is written to the standard output stream.
 
The statements within the <code>finally</code> block are always executed after the <code>try</code> and <code>catch</code> blocks, whether or not an exception was thrown and even if a <code>return</code> statement was reached. Such blocks are useful for providing clean-upcleanup code that is guaranteed to always be executed.
 
The <code>catch</code> and <code>finally</code> blocks are optional, but at least one or the other must be present following the <code>try</code> block.
Line 711 ⟶ 927:
<code>try</code>-with-resources statements are a special type of <code>try-catch-finally</code> statements introduced as an implementation of the [[dispose pattern]] in Java SE 7. In a <code>try</code>-with-resources statement the <code>try</code> keyword is followed by initialization of one or more resources that are released automatically when the <code>try</code> block execution is finished. Resources must implement <code>java.lang.AutoCloseable</code>. <code>try</code>-with-resources statements are not required to have a <code>catch</code> or <code>finally</code> block unlike normal <code>try-catch-finally</code> statements.
 
<syntaxhighlight lang=Java5"java">
try (FileOutputStream fos = new FileOutputStream("filename");
XMLEncoder xEnc = new XMLEncoder(fos)) {
xEnc.writeObject(object);
{
} catch (IOException ex) {
Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);
}
</syntaxhighlight>
 
Since Java 9 it is possible to use already declared variables:
 
<syntaxhighlight lang="java">
FileOutputStream fos = new FileOutputStream("filename");
XMLEncoder xEnc = new XMLEncoder(fos);
try (fos; xEnc) {
xEnc.writeObject(object);
} catch (IOException ex) {
Line 722 ⟶ 949:
 
====<code>throw</code> statement====
The <code>throw</code> statement is used to throw an exception and end the execution of the block (or method). execution.The Thrownthrown exception instance is written after the <code>throw</code> statement.
 
<sourcesyntaxhighlight lang=Java5"java">
void methodThrowingExceptions(Object obj) {
if (obj == null) {
Line 730 ⟶ 957:
throw new NullPointerException();
}
// Will not be called, if object wasis null
doSomethingWithObject(obj);
}
</syntaxhighlight>
</source>
 
===Thread concurrency control===
Java has built-in tools for [[Thread (computer sciencecomputing)|multi-thread programming]]. For the purposes of thread [[Synchronization (computer science)|synchronization]] the <code>synchronized</code> statement is included in Java language.
 
To make a code block synchronized, it is preceded by the <code>synchronized</code> keyword followed by the lock object inside the brackets. When the executing thread reaches the synchronized block, it acquires a [[mutual exclusion]] 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.
 
<syntaxhighlight lang=Java5"java">
/* Acquires lock on someObject. It must be of
a reference type and must be non-null */
Line 749 ⟶ 976:
 
===<code>assert</code> statement===
<code>assert</code> statements have been available since [[J2SE 1.4]]. These types of statements are used to make [[assertion (computing)|assertion]]s in the source code, which can be turned on and off during execution for specific classes or packages. To declare an assertion the <code>assert</code> keyword is used followed by a conditional expression. If it evaluates to <code>false</code> during when the statement is executed, an exception is thrown. This statement maycan include a colon followed by another expression, which will act as the exception's detail message.
 
<sourcesyntaxhighlight lang=Java5"java">
// If n equals 0, AssertionError is thrown
assert n != 0;
Line 757 ⟶ 984:
with the message after the colon */
assert n != 0 : "n was equal to zero";
</syntaxhighlight>
</source>
 
==Primitive types==
Primitive types in Java include integer types, floating-point numbers, [[UTF-16]] code units and a booleanBoolean type. ThereUnlike C++ and C#, there are no unsigned types in Java except <code>char</code> type, which is used to represent UTF-16 code units. The lack of unsigned types is offset by introducing unsigned right shift operation (<code>>>></code>), which is not present in C++, methods such as <code>.toUnsignedInt()</code>. Nevertheless, criticisms have been levelledleveled about the lack of compatibility with C and C++ this causes.<ref>{{cite web|url=http://darksleep.com/player/JavaAndUnsignedTypes.html|first=Sean|last=Owens|title=Java and unsigned int, unsigned short, unsigned byte, unsigned long, etc. (Or rather, the lack thereof)|access-date=April 21, 2010|archive-date=February 20, 2009|archive-url=https://web.archive.org/web/20090220171410/http://darksleep.com/player/JavaAndUnsignedTypes.html|url-status=live}}</ref> <!-- This is a terrible citation. If you have a better one, use it. -->
 
{| class="wikitable"
|-
!colspan="6"|Primitive Typestypes
|-
! Type Namename
! [[Java Class Library|Class Library]] equivalent
! Wrapper class
! Value
! Range
! Size
! Default Valuevalue
|-
| <code>byte</code>
| <code>java.lang.Byte</code>
| integer
| −128 through +127
| 8-bit (1-byte)
| <code>0</code>
|-
| <code>{{java|short</code>}}
| <code>{{java|java.lang.Short</code>}}
| integer
| −32,768 through +32,767
Line 787 ⟶ 1,007:
| <code>0</code>
|-
| <code>{{java|int</code>}}
| <code>{{java|java.lang.Integer</code>}}
| integer
| −2,147,483,648 through +2,147,483,647
Line 794 ⟶ 1,014:
| <code>0</code>
|-
| <code>{{java|long</code>}}
| <code>{{java|java.lang.Long</code>}}
| integer
| −9,223,372,036,854,775,808 through<br/> +9,223,372,036,854,775,807
Line 801 ⟶ 1,021:
| <code>0</code>
|-
| {{java|byte}}
| <code>float</code>
| <code>{{java|java.lang.Float</code>Byte}}
| integer
| -128 through 127
| 8-bit (1-byte)
| <code>0</code>
|-
| {{java|float}}
| {{java|java.lang.Float}}
| floating point number
| ±1.401298E−45 through ±3.402823E+38
| 32-bit (4-byte)
| <code>0.0</code>
| <code>0.0f</code><ref>{{cite web|url=http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html|title=Primitive Data Types}}</ref>
|-
| <code>{{java|double</code>}}
| <code>{{java|java.lang.Double</code>}}
| floating point number
| ±4.94065645841246E−324 through<br/> ±1.79769313486232E+308
Line 815 ⟶ 1,042:
| <code>0.0</code>
|-
| <code>{{java|boolean</code>}}
| <code>{{java|java.lang.Boolean</code>}}
| Boolean
| <code>{{java|true</code>}} or <code>{{java|false</code>}}
| 18-bit (1-bitbyte)
| <code>{{java|false</code>}}
|-
| <code>{{java|char</code>}}
| <code>{{java|java.lang.Character</code>}}
| single Unicode character
| [[UTF-16]] code unit ([[Mapping of Unicode character planes#Basic Multilingual Plane|BMP]] character<br/>or a part of a surrogate pair)
| <code>{{java|'\u0000'</code>}} through <code>{{java|'\uFFFF'</code>}}
| 16-bit (2-byte)
| <code>{{java|'\u0000'</code>}}
|-
| {{java|void}}
| {{java|java.lang.Void}}
| N/A
| N/A
| N/A
| N/A
|}
 
<code>null</code> has no type, neither primitive nor class. Any object type may store <code>null</code>.
 
The class <code>Void</code> is used to hold a reference to the <code>Class</code> object representing the keyword <code>void</code>. It cannot be instantiated as <code>void</code> cannot be the type of any object. For example, <code>CompletableFuture<Void></code> signifies that a <code>CompletableFuture</code> performs a task that does not return a value.
 
The class <code>java.lang.Number</code> represents all numeric values which can be converted to <code>byte</code>, <code>double</code>, <code>float</code>, <code>int</code>, <code>long</code>, and <code>short</code>.
 
<code>char</code> does not necessarily correspond to a single character. It may represent a part of a [[UTF-16#Encoding of characters outside the BMP|surrogate pair]], in which case Unicode code point is represented by a sequence of two <code>char</code> values.
Line 836 ⟶ 1,076:
 
Example:
<sourcesyntaxhighlight lang=Java5"java">
int foo = 42; // Primitive type
Integer bar = foo; /* foo is boxed to bar, bar is of Integer type,
which serves as a wrapper for int */
int foo2 = bar; // Unboxed back to primitive type
</syntaxhighlight>
</source>
 
==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 collectcollects and destroydestroys it some time afterwards.
 
A reference variable is <code>null</code> when it does not reference any object.
Line 851 ⟶ 1,091:
Arrays in Java are created at runtime, just like class instances. Array length is defined at creation and cannot be changed.
 
<sourcesyntaxhighlight lang=Java5"java">
int[] numbers = new int[5];
numbers[0] = 2;
numbers[1] = 5;
int x = numbers[0];
</syntaxhighlight>
</source>
 
====Initializers====
 
<sourcesyntaxhighlight lang=Java5"java">
// Long syntax
int[] numbers = new int[] {20, 1, 42, 15, 34};
// Short syntax
int[] numbers2 = {20, 1, 42, 15, 34};
</syntaxhighlight>
</source>
 
====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.
 
<sourcesyntaxhighlight lang=Java5"java">
int[][] numbers = new int[3][3];
numbers[1][2] = 2;
 
int[][] numbers2 = {{2, 3, 2}, {1, 2, 6}, {2, 4, 5}};
</syntaxhighlight>
</source>
 
Due to the nature of the multi-dimensional arrays, sub-arrays maycan vary in length, so multi-dimensional arrays are not bound to be rectangular unlike C:
<sourcesyntaxhighlight lang=Java>
int[][] numbers = new int[2][]; // Initialization of the first dimension only
 
numbers[0] = new int[3];
numbers[1] = new int[2];
</syntaxhighlight>
</source>
 
===Classes===
[[Class (computer scienceprogramming)|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''.
 
====Declaration====
Line 892 ⟶ 1,132:
|-
! Top-level class
|<sourcesyntaxhighlight lang=Java5"java">
class Foo {
// Class members
}
</syntaxhighlight>
</source>
|-
!Inner class
|<sourcesyntaxhighlight lang=Java5"java">
class Foo { // Top-level class
class BarFoo { // Inner class
// Inner class
class Bar {
// ...
}
}
</syntaxhighlight>
</source>
|-
!Nested class
|<sourcesyntaxhighlight lang=Java5"java">
class Foo { // Top-level class
static class BarFoo { // Nested class
// Nested class
static class Bar {
// ...
}
}
</syntaxhighlight>
</source>
|-
! Local class
|<sourcesyntaxhighlight lang=Java5"java">
class Foo {
void bar() {
class Foobar {// Local class within a method
class Foobar {
// ...
}
}
}
</syntaxhighlight>
</source>
|-
! Anonymous class
|<sourcesyntaxhighlight lang=Java5"java">
class Foo {
void bar() {
new Object() {// Creation of a new anonymous class extending Object
new Object() {};
}
}
</syntaxhighlight>
</source>
|}
 
====InitializationInstantiation====
To use nonNon-static members of thea class itdefine mustthe betypes instantiatedof the [[instance variable]]s and methods, which are related to the objects created from that class. ItTo iscreate donethese objects, the class must be instantiated by using the <code>new</code> keywordoperator and calling the class constructor.
 
<sourcesyntaxhighlight lang=Java5"java">
Foo foo = new Foo();
</syntaxhighlight>
</source>
 
====Accessing members====
Members of both instances and static classes are accessed with the <code>.</code> (dot) operator.
 
'''Accessing an instance member'''<br/>
Instance members can be accessed through the name of a variable.
 
<sourcesyntaxhighlight lang=Java5"java">
String foo = "Hello";
String bar = foo.toUpperCase();
</syntaxhighlight>
</source>
 
'''Accessing a static class member'''<br/>
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 <code>static</code> modifier.
 
<sourcesyntaxhighlight lang=Java5"java">
public class Foo {
public static void doSomething() {
// ...
}
}
Line 964 ⟶ 1,213:
// Calling the static method
Foo.doSomething();
</syntaxhighlight>
</source>
 
====Modifiers====
Line 970 ⟶ 1,219:
 
* '''<code>abstract</code>''' - Specifies that a class only serves as a base class and cannot be instantiated.
 
* '''<code>static</code>''' - Used only for member classes, specifies that the member class does not belong to a specific instance of the containing class.
 
* '''<code>final</code>''' - Classes marked as <code>final</code> cannot be extended from and cannot have any subclasses.
 
* '''<code>strictfp</code>''' - Specifies that all floating-point operations must be carried out conforming to [[IEEE 754]] and forbids using enhanced precision to store intermediate results.
 
=====Abstract class=====
{{Excerpt|Abstract type #Java}}
 
=====Final class=====
{{Excerpt|final (Java)#Final classes}}
 
=====Access modifiers=====
The ''access modifiers'', or ''inheritance modifiers'', set the accessibility of classes, methods, and other members. Members marked as <code>public</code> can be reached from anywhere. If a class or its member does not have any modifiers, default access is assumed.
 
<sourcesyntaxhighlight lang=Java5"java">
public class Foo {
int gobaz() {
return 0;
}
 
private class Bar {
 
}
}
</syntaxhighlight>
</source>
 
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:
Line 1,029 ⟶ 1,282:
 
====Constructors and initializers====
A [[Constructor (computerobject-oriented scienceprogramming)|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:
 
<sourcesyntaxhighlight lang=Java5"java">
class Foo {
String str;
 
Foo() { // Constructor with no arguments
Foo() {}
// Initialization
}
 
Foo(String str) { // Constructor with one argument
Foo(String str) {
this.str = str;
}
}
</syntaxhighlight>
</source>
 
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''.
The purpose of static initializers is to initialize static fields when the class is created. They are declared using <code>static</code> keyword:
 
Static initializers initialize static fields when the class is created. They are declared using the <code>static</code> keyword:
<source lang=Java5>
 
<syntaxhighlight lang="java">
class Foo {
static {
Line 1,054 ⟶ 1,308:
}
}
</syntaxhighlight>
</source>
 
AnyA class is created only once. Therefore, therefore static initializers aren'tare 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 can'tcannot take any arguments and generally they can'tcannot throw any [[Exception handling#Checked exceptions|checked exceptions]] (except in several special cases). Instance initializers are declared in a block without any keywords:
 
<sourcesyntaxhighlight lang=Java5"java">
class Foo {
{
Line 1,064 ⟶ 1,318:
}
}
</syntaxhighlight>
</source>
 
Since Java has a garbage collection mechanism, there are no [[Destructor (computer science)|destructors]]. However, every object has a <code>finalize()</code> method called prior to garbage collection, which couldcan be [[method overriding|overridden]] to implement finalization.
 
====Methods====
All the statements in Java must reside within [[Method (computer programming)|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 <code>void</code>. Unlike in C++, methods in Java are not allowed to have [[default argument]] values and methods are usually overloaded instead.
 
<sourcesyntaxhighlight lang=Java5"java">
class Foo {
int bar(int a, int b) {
return (a * 2) + b;
}
 
/* Overloaded method with the same name but different set of arguments */
int bar(int a) {
return a * 2;
}
}
</syntaxhighlight>
</source>
 
A method is called using <code>.</code> notation on an object, or in the case of a static method, also on the name of a class.
 
<sourcesyntaxhighlight lang=Java5"java">
Foo foo = new Foo();
int result = foo.bar(7, 2); // Non-static method is called on foo
 
int finalResult = Math.abs(result); // Static method call
</syntaxhighlight>
</source>
 
The <code>throws</code> keyword indicates that a method throws an exception. All checked exceptions must be listed in a comma-separated list.
<syntaxhighlight lang="java">
import java.io.IOException;
import java.util.zip.DataFormatException;
 
// Indicates that IOException and DataFormatException may be thrown
Methods throwing exceptions use <code>throws</code> keyword to indicate that. All checked exceptions are mandatory to be declared.
void operateOnFile(File f) throws IOException, DataFormatException {
<source lang=Java5>
// ...
void openStream() throws IOException { // Indicates that IOException may be thrown
}
</syntaxhighlight>
</source>
 
=====Modifiers=====
* '''<code>abstract</code>''' - [[Abstract methodsmethod]]s can be present only in [[abstract classesclass]]es, such methods have no body and must be overridden in a subclass unless it is abstract itself.
* '''<code>static</code>''' - Makes the method static and accessible without creation of a class instance. However static methods cannot access non-static members in the same class.
* '''<code>final</code>''' - Declares that the method cannot be overridden in a subclass.
* '''<code>native</code>''' - Indicates that this method is implemented through [[JNI]] in platform-dependent code. Actual implementation happens outside Java code, and such methods have no body.
* '''<code>strictfp</code>''' - Declares strict conformance to [[IEEE 754]] in carrying out floating-point operations. Now obsolete.
* '''<code>synchronized</code>''' - Declares that a thread executing this method must acquire monitor. For <code>synchronized</code> methods the monitor is the class instance or <code>java.lang.Class</code> if the method is static.
* Access modifiers - Identical to those used with classes.
 
======Final methods======
{{Excerpt|final (Java)#Final methods}}
 
=====Varargs=====
{{Main|Variadic function#In Java}}
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.
 
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 [[variadic function|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.
 
<sourcesyntaxhighlight lang=Java5"java">
void printReport(String header, int... numbers) { // numbers represents varargs
void printReport(String header, int... numbers) {
System.out.println(header);
for (int num : numbers) {
Line 1,121 ⟶ 1,386:
// Calling varargs method
printReport("Report data", 74, 83, 25, 96);
</syntaxhighlight>
</source>
 
====Fields====
Fields, or [[class variablesvariable]]s, can be declared inside the class body to store data.
 
<sourcesyntaxhighlight lang=Java5"java">
class Foo {
double bar;
}
</syntaxhighlight>
</source>
 
Fields can be initialized directly when declared.
 
<sourcesyntaxhighlight lang=Java5"java">
class Foo {
double bar = 2.3;
}
</syntaxhighlight>
</source>
 
=====Modifiers=====
* '''<code>static</code>''' - Makes the field a static member.
* '''<code>final</code>''' - Allows the field to be initialized only once in a constructor or inside initialization block or during its declaration, which everwhichever is earlier.
* '''<code>transient</code>''' - Indicates that this field will not be stored during [[serialization]].
* '''<code>volatile</code>''' - If a field is declared <code>volatile</code>, it is ensured that all threads see a consistent value for the variable.
 
====Inheritance====
Classes in Java maycan only [[Inheritance (computerobject-oriented scienceprogramming)|inherit]] from ''one'' class. A class maycan derivebe derived from any class that is not marked as <code>final</code>. Inheritance is declared using the <code>extends</code> keyword. A class maycan reference itself using the <code>this</code> keyword and its direct superclass using the <code>super</code> keyword.
 
<sourcesyntaxhighlight lang=Java5"java">
class Foo {
 
Line 1,157 ⟶ 1,422:
 
}
</syntaxhighlight>
</source>
 
If a class does not specify theits superclass, it implicitly inherits from <code>java.lang.Object</code> class. Thus all classes in Java are subclasses of <code>Object</code> 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:
 
<syntaxhighlight lang="java">
class Foo {
public Foo(int n) {
// Do something with n
}
}
 
class Foobar extends Foo {
private int number;
// Superclass does not have constructor without parameters
// so we have to specify what constructor of our superclass to use and how
 
public Foobar(int number) {
super(number);
this.number = number;
}
}
</syntaxhighlight>
 
=====Overriding methods=====
Unlike C++, all non-<code>final</code> methods in Java are [[Virtual function|virtual]] and can be overridden by the inheriting classes.
 
<sourcesyntaxhighlight lang=Java5"java">
class Operation {
public int doSomething() {
Line 1,177 ⟶ 1,463:
}
}
</syntaxhighlight>
</source>
 
=====Abstract classes=====
 
An [http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.1.1 Abstract Class] is a class that is incomplete, or is to be considered incomplete, so cannot be instantiated.
 
Normal classes may have abstract methods, that is, methods that are declared but not yet implemented, only if they are abstract classes.
A class C has abstract methods if any of the following is true:
 
* C explicitly contains a declaration of an abstract method.
* Any of C's superclasses has an abstract method and C neither declares nor inherits a method that implements it.
* A direct superinterface of C declares or inherits a method (which is therefore necessarily abstract) and C neither declares nor inherits a method that implements it.
* A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class.
 
<syntaxhighlight lang="java">
Any of C's superclasses has an abstract method and C neither declares nor inherits a method that implements it.
package org.example.test;
 
A direct superinterface of C declares or inherits a method (which is therefore necessarily abstract) and C neither declares nor inherits a method that implements it.
 
A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class.
 
<source lang=Java5>
package org.dwwwp.test;
 
/**
* @author jcrypto
*/
public class AbstractClass {
private static final String hello;
 
static {
System.out.printlnprintf(AbstractClass.class.getName() + "%s: static block runtime%n", Abstract.class.getName());
hello = String.format("hello from %s" +, AbstractClass.class.getName());
}
 
{
System.out.printlnprintf(AbstractClass.class.getName() + "%s: instance block runtime%n", Abstract.class.getName());
}
 
public AbstractClass() {
System.out.printlnprintf(AbstractClass.class.getName() + "%s: constructor runtime%n", Abstract.class.getName());
}
 
Line 1,219 ⟶ 1,499:
}
}
</syntaxhighlight>
</source>
<sourcesyntaxhighlight lang=Java5"java">
package org.dwwwpexample.test;
 
/**
* @author jcrypto
*/
public class CustomClass extends AbstractClass {
 
static {
System.out.printlnprintf(CustomClass.class.getName() + "%s: static block runtime%n", CustomClass.class.getName());
}
 
{
System.out.printlnprintf(CustomClass.class.getName() + "%s: instance block runtime%n", CustomClass.class.getName());
}
 
public CustomClass() {
System.out.printlnprintf("%s: constructor runtime%n", CustomClass.class.getName() + ": constructor runtime");
}
 
Line 1,243 ⟶ 1,520:
CustomClass nc = new CustomClass();
hello();
//AbstractClass.hello(); //also valid
}
}
</syntaxhighlight>
</source>
 
Output:
<sourcesyntaxhighlight lang=Java5"text">
org.dwwwpexample.test.AbstractClass: static block runtime
org.dwwwpexample.test.CustomClass: static block runtime
org.dwwwpexample.test.AbstractClass: instance block runtime
org.dwwwpexample.test.AbstractClass: constructor runtime
org.dwwwpexample.test.CustomClass: instance block runtime
org.dwwwpexample.test.CustomClass: constructor runtime
hello from org.dwwwpexample.test.AbstractClass
</syntaxhighlight>
</source>
 
====Enumerations====
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.
 
<sourcesyntaxhighlight lang=Java5"java">
enum Season {
WINTER, SPRING, SUMMER, AUTUMN
}
</syntaxhighlight>
</source>
 
Enum constants are allowed to have constructors, which are called when the class is loaded:
 
<sourcesyntaxhighlight lang=Java5"java">
public enum Season {
WINTER("Cold"), SPRING("Warmer"), SUMMER("Hot"), AUTUMN("Cooler");
Line 1,284 ⟶ 1,561:
}
}
</syntaxhighlight>
</source>
 
Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class:
 
<sourcesyntaxhighlight lang=Java5"java">
public enum Season {
WINTER {
Line 1,299 ⟶ 1,576:
String getDescription() {return "hot";}
},
AUTUMNFALL {
String getDescription() {return "cooler";}
};
}
</syntaxhighlight>
</source>
 
===Interfaces===
[[Interface (Java)|Interfaces]] are datatypes structures thatwhich contain memberno definitionsfields and notusually define a number of methods without an actual implementation. They are useful to define a contract betweenwith membersany innumber different types that haveof different implementations. Every interface is implicitly abstract. TheInterface onlymethods modifierare allowed to usehave witha interfacessubset apart fromof access modifiers isdepending on the language version, <code>strictfp</code>, which has the same effect as for classes, and also <code>static</code> since Java SE 8.
 
<sourcesyntaxhighlight lang=Java5"java">
interface ActionListener {
int ACTION_ADD = 0;
Line 1,315 ⟶ 1,592:
void actionSelected(int action);
}
</syntaxhighlight>
</source>
 
====Implementing an interface====
An interface is implemented by a class using the <code>implements</code> keyword. It is allowed to implement more than one interface, in which case they are written after <code>implements</code> keyword in a comma-separated list. ClassA class implementing an interface must override all its methods, otherwise it must be declared as abstract.
 
<sourcesyntaxhighlight lang=Java5"java">
interface RequestListener {
int requestReceived();
Line 1,327 ⟶ 1,604:
class ActionHandler implements ActionListener, RequestListener {
public void actionSelected(int action) {
// ...
}
 
public int requestReceived() {
// ...
}
}
 
// Calling method defined by interface
// ActionHandler can be represented as RequestListener...
RequestListener listener = new ActionHandler(); /*ActionHandler can be
RequestListener listener = new ActionHandler();
represented as RequestListener...*/
listener.requestReceived(); /*/ ...and thus is known to implement requestReceived() method
listener.requestReceived() method*/;
</syntaxhighlight>
</source>
 
====Functional interfaces and lambda expressions====
 
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 programming|functional style]]. Functional interfaces can optionally be annotated with the <code>[[@FunctionalInterface]]</code> annotation, which will tell the compiler to check whether the interface actually conforms to a definition of a functional interface.
 
<syntaxhighlight lang="java">
// A functional interface
@FunctionalInterface
interface Calculation {
int calculate(int someNumber, int someOtherNumber);
}
 
// A method which accepts this interface as a parameter
int runCalculation(Calculation calculation) {
return calculation.calculate(1, 2);
}
 
// Using a lambda to call the method
runCalculation((number, otherNumber) -> number + otherNumber);
 
// Equivalent code which uses an anonymous class instead
runCalculation(new Calculation() {
@Override
public int calculate(int someNumber, int someOtherNumber) {
return someNumber + someOtherNumber;
}
})
</syntaxhighlight>
 
Lambda's parameters types do not 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 <code>return</code> 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.<ref>{{Cite web|title=Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)|url=https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html|access-date=August 8, 2021|website=docs.oracle.com|archive-date=June 16, 2020|archive-url=https://web.archive.org/web/20200616055353/https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html|url-status=live}}</ref>
 
<syntaxhighlight lang="java">
// Same call as above, but with fully specified types and a body block
runCalculation((int number, int otherNumber) -> {
return number + otherNumber;
});
 
// A functional interface with a method which has only a single parameter
interface StringExtender {
String extendString(String input);
}
 
// Initializing a variable of this type by using a lambda
StringExtender extender = input -> input + " Extended";
</syntaxhighlight>
 
====Method references====
 
Java allows method references using the operator <code>::</code> (it is not related to the C++ namespace qualifying operator <code>::</code>). 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:
 
{| class="wikitable"
|-
! Reference type !! Example !! Equivalent lambda
|-
| Static || <code>Integer::sum</code> || <code>(number, otherNumber) -> number + otherNumber</code>
|-
| Bound || <code>"LongString"::substring</code> || <code>index -> "LongString".substring(index)</code>
|-
| Unbound || <code>String::isEmpty</code> || <code>string -> string.isEmpty()</code>
|-
| Class constructor || <code>ArrayList<String>::new</code> || <code>capacity -> new ArrayList<String>(capacity)</code>
|-
| Array constructor || <code>String[]::new</code> || <code>size -> new String[size]</code>
|}
 
The code above which calls <code>runCalculation</code> could be replaced with the following using the method references:
 
<syntaxhighlight lang="java>
runCalculation(Integer::sum);
</syntaxhighlight>
 
====Inheritance====
Line 1,344 ⟶ 1,693:
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.
 
<sourcesyntaxhighlight lang=Java5"java">
/* Class implementing this interface must implement methods of both
ActionListener and RequestListener */
interface EventListener extends ActionListener, RequestListener {
}
</syntaxhighlight>
 
====Default methods====
 
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 does not override it.
 
<syntaxhighlight lang="java">
interface StringManipulator {
String extendString(String input);
// A method which is optional to implement
default String shortenString(String input) {
return input.substring(1);
}
}
 
</source>
// This is a valid class despite not implementing all the methods
class PartialStringManipulator implements StringManipulator {
@Override
public String extendString(String input) {
return String.format("%s Extended", input);
}
}
</syntaxhighlight>
 
====Static methods====
{{Main|Method (computer programming)#Static methods}}
 
Static methods is another language feature introduced in Java SE 8. They behave in exactly the same way as in the classes.
 
<syntaxhighlight lang="java">
interface StringUtils {
static String shortenByOneSymbol(String input) {
return input.substring(1);
}
}
 
StringUtils.shortenByOneSymbol("Test");
</syntaxhighlight>
 
====Private methods====
 
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.
 
<syntaxhighlight lang="java">
interface Logger {
default void logError() {
log(Level.ERROR);
}
 
default void logInfo() {
log(Level.INFO);
}
 
private void log(Level level) {
SystemLogger.log(level.id);
}
}
</syntaxhighlight>
 
====Annotations====
Line 1,358 ⟶ 1,764:
=====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 <code>interface</code> keyword is preceded by the <code>@</code> sign. All annotations are implicitly extended from <code>java.lang.annotation.Annotation</code> and cannot be extended from anything else.
<sourcesyntaxhighlight lang=Java5"java">
@interface BlockingOperations {
 
}
</syntaxhighlight>
</source>
 
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 <code>default</code> keyword after the method name:
 
<sourcesyntaxhighlight lang=Java5"java">
@interface BlockingOperations {
boolean fileSystemOperations();
boolean networkOperations() default false;
}
</syntaxhighlight>
</source>
 
=====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 <code>@</code> 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.
 
<sourcesyntaxhighlight lang=Java5"java">
@BlockingOperations(/*mandatory*/ fileSystemOperations = true,
fileSystemOperations, // mandatory
/*optional*/ networkOperations = true)
networkOperations = true // optional
void openOutputStream() { //Annotated method
)
void openOutputStream() {
// annotated method
}
</syntaxhighlight>
</source>
 
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:
<sourcesyntaxhighlight lang=Java5"java">
@Unused // Shorthand for @Unused()
void travelToJupiter() {
 
}
</syntaxhighlight>
</source>
 
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:
 
<sourcesyntaxhighlight lang=Java5"java">
/*
/* Equivalent for @BlockingOperations(fileSystemOperations = true).
Equivalent for @BlockingOperations(fileSystemOperations = true).
networkOperations has a default value and
does not have to be assigned a value
*/
 
@BlockingOperations(true)
void openOutputStream() {
 
}
</syntaxhighlight>
</source>
 
==Generics==
{{Main|Generics in Java}}
 
[[Generic programming|Generics]], or parameterized types, or [[Polymorphism in object-oriented programming#Parametric Polymorphism|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]].<ref>{{Cite web |url=https://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx |title=Generics in the Run Time (C# Programming Guide) |access-date=March 9, 2016 |archive-date=March 10, 2016 |archive-url=https://web.archive.org/web/20160310012449/https://msdn.microsoft.com/en-us/library/f4a6ta2h.aspx |url-status=live }}</ref>
 
===Generic classes===
{{Main|Generics in Java#Generic class definitions}}
Classes can be parameterized by adding a type variable inside angle brackets (<code><</code> and <code>></code>) 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 <code>extends</code> 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 <code>& </code> sign used as the delimiter.
 
<sourcesyntaxhighlight lang=Java5"java">
/* This class has two type variables, T and V. T must be
a subtype of ArrayList and implement Formattable interface */
Line 1,420 ⟶ 1,835:
}
}
</syntaxhighlight>
</source>
 
When a variable of a parametrizedparameterized 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.
 
<syntaxhighlight lang=Java5"java">
/* Mapper is created with CustomList as T and Integer as V.
CustomList must be a subclass of ArrayList and implement Formattable */
Line 1,430 ⟶ 1,845:
</syntaxhighlight>
 
Since Java SE 7, it is possible to use a diamond (<code><></code>) 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:
 
<syntaxhighlight lang=Java5"java">
Mapper<CustomList, Integer> mapper = new Mapper<>();
</syntaxhighlight>
 
When declaring a variable for a parametrizedparameterized type, it is possible to use wildcards instead of explicit type names. [[Wildcard (Java)|Wildcards]] are expressed by writing <code>?</code> 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 <code>extends</code> keyword or the <code>super</code> keyword correspondingly followed by the class name.
 
<syntaxhighlight lang=Java5"java">
/* Any Mapper instance with CustomList as the first parameter
may be used regardless of the second one.*/
Line 1,454 ⟶ 1,869:
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.
 
<sourcesyntaxhighlight lang=Java5"java">
class Mapper {
// The class itself is not generic, the constructor is
<T, V> Mapper(T array, V item) {}
}
}
 
Line 1,471 ⟶ 1,885:
return false;
}
</syntaxhighlight>
</source>
 
===Generic interfaces===
Interfaces can be parametrizedparameterized in the similar manner as the classes.
 
<sourcesyntaxhighlight lang=Java5"java">
interface Expandable<T extends Number> {
void addItem(T item);
}
 
// This class is parametrizedparameterized
class Array<T extends Number> implements Expandable<T> {
void addItem(T item) {
Line 1,492 ⟶ 1,906:
}
}
</syntaxhighlight>
</source>
 
== See also ==
{{Portal|JavaComputer programming}}
* [[Java Platform, Standard Edition]]
* [[C Sharp syntax|C# syntax]]
* [[C++ syntax]]
* [[C syntax]]
 
==References==
Line 1,502 ⟶ 1,919:
 
{{Refbegin}}
* [[{{cite book |last1=Naughton |first1=Patrick |author1-link=Patrick Naughton]], [[|last2=Schildt |first2=Herbert |author2-link=Herbert Schildt]]. ''|year=1999 |title=Java 2: The Complete Reference'', third |edition.=3rd |publisher=The McGraw-Hill Companies, 1999. ISBN |isbn=0-07-211976-4}}
* {{cite book |last1=Vermeulen |last2=Ambler |last3=Bumgardner |last4=Metz |last5=Misfeldt |last6=Shur |last7=Thompson |year=2000 |title=The Elements of Java Style |url-access=registration |url=https://archive.org/details/elementsofjavast00verm |publisher=Cambridge University Press |isbn=0-521-77768-2 }}
* {{cite book | author1 = Vermeulen | author2 = Ambler | author3 = Bumgardner | author4 = Metz | author5 = Misfeldt
* {{cite book |last1=Gosling |first1=James |author1-link=James Gosling |last2=Joy |first2=Bill |author2-link=Bill Joy |last3=Steele |first3=Guy |author3-link=Guy L. Steele Jr. |last4=Bracha |first4=Gilad |year=2005 |title=Java Language Specification |edition=3rd |url=http://java.sun.com/docs/books/jls/ |publisher=Addison-Wesley Professional |access-date=December 3, 2008 |archive-date=February 26, 2009 |archive-url=https://web.archive.org/web/20090226152425/http://java.sun.com/docs/books/jls/ |url-status=live }}
| author6 = Shur | author7 =Thompson | title = The Elements of Java Style
| publisher=Cambridge University Press | year =2000 | isbn = 0-521-77768-2}}
* {{cite book |last1=Gosling |first1=James |author1link=James Gosling |author2=[[Bill Joy|Joy, Bill]]
| author3 = [[Guy Steele|Steele, Guy]] | author4 = [[Gilad Bracha|Bracha, Gillad]]
| title=Java Language Specification |edition=3rd |publisher=Addison-Wesley Professional |year=2005
| url=http://java.sun.com/docs/books/jls/index.html |accessdate=2008-12-03}}
{{Refend}}
 
==External links==
{{Wikibooks|Java Programming/Syntax}}
* [httphttps://docs.oracle.com/javase/specs/ The Java Language Specification, Third edition] Authoritative description of the Java language
* {{Javadoc:SE}}
 
{{Java (Sunsoftware platform)}}
 
<!--Interwikies-->
 
[[Category:Programming language syntax]]
<!--Categories-->
[[Category:Java (programming language)]]
<!-- Hidden categories below -->
[[Category:Articles with example Java code]]