Java syntax

from Wikipedia, the free encyclopedia
Duke, the Java mascot

The syntax of the Java programming language is defined in the Java Language Specification , as is the semantics of Java.

This article gives an overview of Java syntax and highlights some of its specifics. Details are provided in the Sun Microsystems Java Language Specification .

terminology

Since Java is a programming language, for the description of which mainly English-language terms are used, but German translations of certain components are also used in the literature, the ambiguity should be clarified at this point and the expressions used by this article should also be determined to avoid confusion can be excluded. The following are the terms used in this article and their English or German equivalents.

Expression
(Engl. Expression ) An expression is understood to be any complex language construct whose evaluation results in a single, well-defined value. In the simplest case, an expression is a constant, such as E.g. the keyword true or a number (e.g. 1 or 0x7fff ). More complex expressions are comparisons or calculations with multiple variables and constants. Within the grammar descriptions, a distinction is often made between different types of expressions (e.g. numerical, literal, etc.), which should not be the case here.
Instruction
(English. Statement , Instruction or Command ; also called command ) In Java, as in many other imperative programming languages, an instruction refers to a single rule that is to be executed within the framework of the execution of the program. This includes the declaration of variables, expressions terminated by semicolons, control structures, instruction blocks, jump instructions, synchronization blocks, return of values ​​and the triggering of exceptions.
Statement block
(Engl. statement Block ) An instruction block is used to group multiple instructions. This means that several statements can be interpreted as a single statement, which is a requirement of some language constructs - such as the control structures.

Lexical structure

Java programs are written in Unicode . In contrast to other languages, identifiers of classes, methods, variables etc. can contain not only the letters of the Latin alphabet and digits, but also characters from other alphabets, such as B. German umlauts or Chinese characters.

All keywords in Java are written in lower case, e.g. B. " class" or " if".

Letter symbols (English literals ) are in Java, the smallest possible expressions for numbers, individual characters, character strings ( strings ) logical values ( trueor false) and the specific word null.

Delimiter (English separators ) are different types of braces and commas, periods, and semicolons.

Java knows the logical , comparison and mathematical operators common in programming languages . The syntax is based on the C ++ programming language . For example, the single equal sign " =" is used as an assignment operator, while the double equal sign " ==" is used for comparisons .

Spaces, line endings and comments can be inserted anywhere between the identifiers, keywords, letter symbols, separators and operators.

syntax

Data types

Java knows two types of data : primitive data type and references to objects. The primitive data types are one reason why Java is not strictly an object-oriented language.

Primitive data types

There are eight primitive data types. They have different sizes and properties and are used to calculate and store discrete numerical values. All of these data types have a fixed size that is the same for all platforms. For each type there is a corresponding wrapper class so that they can also be treated as real objects.

Data type Size (a) Wrapper class Range of values description
boolean 1 bit java.lang.Boolean true / false Boolean truth value
char 16 bit java.lang.Character U + 0000… U + FFFF Unicode character (= symbol) (e.g. 'A'or '\uC3A4')
byte 8 bit java.lang.Byte −128 ... +127 Two's complement value
short 16 bit java.lang.Short −32,768 ... +32,767 Two's complement value
int 32 bit java.lang.Integer −2,147,483,648… +2,147,483,647 Two's complement value
long 64 bit java.lang.Long −9.223.372.036.854.775.808…
+9.223.372.036.854.775.807
Two's complement value
float 32 bit java.lang.Float ± 1.4E − 45… ± 3.4E + 38 Floating point number ( IEEE 754 )
double 64 bit java.lang.Double ± 4.9E − 324… ± 1.7E + 308 Double precision floating point number (IEEE 754)
(a)Specifies the size of the range of values. The actual memory requirement depends on the platform and implementation of the Java virtual machine.
Typecast

The hierarchy for converting ( typecasting ) of the primitive data types can be guessed from the above table. The numeric data types can be converted to the next larger data type without loss, but not vice versa. A “ int” can be converted implicitly, without a special operator, into a “ long”, but not vice versa.

int i = 12345;
long l = i;

However, to convert, for example, a “ long” to a “ int” in the opposite direction , the type conversion operator must be used. Information can also be lost in the process.

long l = 12345678901L;
int i = (int) l;

A iloss of information occurs here: " " has the value −539222987 after the assignment, because the more significant bytes are cut off.

The primitive data type " boolean" cannot be converted into any other data type. Characters of type " char" can be implicitly converted to any integer type from " int". This is particularly due to the fact that " char" is the only unsigned data type known in Java. A lossless conversion to " short" is no longer possible from the value 32768.

credentials

All objects and fields are in the heap memory and are therefore referenced via an address. Object access in Java is implemented using references that are similar to pointers known from C / C ++. The language definition (Java Language Specification) refers to them as "Reference Values" to make it clear that they are transferred by call-by-value . In Java there is no direct way to display the memory address of a reference or to modify it, which excludes so-called pointer arithmetic in Java.

Object a = new Object();  // a referenziert das gerade neu erstellte Objekt
Object b = a;             // b referenziert dasselbe Objekt wie a
a = null;                 // a referenziert kein Objekt mehr, enthält somit die reservierte Adresse null.

It should be noted here that character strings (class String) also represent reference types and therefore their content must always equals()be compared using the method (" ==" only checks the references, i.e. memory addresses). This is in contrast to programming languages ​​such as C ++ and C # , which support full operator overload and "hallo"=="hallo"carry out content comparisons.

Reserved words

constand gotoare reserved, but without function, so no keywords in the actual sense. They only serve the compiler to output useful error messages for those switching from C ++ or C.

true, falseand nullare literals, but also not actually keywords in the strict sense.

With assertare assertions realized.

private, protectedAnd publicare access modifiers ( access modifier ):

The class itself Package classes /
inner classes
Subclasses Other
classes
private Yes No No No
(without) Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes
  1. To enable inner classes to access private methods and properties, the compiler creates static, package-private methods that emulate calling, setting or reading. These methods have the name access$xxx, where stands xxxfor a sequential number.
  2. Often referred to as "package private", although this access modifier does not exist.

Private methods are excluded from the polymorphism; H. defining a method with the same signature in a subclass is not considered overwriting (but rather hiding ).

staticidentifies implementations that can be used without an object reference. The keyword is used when declaring fields, methods and inner classes. Fields, methods and classes that are staticmarked with can be used in the context of the class and are not linked to any object .

abstractcan appear in front of classes and methods . Abstract methods have no implementation and must be overridden in derived classes. Classes that contain abstract methods must themselves be declared abstract. Abstract classes cannot be instantiated even if they are fully implemented, such as B. in the case of the EventListener adapter classes of the Swing framework.

finalcan stand before variables , fields, methods and classes and enforces immutability. In the case of variables and member variables, their constancy, in the case of methods the impossibility of overwriting them in derived classes, and finally in the case of classes, that no further derivations can be made from them. A final variable is assigned a one-time value that cannot be changed afterwards. A final variable does not have to be initialized in the declaration, but can only be assigned once in the following alternative instructions:

public int calcFinal(int a) {
  final int b; // hier findet noch keine Zuweisung statt
  switch (a) {
    case 1:
       b = 7;
       break;
    case 2:
       b = 3;
       break;
    default:
       b = 1;
       break;
  }
  return b;
}

Access to final variables whose value is known to the compiler may be replaced by the compiler with the value of the variable. The compiler may replace calls to final methods with embedded code (inlining). Private methods are automatically final.

nativecan only appear in front of methods and means that the implementation of the method in question was not written in Java, but in another programming language, and must be integrated by the virtual machine via a runtime library.

strictfpIdentifies classes and methods, the floating point operations of which must strictly follow IEEE 754 .

packagedeclares the package belonging to a complex data type. The naming of a package should be clear and is mostly based on the internet domain of the owner or creator.

importimports symbols (previously only types, from Java 5 also static members of classes) so that they can be used without fully qualified names. The import can be *extended to complete packages using the wildcard .

boolean, char, byte, short, int, long, floatAnd doubleare types. voidthe non-type is necessary to identify methods without return values. For the primitive types: see above.

class, interface, enumAnd @interfaceserve to declare its own types: classes, interfaces (interfaces for classes), enums ( enumeration type for type-safe enumeration, english type safe enumeration ) and annotation metadata. enumand @interfacehave been incorporated into the language with Java 5.

try, catch, finally, throw, throwsRefer to the exception handling (English exception handling ). With throwan exception is thrown. Any exceptions raised by a method that are not derived from RuntimeExceptionor Errormust be throwsspecified in the declaration of the method. These are so-called checked exceptions . tryencloses a block in which an exception could possibly occur. catchcatches trythe exception that has occurred after a block, finallyis appended to an tryor catchblock for cleanup work such as closing files.

extendsand implementsserve for inheritance: extendsthe genetic extension inheritance from class to class or interface to interface and implementsimplementation inheritance from interface to class. In addition, extendsgenerics are used for type extension.

superand thisrelate in the object context to the current object in its actual morph ( this) or in the morph of the superclass ( super). thisis used to call constructors overloaded in constructors and to refer to hidden members of outer structures in members. superis used in constructors to call the superclass constructor and in overriding methods to call the overridden method. In addition, supergenerics are used for type delimitation.

newreserves memory for new objects (including arrays) on the heap .

if, else, switch, case, default, while, do, for, break, continueServe operation Test and loop control and make use of an imperative syntax.

return returns values ​​from a method to the calling method.

volatileis a modifier for non-local variables and prohibits the JIT compiler from registering optimizations on this variable because several threads could use them simultaneously (especially in the context of native methods).

synchronizedIdentifies a critical section in the source code that can only be executed by one thread at a time. A monitor locks the section as soon as a thread enters it. If another thread tries to enter the blocked section, this thread blocks until the monitor releases the section. Any Java object can be used as a monitor. If a method is synchronizedmarked with , the object or, in the case of static methods, the class object is used as a monitor.

transient identifies non-persistent variables that must not be serialized.

instanceof is a Java operator that checks whether an object is an instance of a specified type or subtype.

Packages, names, classes, interfaces

A Java package contains several classes, interfaces and exceptions and forms its own namespace .

Java source text is divided into several compilation units , each of which is stored in its own file. Each individual translation unit first defines the package to which it belongs, then imports several classes or interfaces from other packages, and finally defines one or more classes and interfaces.

Java distinguishes between simple names, which consist of only one identifier, and fully qualified names, which consist of a series of identifiers separated by periods. The simple names are just an aid to save the programmer typing and to increase the readability of the program. The compiler always translates them into fully qualified names.

The following example shows a Hello World program in Java.

package org.wikipedia;

import static java.lang.System.out;

public class HalloWelt {

    public static void main(String[] arguments) {
        out.println("Hallo Welt.");
    }

}

In this example, a class " HalloWelt" is defined that org.wikipediabelongs to the package " ". By convention, the package names in Java are based on the Internet domains of their developers, in this case " org.wikipedia" for the domain " wikipedia.org". The direction of the name is reversed because in Internet domains the name of the outermost unit is in the back, while in Java it is in front. The package “ org.wikipedia” is therefore “within” the package “ org”.

An import statement defines a simple name for a fully qualified name. So defined e.g. For example, the instruction " import java.io.File" gives the simple name " File" for the class whose full name is " java.io.File". In addition to importing classes and interfaces, static fields or methods of classes can also be imported since Java version 5. Such a "static import" is defined by the additional keyword " static". In the example above, the static field " out" of the class " java.lang.System" is imported and then used under the short name " out".

The most important construct of the Java programming language, as it is an object-oriented language, is the class . The declaration of a class is introduced with the keyword " class". This is followed by the name of the class and then - in curly brackets - the fields and methods of the class are defined.

The interface is a specialty of Java. Such an interface consists only of method declarations, the implementation of which is only determined by the classes that “implement” them. The declaration of an interface looks similar to the declaration of a class, but it is introduced with the keyword " interface".

package org.wikipedia;

public interface Article {

    String getName();

    void setContent(String aContent);

}

Since all methods of an interface are abstract, the keyword “ abstract” can be omitted for the individual methods. The keyword " public" in front of the individual methods can also be omitted because methods of an interface are always public.

As of Java 8, there is also the option of defaultdefining static methods and " " methods in interfaces . In addition, interfaces can be annotated with “ @FunctionalInterface” to indicate that they are functional interfaces. Such is defined by declaring exactly one abstract method; the annotation is not required for this. Functional interfaces can be implemented in a nutshell using lambda expressions or method references.

Methods

The actual behavior of an object is defined in methods. The signature of a method consists of its name and the types of its parameters. Also, each method has a specific return type, or " void" if it doesn't return anything, and can throwsdefine a number of exceptions in what is called a " " clause.

Example of a concrete method:

public double summe(double a, double b) throws NotANumberException {
    if (Double.isNaN(a) || Double.isNaN(b)) {
        throw new NotANumberException();
    }
    return a + b;
}

This method expects two double-precision floating point numbers as parameters and also returns the sum of the two as floating point numbers. If either number is not a valid floating point number, the method throws an exception named " NotANumberException".

Example of an abstract method:

public abstract double summe(double a, double b) throws NotANumberException;

Attributes

Attributes are variables that belong to an object. They are defined by a type and a name and can optionally be initialized when the object is created.

Example of a variable declaration without initialization:

private int x;

Class variables are declared as static attributes. These attributes do not exist once per object, but only once per class. The keyword " final" prevents a variable from changing its value after it has been initialized. It is used, for example, to define constants.

Example of a static and final class variable declaration with initialization:

private static final int X = 2;

Fields

In the Java programming language , a field (English array ) is an independent object. This can accept data of a type specified in the declaration. The memory is only occupied when the field is initialized. To do this, a length ( size ) must be specified, which describes how many elements of a type the field should have. The size of an array is fixed and cannot be changed after it has been instantiated. In Java, a field is always indexed with a positive integer. This limits the possible length of an array to 0 to 2 31 - 1.

The individual elements of a field - analogous to the attributes of other objects - are initialized with the zero value of the respective field basic type when the field is instantiated. For fields of numerical primitive types this is 0 or 0.0, for a field with the basic type boolean it is the value false, for fields of object references it is the empty reference null. When creating a field of object references, no objects are created apart from the field itself.

There are no real multi-dimensional fields in Java. However, it is possible to create multi-dimensional fields by nesting fields within fields. In the case of a two-dimensional field, a field is first created which can contain references to fields of the desired type. A reference to a one-dimensional field of the desired basic type is then assigned to each place in this field.

One-dimensional field

declaration

<Datentyp>[] <Variablenbezeichner>; // Deklaration
<Datentyp> <Variablenbezeichner>[]; // Alternative Deklaration (seltener verwendet)

The data type of the field is specified in the declaration. However, no field is allocated, but, as with all other objects, only a reference of a type is defined to which a field can be assigned.

Instantiation

<Variablenbezeichner> = new <Datentyp>[<Anzahl>]; // Instanziierung eines eindimensionalen Feldes

When instantiating a one-dimensional field, both its data type and the number of elements must be known. As noted at the beginning, the length of a field is limited to non-negative integer values. The keyword newhas the same meaning here as with all other objects and creates an instance of the type. The required memory is reserved for the object as well as for its elements. In contrast to other objects, however, fields do not have any constructors and it is not possible to form subtypes of a field type through explicit derivation.

Example of a one-dimensional field of type int with length 3

int[] feld = new int[3];  // auf der linken Seite wird die Objektreferenz deklariert
                          // auf der rechten Seite wird das Feld initialisiert

The declaration and instantiation do not have to be done separately, but can, as usual, also be written as one instruction. When accessing the elements, please note that Java starts counting with index 0. In this example, the first element is accessed with index 0 and the last element with index 2.

int[] feld = {1,2,3}

is a shortening of

int[] feld = new int[3];
feld[0]=1;
feld[1]=2;
feld[2]=3;

Reading out values

int a = feld[0];         // das Auslesen erfolgt durch Angabe des Index
objekt.methode(feld[1]); // Einzelwerte eines Feldes können wie Variablen des gleichen Typs verwendet werden
int b = feld[3];         // würde in diesem Beispiel eine IndexOutOfBoundsException auslösen, da es kein 4. Element gibt

Assignment of values

feld[0] = 5;             // Java ist "nullbasiert"
feld[1] = (int) 2.7;     // bei Zuweisungen muss wie bei normalen Variablen der Typ angepasst werden
feld[2] = 0;             // die Indexierung läuft immer bis n-1

Length of a field Many algorithms require the length of a field, for example to process all entries. The length of a field is known at runtime and can be lengthqueried via the object variable , which is itself of the type int. This variable is always constant and cannot be changed. It is therefore not possible to assign a different value.

int len = feld.length;   // Liest die Länge des Feldes aus und speichert sie in der Variablen len
feld.length = 5;         // diese Zuweisung würde einen Fehler beim Kompilieren ergeben, da sie nicht zulässig ist

Multi-dimensional fields

Example of the construction of a two-dimensional double array.

As already noted, Java does not recognize multi-dimensional fields. However, fields can be nested within one another in order to obtain an analogous structure. A two-dimensional field is comparable to a table, whereby the first (outer) indexing field would refer to the row. The row itself is in turn a field whose indices refer to the column of the row, i.e. to the corresponding entry, as can also be seen in the figure.

In Java, multi-dimensional fields can be implemented by specifying several pairs of square brackets [], each pair standing for a further dimension of the field. The outer field, which indicates the next inner one, is on the left-hand side or is the pair of brackets that was defined first. This can be seen in the example of an image that would normally be [y][x]indexed, whereby the row (y) is determined first and then the column (x) from the row.

Example of creating a two-dimensional field

double[][] feld = new double[zeilen][spalten];

In this example it should be noted that not only the outer field (here called field ) is allocated, but also the fields for the "lines". So they are not zero and were also created. As expected from a one-dimensional field, your entries are initialized with 0 .

In a matrix , the horizontal fields are called rows, the vertical fields are called columns. An individual element is uniquely determined by the respective row and column index. The syntax for a matrix or in general for multidimensional fields is almost identical. The difference lies in the number of closed square brackets that tell you how many dimensions the field will have.

Example of the creation of a two-dimensional field with different sizes in the "sub-fields"

double[][] feld = new double[3][];
feld[0] = new double[3];
feld[1] = new double[2];
feld[2] = new double[1];

In this example it should be noted that in the first command only the outer field (here called field ) is allocated and the individual elements are initialized with zero . In the following commands, these elements are then assigned to the "subfields", resulting in a "triangular" field.

As with one-dimensional arrays, there is also a shortened version of multi-dimensional arrays:

int[][] array2D={{1,2,3},{4,5,6}};
//Entspricht "=new int[2][3];" mit den darauf folgenden Zuweisungen
//"array2D[0][0]=1;"
//"array2D[0][1]=2;"
//(...)
//"array2D[1][2]=6;"

Where the square brackets ([]) are placed is up to the programmer:

int[][] A

is the same as

int A[][]

or

int[] A[]

General syntax

<Datentyp> [] <Feldvariable> = new <Datentyp> [<Anzahl>] ;

The ellipses '...' represent further pairs of brackets, each of which creates a further dimension. Access to the elements is analogous to that of a one-dimensional field. It should be noted, however, that the respective outer field can also be accessed to e.g. B. to determine the number of lines. Based on the example of a two-dimensional field, the number can be determined as follows.

Reading out and assigning values

double wert = feld[y][x];                // liefert den Wert des Feldes x,y
feld[y][x] = wert;                       // weist dem Feld x,y einen Wert zu

Determination of the length of the field and the subfields

int zeilenanzahl = feld.length;          // weist der Variable "zeilenanzahl" den Wert von "feld.length" zu

The length of the subfields can be determined using the field's index.

int spaltenanzahl = feld[index].length;  // weist der Variable "spaltenanzahl" den Wert von "feld[index].length" zu

In long form or broken down into individual steps, this would look like this. This also shows that the lines are objects - one-dimensional fields.

double[] zeilenfeld = feld[index];       // ermittelt das erste "Unterfeld" mit gegebenen Index
int spaltenanzahl = zeilenfeld.length;   // weist der Variable "spaltenanzahl" den Wert von "zeilenfeld.length" zu


Instructions and control structures

Structogram of a linear program

Java supports the usual instructions that are also known from other imperative programming languages. Simple instructions are terminated with a semicolon . Several instructions can be combined to form a block of instructions using curly brackets. Control structures are also treated like blocks and therefore do not (with one exception) need to be terminated with a semicolon.

As control structures are the Conditional statement and branching and case statement , and While - Do-while - and For loop and its various forms are available.

Conditional statement and branch

Structogram of an if statement
Structogram of an if-else statement

The conditional statement and branch , referred to in the following as the If statement , enables statements to be executed subject to a certain condition. The keyword "if" is used for this. This is followed by a pair of round brackets in which the condition can be defined. The condition is an expression that must return a Boolean value ( true or false ) as the result . This distinguishes Java from other languages ​​such as C, where other values ​​are also allowed as conditions. It should also be noted that the frequently encountered keyword "then" does not exist.

The keyword "else" can be used to execute a statement in the event that the condition is not met. It is optional and in this case it is called a branch because either the first or the second statement is executed. Alternatively, instead of “else”, an “else if” can be used which, like the first “if”, expects a further condition. This makes it possible to build cascades of branches. Without structuring using blocks (curly brackets), however, there is a risk of dangling else , in which it is not clear which If statement the Else branch is to be assigned to.

General syntax

if (<Bedingung>)
    <Anweisung>;
else
    <Anweisung>;

Example of a simple If statement with a block of two outputs

if (i < 0) {
    System.out.print("Die Zahl ist negativ"); // Bedingte Ausgabe
    System.out.println();                     // Zeilenumbruch auf der Konsole
}

More complex example

if (i < 0) {
    System.out.println("Die Zahl ist negativ");
}
else if (i == 0) {
    System.out.println("Die Zahl ist Null");
}
else if (i < 5) {
    System.out.println("Die Zahl ist kleiner als 5");
}
else {
    System.out.print("Die Zahl ist größer oder gleich 5");
}

The ternary operator

There is an additional abbreviation for a simple If statement. This can be used within an expression, but is limited to an “either-or”. I.e. in any case it must return a specific value. The operator itself is the question mark '?' which must be preceded by a Boolean expression. The return value for the case that the Boolean expression is true follows the question mark. This is followed by a colon ':' after which the return value must follow if the Boolean expression is not true (false).

syntax

<Bedingung> ? <Ausdruck> : <Ausdruck>

example

int a = (i<0) ? -i : i; // kehrt vor der Zuweisung an a das Vorzeichen von i um, wenn i negativ ist (Betrag von i)

Switch statement

Structogram of a switch instruction
  • A distinction between cases, where the expression can be a character, an integer, a character string or an enumeration type.
switch (''Ausdruck'') {
   case ''Konstante1'': ''Anweisung1''; break;
   case ''Konstante2'': ''Anweisung2''; break;
   default: ''Anweisung3'';
}

grind

Java distinguishes four different types of loops .

  • Repeat a statement as long as the condition is true, whereby the condition is checked before the statement ( while loop ).
while (''Bedingung'') ''Anweisung'';
  • Repetition of an instruction as long as the condition is true, whereby the condition is only checked after execution ( do-while loop ).
do ''Anweisung''; while (''Bedingung'');
  • Initializes a value, repeats the statement as long as the condition is true and executes a second statement after each loop pass ( for loop ).
for (''Initialisierung''; ''Bedingung''; ''Anweisung2'') ''Anweisung1'';
  • In addition, there is an extended for loop, also known as a foreach loop, which allows statements to be executed for each element of an iterable object ( sequences , lists, etc.).
for (''Element'' : ''Kollektion'') ''Anweisung'';

The following examples show the use of such an extended for loop, applied once to the basic data type charand once to a list.

char[] chars = new char[] { 'a', 'b', 'c' }; // neues Zeichen-Array anlegen
for (char c : chars) {
    System.out.println("Zeichen: " + c); // Jedes Zeichen auf die Konsole schreiben.
}

List<Character> charlist = new ArrayList<Character>(); // neue Zeichen-Liste anlegen
charlist.add('a'); // Werte hinzufügen (mit Autoboxing)
charlist.add('b');
charlist.add('c');
for (Character c : charlist) {
    System.out.println("Zeichen: " + c); // Jedes Zeichen auf die Konsole schreiben.
}

Expressions

In contrast to other programming languages, such as C , the order in which expressions are evaluated in Java is already set in the language definition: binary infix operators of the same rank that are not assignment operators are always evaluated from left to right. In addition, as in C, the evaluation of logical expressions can be shortened if the result has already been determined. In the following example, it is guaranteed to first check whether " objekt" is not " null". If this subexpression is false ( objekti.e. it is a null reference), the right operand of &&is not evaluated at all, i.e. H. the method inOrdnung()is not searched for or even called. Thus the overall expression is safe and can never cause a " NullPointerException". (A " NullPointerException" is always thrown in Java when an attempt is made to nullresolve the object reference " ".)

if (objekt != null && objekt.inOrdnung()) {
    System.out.println("in Ordnung");
}
else {
    System.out.println("ungeprüft oder Prüfung misslungen");
}

If the bit operators and are used instead of the logical operators &&and , both partial results must be linked bit by bit and processing cannot abort with the expression on the left, if the is. If the variable has the value , the Java VM tries to link the value resulting from the first expression with the result of the second expression bit by bit. To compute the second expression, the VM tries to dereference and throws one . ||&|falseobjektnullfalseobjektNullPointerException

Lambda expressions are available from Java 8 and have one of the forms

(<Datentyp> <Variablenbezeichner>,...,<Datentyp> <Variablenbezeichner>) -> <Anweisungsblock>
(<Datentyp> <Variablenbezeichner>,...,<Datentyp> <Variablenbezeichner>) -> <Ausdruck>
(<Variablenbezeichner>,...,<Variablenbezeichner>) -> <Anweisungsblock>
(<Variablenbezeichner>,...,<Variablenbezeichner>) -> <Ausdruck>

The round brackets can be omitted if the number of elements contained is exactly one. They do not have a specific type themselves and can therefore only be used in a context that specifies a type, such as method calls, return statements and variable initializations. The specified type must be a functional interface. In the following example, an Comparator<String>object is defined using a lambda expression. The sortcall effects the sorting of someStringsaccording to their length, in descending order.

List<String> someStrings = ...
Collections.sort(someStrings, (x,y) -> y.length() - x.length());

Method references also represent an option available from Java 8 onwards to implement functional interfaces. You have one of the forms

<Klassenreferenz>::<Methodenbezeichner>
<Ausdruck>::<Methodenbezeichner>

In the following code, the method reference is used System.out::printlnas an java.util.function.Consumer<String>object.

static <A> Consumer<A> doTwice(Consumer<A> consumer) {
    return a -> {
        consumer.accept(a);
        consumer.accept(a);
    };
}
static void foo() {
    doTwice(System.out::println).accept("Hello");
}

Comments

Comments are parts of the source code which contain information for the human reader and are ignored by the computer during further processing.

A distinction is made between line comments and block comments. The line comment follows on a line. The syntax consists of a double slash. The block comment includes the description of several lines. The syntax for this consists of a slash followed by a mal symbol. The comment is closed with the mark and the slash. The compiler ignores the comments when compiling.

Example:

 int i = 10; // Zeilenkommentar: hier bekommt die Variable i den Wert 10 zugewiesen.
 int j = 0;

/* Blockkommentar: hier beginnt eine While-Schleife
....
j wird um Eins erhöht, solange j kleiner i ist.*/
 while (j < i) {
  j++;
 }

The Javadoc system is often used to document entire methods or classes .

Generic programming

With version 5 of Java the language element of generic programming was introduced.

Web links

Individual evidence

  1. Scott Stanchfield: Java is Pass-by-Value, Dammit! JavaDude.com, accessed November 5, 2010 .
  2. Types, Values, and Variables. (No longer available online.) In: Java Language Specification. Oracle (Sun), archived from the original on March 9, 2012 ; accessed on November 6, 2010 (English). Info: The archive link was inserted automatically and has not yet been checked. Please check the original and archive link according to the instructions and then remove this notice. @1@ 2Template: Webachiv / IABot / docs.oracle.com