Content deleted Content added
No edit summary Tags: Mobile edit Mobile web edit |
|||
(43 intermediate revisions by 3 users not shown) | |||
Line 292:
Classes in the package java.lang are implicitly imported into every program, as long as no explicitly-imported types have the same names. Important ones include:
===={{mono|java.lang.System}}====
{{code|java.lang.System}} is one of the most fundamental classes in Java. It is a utility class for interacting with the system, containing standard input, output, and error streams, system properties and environment variables, time, and more.
===={{mono|java.lang.Object}}====
{{code|java.lang.Object}} is Java's [[top type]]. It is implicitly the superclass of all classes that do not declare any parent class (thus all classes in Java inherent from <code>Object</code>). All values can be converted to this type, although for primitive values this involves [[Object type (object-oriented programming)#Autoboxing|autoboxing]].
===={{mono|java.lang.Record}}====
All [[Record (computer science)|records]] implicitly extend {{code|java.lang.Record}}. Thus, a <code>record</code>, while treated as a <code>class</code>, cannot extend any other class.
===={{mono|java.lang.Enum}}====
All [[enumerated type]]s (enums) in Java implicitly extend {{code|java.lang.Enum}}. Thus, an <code>enum</code>, while treated as a <code>class</code>, cannot extend any other class.
===={{mono|java.lang.Class<T>}}====
{{code|java.lang.Class<T>}} is a class that represents a <code>class</code> or <code>interface</code> in the application at runtime. It cannot be constructed via direct instantiation, but is rather created by the JVM when a class is derived from the bytes of a <code>.class</code> file. A class literal can be obtained through <code>.class</code> on such a class. For instance, <code>String.class</code> returns <code>Class<String></code>. An unknown class being modeled can be represented as <code>Class<?></code> (where <code>?</code> denotes a [[Wildcard (Java)|wildcard]]).
===={{mono|java.lang.String}}====
{{code|java.lang.String}} is Java's basic string type. It is [[immutable object|
===={{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 317 ⟶ 338:
<syntaxhighlight lang=Java>
public static void main(String[] args) {
// ...
}
</syntaxhighlight>
Line 323 ⟶ 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:
Line 335 ⟶ 358:
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 455 ⟶ 513:
==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 636 ⟶ 694:
<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 646 ⟶ 710:
<syntaxhighlight lang="java">
case 'A':
yield Result.GREAT;
Line 653 ⟶ 717:
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. The condition must have type <code>boolean</code> or
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 699 ⟶ 766:
</syntaxhighlight>
Like C, all three expressions are optional. The following loop
<syntaxhighlight lang="java">
for (;;) {
Line 706 ⟶ 773:
</syntaxhighlight>
====
{{Main|
[[
<syntaxhighlight lang="java">
Line 918 ⟶ 985:
==Primitive types==
Primitive types in Java include integer types, floating-point numbers, [[UTF-16]] code units and a Boolean type.
{| 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 945 ⟶ 1,005:
| <code>0</code>
|-
|
|
| integer
| −2,147,483,648 through +2,147,483,647
Line 952 ⟶ 1,012:
| <code>0</code>
|-
|
|
| integer
| −9,223,372,036,854,775,808 through<br/> +9,223,372,036,854,775,807
Line 959 ⟶ 1,019:
| <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 973 ⟶ 1,040:
| <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 1,037 ⟶ 1,117:
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,058 ⟶ 1,138:
!Inner class
|<syntaxhighlight lang="java">
// Inner class
class Bar {
// ...
}
}
Line 1,066 ⟶ 1,149:
!Nested class
|<syntaxhighlight lang="java">
// Nested class
static class Bar {
// ...
}
}
Line 1,076 ⟶ 1,162:
class Foo {
void bar() {
class Foobar {
// ...
}
}
Line 1,086 ⟶ 1,174:
class Foo {
void bar() {
new Object() {};
}
}
Line 1,117 ⟶ 1,205:
public class Foo {
public static void doSomething() {
// ...
}
}
Line 1,143 ⟶ 1,232:
<syntaxhighlight lang="java">
public class Foo {
int
return 0;
}
private class Bar {
}
}
Line 1,196 ⟶ 1,286:
String str;
Foo() {}
Foo(String str) {
this.str = str;
}
Line 1,237 ⟶ 1,326:
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,258 ⟶ 1,347:
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,267 ⟶ 1,361:
* '''<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,280 ⟶ 1,374:
<syntaxhighlight lang="java">
void printReport(String header, int... numbers) {
System.out.println(header);
for (int num : numbers) {
Line 1,380 ⟶ 1,475:
<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,407 ⟶ 1,499:
</syntaxhighlight>
<syntaxhighlight lang="java">
package org.
public class CustomClass extends AbstractClass {
static {
System.out.
}
{
System.out.
}
public CustomClass() {
System.out.
}
Line 1,429 ⟶ 1,518:
CustomClass nc = new CustomClass();
hello();
}
}
Line 1,436 ⟶ 1,525:
Output:
<syntaxhighlight lang="text">
org.
org.
org.
org.
org.
org.
hello from org.
</syntaxhighlight>
Line 1,513 ⟶ 1,602:
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>
Line 1,573 ⟶ 1,664:
====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,625 ⟶ 1,716:
@Override
public String extendString(String input) {
return
}
}
Line 1,673 ⟶ 1,764:
<syntaxhighlight lang="java">
@interface BlockingOperations {
}
</syntaxhighlight>
Line 1,689 ⟶ 1,781:
<syntaxhighlight lang="java">
@BlockingOperations(
fileSystemOperations, // mandatory
networkOperations = true // optional
)
void openOutputStream() {
// annotated method
}
</syntaxhighlight>
Line 1,699 ⟶ 1,794:
@Unused // Shorthand for @Unused()
void travelToJupiter() {
}
</syntaxhighlight>
Line 1,705 ⟶ 1,801:
<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,723 ⟶ 1,822:
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,750 ⟶ 1,849:
</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,771 ⟶ 1,870:
class Mapper {
// The class itself is not generic, the constructor is
<T, V> Mapper(T array, V item) {}
}
Line 1,811 ⟶ 1,909:
{{Portal|Computer programming}}
* [[Java Platform, Standard Edition]]
* [[C Sharp syntax|C# syntax]]
* [[C++ syntax]]
* [[C syntax]]
|