Java syntax: Difference between revisions

Content deleted Content added
Dormantor (talk | contribs)
No edit summary
 
(145 intermediate revisions by 50 users not shown)
Line 1:
{{Short description|Rules defining correctly structured Java programs}}
{{more footnotes|date=January 2014}}
{{See also|Java (programming language)#Syntax}}
 
{{More footnotes|date=January 2014}}
{{see also|Java (programming_language)#Syntax}}
{{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 the [[Java (programming language)|Java]]''' refers tois [[syntax|the set of rulerules]]s 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 in C++, in Java there arehas no global functions or variables, but there arehas data members which are also regarded as [[global variablesvariable]]s. All 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 class instanceobjects for 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''' has been gradually extended in the course of the elevennumerous major [[JDK]] [[Java version history|releases]], supportand now supports capabilitiesabilities such as [[generic programming]] and [[functionanonymous literalsfunction]]s (function literals, called lambda expressions in Java). Since 2017, a new JDK version is released twice a year, with each release improving 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 23 ⟶ 39:
An identifier cannot:
* Start with a digit.
* Be 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
* <code>case</code>
| default
* <code>catch</code>
| goto
* <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
* <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
* <code>transient</code>
|interface
* <code>try</code>
|static
* <code>void</code>
|var
* <code>volatile</code>
|-
* <code>while</code>
| class
{{div col end}}
| finally
 
| long
====Reserved identifiers====
| strictfp
The following words are contextual keywords and are only restricted in certain contexts.
| void
{{div col|colwidth=15em}}
|-
* <code>exports</code>
| const
* <code>module</code>
| float
* <code>non-sealed</code>
| native
* <code>open</code>
| super
* <code>opens</code>
| volatile
* <code>permits</code>
|-
* <code>provides</code>
| while
* <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 103 ⟶ 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>}} can 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="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="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> 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, braces may be used to create new scopes, as follows:
Line 217 ⟶ 266:
 
===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="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="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. 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="java">
/**
* This is a documentation comment.
Line 238 ⟶ 287:
* @author John Doe
*/
</syntaxhighlight>
</source>
 
===Universal types===
Line 244 ⟶ 293:
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}}====
;java.lang.Object: 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 [[Object type (object-oriented programming)#Autoboxing|autoboxing]].
{{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.
;java.lang.String: Java's basic string type. [[immutable object|Immutable]]. Some methods treat each [[UTF-16]] code unit as a "character", but methods to convert to an <code>int[]</code> that is effectively [[UTF-32]] are also available.
 
;java.lang.Throwable: supertype of everything that can be [[exception handling|thrown or caught]] with Java's <code>throw</code> and <code>catch</code> statements.
===={{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==
Line 252 ⟶ 333:
 
===<code>main</code> method===
{{Main|Entry point#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 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 <code>myapplication.mylibrary.MyClass</code> will have the following path: <code>myapplication/mylibrary/MyClass.java</code>.
| 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====
Line 278 ⟶ 400:
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.
 
<sourcesyntaxhighlight lang="java">
package myPackagecom.myapp;
 
import java.util.Random; // Single type declaration
Line 287 ⟶ 409:
/* The following line is equivalent to
* java.util.Random random = new java.util.Random();
* It would've have been incorrect without the import.
*/
Random random = new Random();
}
}
</syntaxhighlight>
</source>
 
Import-on-demand declarations are mentioned in the code. A "typeglob import" imports all the types of the package. A "static import" imports members of the package.
 
<sourcesyntaxhighlight lang="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="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!");
 
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="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="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="java">
import screen.ColorName;
import static screen.ColorName.*;
Line 352 ⟶ 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 383 ⟶ 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|accessdateaccess-date = 2015-06-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>
|-
! rowspan=5| 3
Line 420 ⟶ 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 430 ⟶ 584:
! 8
| <code>==</code> <code>!=</code>
| Relational “equal"equal to”to" and “not"not equal to”to"
|-
! 9
Line 479 ⟶ 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}}
 
[[Conditional (computer programming)|if statements]] in Java are similar to those in C and use the same syntax:
<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="java">
if (i == 23) {
doSomething();
} else {
Line 504 ⟶ 662:
</syntaxhighlight>
 
Also, note that thea [[?:]] operator can be used in place of simple if statement, for example
<sourcesyntaxhighlight lang="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 531 ⟶ 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.
 
<sourcesyntaxhighlight lang="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="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="java">
for (int i = 0; i < 10; i++) {
doSomething();
Line 567 ⟶ 766:
doSomething();
}
</syntaxhighlight>
</source>
 
Like C, all three expressions are optional. The following loop isnever infiniteterminates:
<sourcesyntaxhighlight lang="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 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. 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="java">
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. Note that the JavaWhile <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="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="java">
for (int i = 0; i < 10; i++) {
while (true) {
Line 606 ⟶ 805:
// Will break to this point
}
</syntaxhighlight>
</source>
 
It is possible to break out of the outer loop using labels:
 
<sourcesyntaxhighlight lang="java">
outer:
for (int i = 0; i < 10; i++) {
Line 618 ⟶ 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="java">
int ch;
while (ch == getChar()) {
Line 633 ⟶ 832:
doSomething();
}
</syntaxhighlight>
</source>
 
Labels can be specified in <code>continue</code> statements and <code>break</code> statements:
 
<sourcesyntaxhighlight lang="java">
outer:
for (String str : stringsArr) {
Line 650 ⟶ 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="java">
void doSomething(boolean streamClosed) {
// If streamClosed is true, execution is stopped
Line 668 ⟶ 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="java">
void doSomething(boolean streamClosed) {
try {
Line 685 ⟶ 884:
}
}
</syntaxhighlight>
</source>
 
===Exception handling statements===
Line 720 ⟶ 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 730 ⟶ 929:
<syntaxhighlight lang="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 741 ⟶ 951:
The <code>throw</code> statement is used to throw an exception and end the execution of the block or method. The thrown exception instance is written after the <code>throw</code> statement.
 
<sourcesyntaxhighlight lang="java">
void methodThrowingExceptions(Object obj) {
if (obj == null) {
Line 750 ⟶ 960:
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.
Line 768 ⟶ 978:
<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> when the statement is executed, an exception is thrown. This statement can include a colon followed by another expression, which will act as the exception's detail message.
 
<sourcesyntaxhighlight lang="java">
// If n equals 0, AssertionError is thrown
assert n != 0;
Line 774 ⟶ 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 leveled 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
|-
| {{java|short}}
| <code>byte</code>
| <code>{{java|java.lang.Byte</code>Short}}
| integer
| −128 through +127
| 8-bit (1-byte)
| <code>0</code>
|-
| <code>short</code>
| <code>java.lang.Short</code>
| integer
| −32,768 through +32,767
Line 804 ⟶ 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 811 ⟶ 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 818 ⟶ 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 832 ⟶ 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 853 ⟶ 1,076:
 
Example:
<sourcesyntaxhighlight lang="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==
Line 868 ⟶ 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="java">
int[] numbers = new int[5];
numbers[0] = 2;
numbers[1] = 5;
int x = numbers[0];
</syntaxhighlight>
</source>
 
====Initializers====
 
<sourcesyntaxhighlight lang="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="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 can 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 909 ⟶ 1,132:
|-
! Top-level class
|<sourcesyntaxhighlight lang="java">
class Foo {
// Class members
}
</syntaxhighlight>
</source>
|-
!Inner class
|<sourcesyntaxhighlight lang="java">
class Foo { // Top-level class
class BarFoo { // Inner class
// Inner class
class Bar {
// ...
}
}
</syntaxhighlight>
</source>
|-
!Nested class
|<sourcesyntaxhighlight lang="java">
class Foo { // Top-level class
static class BarFoo { // Nested class
// Nested class
static class Bar {
// ...
}
}
</syntaxhighlight>
</source>
|-
! Local class
|<sourcesyntaxhighlight lang="java">
class Foo {
void bar() {
class Foobar {// Local class within a method
class Foobar {
// ...
}
}
}
</syntaxhighlight>
</source>
|-
! Anonymous class
|<sourcesyntaxhighlight lang="java">
class Foo {
void bar() {
new Object() {// Creation of a new anonymous class extending Object
new Object() {};
}
}
</syntaxhighlight>
</source>
|}
 
====Instantiation====
Non-static members of a class define the types of the [[instance variablesvariable]]s and methods, which are related to the objects created from that class. To create these objects, the class must be instantiated by using the <code>new</code> operator and calling the class constructor.
 
<sourcesyntaxhighlight lang="java">
Foo foo = new Foo();
</syntaxhighlight>
</source>
 
====Accessing members====
Line 965 ⟶ 1,196:
Instance members can be accessed through the name of a variable.
 
<sourcesyntaxhighlight lang="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="java">
public class Foo {
public static void doSomething() {
// ...
}
}
Line 981 ⟶ 1,213:
// Calling the static method
Foo.doSomething();
</syntaxhighlight>
</source>
 
====Modifiers====
Line 990 ⟶ 1,222:
* '''<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="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,043 ⟶ 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="java">
class Foo {
String str;
 
Foo() { // Constructor with no arguments
Foo() {}
 
// Constructor with one argument
// Initialization
Foo(String str) {
}
 
Foo(String str) { // Constructor with one argument
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''.
Line 1,064 ⟶ 1,302:
Static initializers initialize static fields when the class is created. They are declared using the <code>static</code> keyword:
 
<sourcesyntaxhighlight lang="java">
class Foo {
static {
Line 1,070 ⟶ 1,308:
}
}
</syntaxhighlight>
</source>
 
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 [[Exception handling#Checked exceptions|checked exceptions]] (except in several special cases). Instance initializers are declared in a block without any keywords:
 
<sourcesyntaxhighlight lang="java">
class Foo {
{
Line 1,080 ⟶ 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 can 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="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="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.
<sourcesyntaxhighlight lang="java">
import java.io.IOException;
void openStream() throws IOException, myException { // Indicates that IOException may be thrown
import java.util.zip.DataFormatException;
}
</source>
 
// Indicates that IOException and DataFormatException may be thrown
=====Lambda expressions=====
void operateOnFile(File f) throws IOException, DataFormatException {
<source lang="text">
// ...
(variables) -> {body}
}
variable -> body_with_one_statement
</syntaxhighlight>
(type variable) -> {}
</source>
 
=====Modifiers=====
Line 1,127 ⟶ 1,363:
* '''<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 [[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="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,144 ⟶ 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="java">
class Foo {
double bar;
}
</syntaxhighlight>
</source>
 
Fields can be initialized directly when declared.
 
<sourcesyntaxhighlight lang="java">
class Foo {
double bar = 2.3;
}
</syntaxhighlight>
</source>
 
=====Modifiers=====
Line 1,170 ⟶ 1,412:
 
====Inheritance====
Classes in Java can only [[Inheritance (computerobject-oriented scienceprogramming)|inherit]] from ''one'' class. A class can be derived from any class that is not marked as <code>final</code>. Inheritance is declared using the <code>extends</code> keyword. A class can reference itself using the <code>this</code> keyword and its direct superclass using the <code>super</code> keyword.
 
<sourcesyntaxhighlight lang="java">
class Foo {
 
Line 1,180 ⟶ 1,422:
 
}
</syntaxhighlight>
</source>
 
If a class does not specify its superclass, it implicitly inherits from <code>java.lang.Object</code> class. Thus all classes in Java are subclasses of <code>Object</code> class.
Line 1,186 ⟶ 1,428:
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:
 
<sourcesyntaxhighlight lang="java">
class Foo {
public Foo(int n) {
Line 1,203 ⟶ 1,445:
}
}
</syntaxhighlight>
</source>
 
=====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="java">
class Operation {
public int doSomething() {
Line 1,221 ⟶ 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:
 
Line 1,234 ⟶ 1,476:
* 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.
 
<sourcesyntaxhighlight lang="java">
package org.dwwwpexample.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,260 ⟶ 1,499:
}
}
</syntaxhighlight>
</source>
<sourcesyntaxhighlight lang="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,284 ⟶ 1,520:
CustomClass nc = new CustomClass();
hello();
//AbstractClass.hello(); //also valid
}
}
</syntaxhighlight>
</source>
 
Output:
<sourcesyntaxhighlight lang="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="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="java">
public enum Season {
WINTER("Cold"), SPRING("Warmer"), SUMMER("Hot"), AUTUMN("Cooler");
Line 1,325 ⟶ 1,561:
}
}
</syntaxhighlight>
</source>
 
Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class:
 
<sourcesyntaxhighlight lang="java">
public enum Season {
WINTER {
Line 1,344 ⟶ 1,580:
};
}
</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="java">
interface ActionListener {
int ACTION_ADD = 0;
Line 1,356 ⟶ 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="java">
interface RequestListener {
int requestReceived();
Line 1,368 ⟶ 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,385 ⟶ 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="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,399 ⟶ 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="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="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="java">
@BlockingOperations(/*mandatory*/ fileSystemOperations,
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="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="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="java">
/* This class has two type variables, T and V. T must be
a subtype of ArrayList and implement Formattable interface */
Line 1,461 ⟶ 1,835:
}
}
</syntaxhighlight>
</source>
 
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.
Line 1,477 ⟶ 1,851:
</syntaxhighlight>
 
When declaring a variable for a parameterized 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="java">
Line 1,495 ⟶ 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="java">
class Mapper {
// The class itself is not generic, the constructor is
<T, V> Mapper(T array, V item) {}
}
}
 
Line 1,512 ⟶ 1,885:
return false;
}
</syntaxhighlight>
</source>
 
===Generic interfaces===
Interfaces can be parameterized in the similar manner as the classes.
 
<sourcesyntaxhighlight lang="java">
interface Expandable<T extends Number> {
void addItem(T item);
Line 1,533 ⟶ 1,906:
}
}
</syntaxhighlight>
</source>
 
== See also ==
{{Portal|Computer programming}}
* [[Java Platform, Standard Edition]]
* [[C Sharp syntax|C# syntax]]
* [[C++ syntax]]
* [[C syntax]]
 
==References==
Line 1,543 ⟶ 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 | author1 last1= Vermeulen | author2 last2= Ambler | author3 last3= Bumgardner | author4 last4= Metz | author5 last5= Misfeldt | author6 last6= Shur | author7 last7= Thompson |year=2000 |title = The Elements of Java Style | publisher = Cambridge University Press | year = 2000 | isbn = 0-521-77768-2 | url-access = registration | url = https://archive.org/details/elementsofjavast00verm |publisher=Cambridge University Press |isbn=0-521-77768-2 }}
* {{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 }}
* {{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-->
 
<!--Categories-->
[[Category:Programming language syntax]]
[[Category:Java (programming language)]]
<!-- Hidden categories below -->
[[Category:Articles with example Java code]]