Content deleted Content added
→Modifiers: Add excerpt for final class |
|||
(87 intermediate revisions by 24 users not shown) | |||
Line 1:
{{Short description|
{{
{{
{{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 Java''' is [[syntax|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
The Java syntax has been gradually extended in the course of numerous major [[JDK]] [[Java version history|releases]], and now supports
==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 22 ⟶ 39:
An identifier cannot:
* Start with a digit.
* Be equal to a reserved keyword, null literal or
===Keywords===
{{Main|List of Java keywords}}
====Keywords====
The following words are keywords and cannot be used as identifiers under any circumstances.
{{div col|colwidth=15em}}
* <code>_</code>
* <code>abstract</code>
* <code>assert</code>
* <code>boolean</code>
* <code>break</code>
* <code>byte</code>
* <code>case</code>
* <code>catch</code>
* <code>char</code>
* <code>class</code>
* <code>continue</code>
* <code>default</code>
* <code>do</code>
* <code>double</code>
* <code>else</code>
* <code>enum</code>
* <code>extends</code>
* <code>final</code>
* <code>finally</code>
* <code>float</code>
* <code>for</code>
* <code>if</code>
* <code>implements</code>
* <code>import</code>
* <code>instanceof</code>
* <code>int</code>
* <code>interface</code>
* <code>long</code>
* <code>native</code>
* <code>new</code>
* <code>package</code>
* <code>private</code>
* <code>protected</code>
* <code>public</code>
* <code>return</code>
* <code>short</code>
* <code>static</code>
* <code>super</code>
* <code>switch</code>
* <code>synchronized</code>
* <code>this</code>
* <code>throw</code>
* <code>throws</code>
* <code>transient</code>
* <code>try</code>
* <code>void</code>
* <code>volatile</code>
* <code>while</code>
{{div col end}}
====Reserved identifiers====
The following words are contextual keywords and are only restricted in certain contexts.
{{div col|colwidth=15em}}
* <code>exports</code>
* <code>module</code>
* <code>non-sealed</code>
* <code>open</code>
* <code>opens</code>
* <code>permits</code>
* <code>provides</code>
* <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 121 ⟶ 159:
|-
!rowspan="2" | double
|{{mono|23.5D}}, {{mono|.5}}, {{mono|5.}}, {{mono|1.72E3D}} (decimal fraction with an optional exponent indicator, followed by optional {{mono|D}})
|-
|{{mono|0x.5FP0}}, {{mono|0x.5P-6D}} ({{mono|0x}} followed by a hexadecimal fraction with a mandatory exponent indicator and an optional suffix {{mono|D}})
Line 184 ⟶ 222:
<syntaxhighlight lang="java">
int count;
count = 35;
int count = 35; // Declaring and initializing the variable at the same time
</syntaxhighlight>
Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.
<syntaxhighlight lang="java">
int a, b;
int a = 2, b = 3; // Declaring and initializing multiple variables of the same type
</syntaxhighlight>
Line 209 ⟶ 247:
===Code blocks===
The separators {{mono|{{(}}}} and {{mono|{{)}}}} 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 228 ⟶ 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++.
Line 255 ⟶ 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.
{{code|java.lang.
===={{mono|java.lang.
{{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.
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 268 ⟶ 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 <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>
Line 276 ⟶ 344:
===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:
<syntaxhighlight lang=Java>
package
public class MyClass {
}
</syntaxhighlight>
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
| 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 295 ⟶ 401:
<syntaxhighlight lang="java">
package
import java.util.Random; // Single type declaration
Line 303 ⟶ 409:
/* The following line is equivalent to
* java.util.Random random = new java.util.Random();
* It would
*/
Random random = new Random();
Line 310 ⟶ 416:
</syntaxhighlight>
Import-on-demand declarations are mentioned in the code. A "
<syntaxhighlight 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
</syntaxhighlight>
====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:
<syntaxhighlight lang="java">
import static java.lang.System.out; // 'out' is a static field in java.lang.System
public class HelloWorld {
Line 369 ⟶ 476:
/* The following line is equivalent to
if (foo == ColorName.RED) foo = ColorName.BLUE; */
if (foo == RED) {
foo = BLUE; }
}
}
</syntaxhighlight>
====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()
));
}
}
Line 375 ⟶ 515:
==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 397 ⟶ 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 =
|-
! rowspan=5| 3
Line 493 ⟶ 633:
====<code>if</code> statement====
{{Main|Conditional (computer programming)#C-like 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 ==
doSomething();
} else {
Line 518 ⟶ 662:
</syntaxhighlight>
Also,
<syntaxhighlight lang="java">
int a = 1;
Line 526 ⟶ 670:
====<code>switch</code> statement====
[[Switch statement]]s in Java can use <code>byte</code>, <code>short</code>, <code>char</code>, and <code>int</code> (
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 552 ⟶ 696:
<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
};
</syntaxhighlight>
Line 562 ⟶ 712:
<syntaxhighlight lang="java">
case 'A':
yield Result.GREAT;
Line 569 ⟶ 719:
yield Result.FINE;
default:
throw new
};
</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.
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====
Line 615 ⟶ 768:
</syntaxhighlight>
Like C, all three expressions are optional. The following loop
<syntaxhighlight lang="java">
for (;;) {
Line 622 ⟶ 775:
</syntaxhighlight>
====
{{Main|
[[
<syntaxhighlight lang="java">
Line 635 ⟶ 788:
====Labels====
Labels are given points in code used by <code>break</code> and <code>continue</code> statements.
<syntaxhighlight lang="java">
Line 766 ⟶ 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
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 834 ⟶ 987:
==Primitive types==
Primitive types in Java include integer types, floating-point numbers, [[UTF-16]] code units and a
{| class="wikitable"
|-
!colspan="6"|Primitive
|-
! Type
! [[Java Class Library|Class Library]] equivalent
! Value
! Range
! Size
! Default
|-
| {{java|short}}
|
| integer
| −32,768 through +32,767
Line 861 ⟶ 1,007:
| <code>0</code>
|-
|
|
| integer
| −2,147,483,648 through +2,147,483,647
Line 868 ⟶ 1,014:
| <code>0</code>
|-
|
|
| integer
| −9,223,372,036,854,775,808 through<br/> +9,223,372,036,854,775,807
Line 875 ⟶ 1,021:
| <code>0</code>
|-
| {{java|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>
|-
|
|
| floating point number
| ±4.94065645841246E−324 through<br/> ±1.79769313486232E+308
Line 889 ⟶ 1,042:
| <code>0.0</code>
|-
|
|
| Boolean
|
|
|
|-
|
|
| single Unicode character
|
| 16-bit (2-byte)
|
|-
| {{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 953 ⟶ 1,119:
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:
<syntaxhighlight lang=Java>
int[][] numbers = new int[2][]; // Initialization of the first dimension only
numbers[0] = new int[3];
Line 974 ⟶ 1,140:
!Inner class
|<syntaxhighlight lang="java">
// Inner class
class Bar {
// ...
}
}
Line 982 ⟶ 1,151:
!Nested class
|<syntaxhighlight lang="java">
// Nested class
static class Bar {
// ...
}
}
Line 992 ⟶ 1,164:
class Foo {
void bar() {
class Foobar {
// ...
}
}
Line 1,002 ⟶ 1,176:
class Foo {
void bar() {
new Object() {};
}
}
Line 1,033 ⟶ 1,207:
public class Foo {
public static void doSomething() {
// ...
}
}
Line 1,047 ⟶ 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=====
Line 1,056 ⟶ 1,234:
<syntaxhighlight lang="java">
public class Foo {
int
return 0;
}
private class Bar {
}
}
Line 1,109 ⟶ 1,288:
String str;
Foo() {}
// Constructor with one argument
Foo(String str) {
this.str = str;
}
Line 1,145 ⟶ 1,323:
====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.
<syntaxhighlight 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;
}
}
Line 1,171 ⟶ 1,349:
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
void operateOnFile(File f) throws IOException, DataFormatException {
// ...
}
</syntaxhighlight>
Line 1,180 ⟶ 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.
<syntaxhighlight lang="java">
void printReport(String header, int... numbers) {
System.out.println(header);
for (int num : numbers) {
Line 1,223 ⟶ 1,412:
====Inheritance====
Classes in Java can only [[Inheritance (
<syntaxhighlight lang="java">
Line 1,288 ⟶ 1,477:
<syntaxhighlight lang="java">
package org.
public class AbstractClass {
private static final String hello;
static {
System.out.
hello = String.format("hello from %s"
}
{
System.out.
}
public AbstractClass() {
System.out.
}
Line 1,315 ⟶ 1,501:
</syntaxhighlight>
<syntaxhighlight lang="java">
package org.
public class CustomClass extends AbstractClass {
static {
System.out.
}
{
System.out.
}
public CustomClass() {
System.out.
}
Line 1,337 ⟶ 1,520:
CustomClass nc = new CustomClass();
hello();
}
}
Line 1,344 ⟶ 1,527:
Output:
<syntaxhighlight lang="text">
org.
org.
org.
org.
org.
org.
hello from org.
</syntaxhighlight>
Line 1,412 ⟶ 1,595:
====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.
<syntaxhighlight lang="java">
Line 1,421 ⟶ 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();
</syntaxhighlight>
====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">
Line 1,462 ⟶ 1,647:
</syntaxhighlight>
Lambda's parameters types
<syntaxhighlight lang="java">
Line 1,481 ⟶ 1,666:
====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"
Line 1,517 ⟶ 1,702:
====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
<syntaxhighlight lang="java">
Line 1,533 ⟶ 1,718:
@Override
public String extendString(String input) {
return
}
}
Line 1,581 ⟶ 1,766:
<syntaxhighlight lang="java">
@interface BlockingOperations {
}
</syntaxhighlight>
Line 1,597 ⟶ 1,783:
<syntaxhighlight lang="java">
@BlockingOperations(
fileSystemOperations, // mandatory
networkOperations = true // optional
)
void openOutputStream() {
// annotated method
}
</syntaxhighlight>
Line 1,607 ⟶ 1,796:
@Unused // Shorthand for @Unused()
void travelToJupiter() {
}
</syntaxhighlight>
Line 1,613 ⟶ 1,803:
<syntaxhighlight lang="java">
/*
Equivalent for @BlockingOperations(fileSystemOperations = true).
networkOperations has a default value and
does not have to be assigned a value
*/ @BlockingOperations(true)
void openOutputStream() {
}
</syntaxhighlight>
Line 1,625 ⟶ 1,818:
{{Main|Generics in Java}}
[[Generic programming|Generics]], or parameterized types, or [[
===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>&
<syntaxhighlight lang="java">
Line 1,657 ⟶ 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,678 ⟶ 1,872:
class Mapper {
// The class itself is not generic, the constructor is
<T, V> Mapper(T array, V item) {}
}
Line 1,718 ⟶ 1,911:
{{Portal|Computer programming}}
* [[Java Platform, Standard Edition]]
* [[C Sharp syntax|C# syntax]]
* [[C++ syntax]]
* [[C syntax]]
==References==
Line 1,723 ⟶ 1,919:
{{Refbegin}}
*
* {{cite book |
* {{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 }}
{{Refend}}
Line 1,736 ⟶ 1,929:
* {{Javadoc:SE}}
{{Java (
[[Category:Programming language syntax]]
[[Category:Java (programming language)]]
<!-- Hidden categories below -->
[[Category:Articles with example Java code]]
|