Java syntax: Difference between revisions

Content deleted Content added
 
(59 intermediate revisions by 8 users not shown)
Line 1:
{{Short description|Set of rulesRules defining correctly structured programJava programs}}
{{See also|Java (programming language)#Syntax}}
{{More footnotes|date=January 2014}}
{{Use mdy dates|date=April 2025}}
{{Use American English|date=April 2025}}
[[File:Java keywords highlighted.svg|thumb|300px|A snippet of Java code with keywords highlighted in bold blue font]]
 
Line 10 ⟶ 12:
The Java syntax has been gradually extended in the course of numerous major [[JDK]] [[Java version history|releases]], and now supports abilities such as [[generic programming]] and [[anonymous function]]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 - Java==
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 205 ⟶ 222:
 
<syntaxhighlight 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>
 
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; // Declaring multiple variables of the same type
int a = 2, b = 3; // Declaring and initializing multiple variables of the same type
</syntaxhighlight>
 
Line 276 ⟶ 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.ObjectSystem}}====
{{code|java.lang.ObjectSystem}} is Java'sone [[topof type]].the Superclassmost of allfundamental classes thatin doJava. notIt declareis a parentutility class. Allfor valuesinteracting canwith bethe convertedsystem, tocontaining thisstandard typeinput, althoughoutput, forand primitiveerror valuesstreams, thissystem involvesproperties [[Objectand typeenvironment variables, time, (object-orientedand programming)#Autoboxing|autoboxing]]more.
 
===={{mono|java.lang.StringObject}}====
{{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]].
{{code|java.lang.String}} is 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.
 
===={{mono|java.lang.ThrowableRecord}}====
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.
{{code|java.lang.Throwable}} is 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.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 291 ⟶ 335:
{{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 299 ⟶ 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 myapplicationcom.myapp.mylibrary;
 
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
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>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 318 ⟶ 401:
 
<syntaxhighlight lang="java">
package myPackagecom.myapp;
 
import java.util.Random; // Single type declaration
Line 326 ⟶ 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();
Line 333 ⟶ 416:
</syntaxhighlight>
 
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.
 
<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 doeswill not import all available classes. */
</syntaxhighlight>
 
Line 350 ⟶ 433:
 
<syntaxhighlight lang="java">
import static java.lang.System.out; // 'out' is a static field in java.lang.System
 
public class HelloWorld {
Line 393 ⟶ 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 399 ⟶ 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 421 ⟶ 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 = 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 554 ⟶ 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> (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=2021-08-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 type]]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 580 ⟶ 696:
 
<syntaxhighlight lang="java">
enum Result {
var result = switch (ch) {
GREAT,
FINE,
// more enum values
}
 
Result result = switch (ch) {
case 'A' -> Result.GREAT;
case 'B', 'C' -> Result.FINE;
default -> throw new ThisIsNoGoodExceptionException();
};
</syntaxhighlight>
Line 590 ⟶ 712:
 
<syntaxhighlight lang="java">
varResult result = switch (ch) {
case 'A':
yield Result.GREAT;
Line 597 ⟶ 719:
yield Result.FINE;
default:
throw new ThisIsNoGoodExceptionException();
};
</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>. meaningJava C's<syntaxhighlightdoes lang="c">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>results in a compilation error.
 
====<code>while</code> loop====
Line 643 ⟶ 768:
</syntaxhighlight>
 
Like C, all three expressions are optional. The following loop isnever infiniteterminates:
<syntaxhighlight lang="java">
for (;;) {
Line 650 ⟶ 775:
</syntaxhighlight>
 
====Enhanced <code>for</code>Foreach loop====
{{Main|Enhanced forForeach loop}}
[[enhanced for loop|Enhanced <code>for</code>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">
Line 663 ⟶ 788:
 
====Labels====
Labels are given points in code used by <code>break</code> and <code>continue</code> statements. The JavaWhile <code>goto</code> is a reserved keyword in Java, it cannot be used to jump to specific points in code (in fact it has no use at all).
 
<syntaxhighlight lang="java">
Line 794 ⟶ 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 862 ⟶ 987:
 
==Primitive types==
Primitive types in Java include integer types, floating-point numbers, [[UTF-16]] code units and a Boolean 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
! [[Primitive wrapper class in Java|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 889 ⟶ 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 896 ⟶ 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 903 ⟶ 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 917 ⟶ 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 981 ⟶ 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 1,002 ⟶ 1,140:
!Inner class
|<syntaxhighlight lang="java">
class Foo { // Top-level class
class BarFoo { // Inner class
// Inner class
class Bar {
// ...
}
}
Line 1,010 ⟶ 1,151:
!Nested class
|<syntaxhighlight lang="java">
class Foo { // Top-level class
static class BarFoo { // Nested class
// Nested class
static class Bar {
// ...
}
}
Line 1,020 ⟶ 1,164:
class Foo {
void bar() {
class Foobar {// Local class within a method
class Foobar {
// ...
}
}
Line 1,030 ⟶ 1,176:
class Foo {
void bar() {
new Object() {// Creation of a new anonymous class extending Object
new Object() {};
}
}
Line 1,061 ⟶ 1,207:
public class Foo {
public static void doSomething() {
// ...
}
}
Line 1,087 ⟶ 1,234:
<syntaxhighlight lang="java">
public class Foo {
int gobaz() {
return 0;
}
 
private class Bar {
 
}
}
Line 1,140 ⟶ 1,288:
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;
}
Line 1,181 ⟶ 1,328:
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,202 ⟶ 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;
void openStream() throws IOException, myException { // Indicates that IOException may be thrown
import java.util.zip.DataFormatException;
 
// Indicates that IOException and DataFormatException may be thrown
void operateOnFile(File f) throws IOException, DataFormatException {
// ...
}
</syntaxhighlight>
Line 1,211 ⟶ 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.
Line 1,224 ⟶ 1,376:
 
<syntaxhighlight 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,324 ⟶ 1,477:
 
<syntaxhighlight 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,351 ⟶ 1,501:
</syntaxhighlight>
<syntaxhighlight 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,373 ⟶ 1,520:
CustomClass nc = new CustomClass();
hello();
//AbstractClass.hello(); //also valid
}
}
Line 1,380 ⟶ 1,527:
Output:
<syntaxhighlight 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>
 
Line 1,457 ⟶ 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>
 
Line 1,498 ⟶ 1,647:
</syntaxhighlight>
 
Lambda's parameters types don'tdo 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-08-08|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">
Line 1,517 ⟶ 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,553 ⟶ 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 doesn'tdoes not override it.
 
<syntaxhighlight lang="java">
Line 1,569 ⟶ 1,718:
@Override
public String extendString(String input) {
return input + String.format("%s Extended", input);
}
}
Line 1,617 ⟶ 1,766:
<syntaxhighlight lang="java">
@interface BlockingOperations {
 
}
</syntaxhighlight>
Line 1,633 ⟶ 1,783:
 
<syntaxhighlight lang="java">
@BlockingOperations(/*mandatory*/ fileSystemOperations,
fileSystemOperations, // mandatory
/*optional*/ networkOperations = true)
networkOperations = true // optional
void openOutputStream() { //Annotated method
)
void openOutputStream() {
// annotated method
}
</syntaxhighlight>
Line 1,643 ⟶ 1,796:
@Unused // Shorthand for @Unused()
void travelToJupiter() {
 
}
</syntaxhighlight>
Line 1,649 ⟶ 1,803:
 
<syntaxhighlight 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>
Line 1,661 ⟶ 1,818:
{{Main|Generics in Java}}
 
[[Generic programming|Generics]], or parameterized types, or [[parametric polymorphism]], is one of the major features introduced in [[J2SE 5.0]]. Before generics were introduced, it was required to declare all the types explicitly. With generics, it became possible to work in a similar manner with different types without declaring the exact types. The main purpose of generics is to ensure type safety and to detect runtime errors during compilation. Unlike C#, information on the used parameters is not available at runtime due to [[type erasure]].<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===
Line 1,667 ⟶ 1,824:
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.
 
<syntaxhighlight lang="java">
Line 1,694 ⟶ 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,715 ⟶ 1,872:
class Mapper {
// The class itself is not generic, the constructor is
<T, V> Mapper(T array, V item) {}
}
}
 
Line 1,755 ⟶ 1,911:
{{Portal|Computer programming}}
* [[Java Platform, Standard Edition]]
* [[C Sharp syntax|C# syntax]]
* [[C++ syntax]]
* [[C syntax]]
Line 1,764 ⟶ 1,920:
{{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 |edition=3rd |publisher=The McGraw-Hill Companies |isbn=0-07-211976-4}}
* {{cite book |last1=Vermeulen |last2=Ambler |last3=Bumgardner |last4=Metz |last5=Misfeldt |last6=Shur |last7=Thompson |year=2000 |title=The Elements of Java Style |url-access=registration |url=https://archive.org/details/elementsofjavast00verm |publisher=Cambridge University Press |isbn=0-521-77768-2 }}
* {{cite book |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-12date=February 26, 2009 |archive-03url=https://web.archive.org/web/20090226152425/http://java.sun.com/docs/books/jls/ |url-status=live }}
{{Refend}}