Java syntax: Difference between revisions

Content deleted Content added
Tags: Mobile edit Mobile web edit
 
(34 intermediate revisions by 2 users not shown)
Line 304:
===={{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|Immutableimmutable]]. 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}}====
Line 318 ⟶ 327:
 
====Primitives====
Each primitive type has an associated wrapper class (see [[#Primitive types|primitive types]]).
Java includes class versions of primitive types. These are as follows:
{| class="wikitable"
|-
!colspan="6"|Primitive types
|-
! Type name
! [[Java Class Library|Class Library]] equivalent
! Value
! Range
! Size
! Default value
|-
| {{java|short}}
| {{java|java.lang.Short}}
| integer
| −32,768 through +32,767
| 16-bit (2-byte)
| <code>0</code>
|-
| {{java|int}}
| {{java|java.lang.Integer}}
| integer
| −2,147,483,648 through +2,147,483,647
| 32-bit (4-byte)
| <code>0</code>
|-
| {{java|long}}
| {{java|java.lang.Long}}
| integer
| −9,223,372,036,854,775,808 through<br/> +9,223,372,036,854,775,807
| 64-bit (8-byte)
| <code>0</code>
|-
| {{java|byte}}
| {{java|java.lang.Byte}}
| unsigned integer
| 0 through 255
| 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>
|-
| {{java|double}}
| {{java|java.lang.Double}}
| floating point number
| ±4.94065645841246E−324 through<br/> ±1.79769313486232E+308
| 64-bit (8-byte)
| <code>0.0</code>
|-
| {{java|boolean}}
| {{java|java.lang.Boolean}}
| Boolean
| {{java|true}} or {{java|false}}
| 8-bit (1-byte)
| {{java|false}}
|-
| {{java|char}}
| {{java|java.lang.Character}}
| single Unicode character
| {{java|'\u0000'}} through {{java|'\uFFFF'}}
| 16-bit (2-byte)
| {{java|'\u0000'}}
|}
 
Java does not have support for unsigned integers like C++ and C#. However, Java has methods to treat integer types as unsigned, such as <code>.toUnsignedInt()</code>.
 
<code>null</code> has no type, neither primitive nor class. Any object type may store <code>null</code>.
 
==Program structure==
Line 400 ⟶ 338:
<syntaxhighlight lang=Java>
public static void main(String[] args) {
// ...
 
}
</syntaxhighlight>
Line 456 ⟶ 394:
 
===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 537 ⟶ 476:
/* The following line is equivalent to
if (foo == ColorName.RED) foo = ColorName.BLUE; */
if (foo == RED) {
foo = BLUE;
}
}
}
Line 574 ⟶ 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 755 ⟶ 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 765 ⟶ 712:
 
<syntaxhighlight lang="java">
varResult result = switch (ch) {
case 'A':
yield Result.GREAT;
Line 772 ⟶ 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 818 ⟶ 768:
</syntaxhighlight>
 
Like C, all three expressions are optional. The following loop isnever infiniteterminates:
<syntaxhighlight lang="java">
for (;;) {
Line 825 ⟶ 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 838 ⟶ 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 1,037 ⟶ 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 1,064 ⟶ 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 1,071 ⟶ 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 1,078 ⟶ 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 1,092 ⟶ 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 1,156 ⟶ 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,177 ⟶ 1,140:
!Inner class
|<syntaxhighlight lang="java">
class Foo { // Top-level class
class BarFoo { // Inner class
// Inner class
class Bar {
// ...
}
}
Line 1,185 ⟶ 1,151:
!Nested class
|<syntaxhighlight lang="java">
class Foo { // Top-level class
static class BarFoo { // Nested class
// Nested class
static class Bar {
// ...
}
}
Line 1,195 ⟶ 1,164:
class Foo {
void bar() {
class Foobar {// Local class within a method
class Foobar {
// ...
}
}
Line 1,205 ⟶ 1,176:
class Foo {
void bar() {
new Object() {// Creation of a new anonymous class extending Object
new Object() {};
}
}
Line 1,236 ⟶ 1,207:
public class Foo {
public static void doSomething() {
// ...
}
}
Line 1,262 ⟶ 1,234:
<syntaxhighlight lang="java">
public class Foo {
int gobaz() {
return 0;
}
 
private class Bar {
 
}
}
Line 1,315 ⟶ 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,356 ⟶ 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,377 ⟶ 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,386 ⟶ 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,399 ⟶ 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,499 ⟶ 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,526 ⟶ 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,548 ⟶ 1,520:
CustomClass nc = new CustomClass();
hello();
//AbstractClass.hello(); //also valid
}
}
Line 1,555 ⟶ 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,632 ⟶ 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,744 ⟶ 1,718:
@Override
public String extendString(String input) {
return input + String.format("%s Extended", input);
}
}
Line 1,792 ⟶ 1,766:
<syntaxhighlight lang="java">
@interface BlockingOperations {
 
}
</syntaxhighlight>
Line 1,808 ⟶ 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,818 ⟶ 1,796:
@Unused // Shorthand for @Unused()
void travelToJupiter() {
 
}
</syntaxhighlight>
Line 1,824 ⟶ 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,842 ⟶ 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,869 ⟶ 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,890 ⟶ 1,872:
class Mapper {
// The class itself is not generic, the constructor is
<T, V> Mapper(T array, V item) {}
}
}