JavaLanguage

From Wiki RB4

General Informations[edit]

  • Java is a imperative language. Programs consist of assignments. All assignments have to be inside a class.
  • Java is strongly typed.

History[edit]

Invented mostly by James Gosling, former known as oak. Ein Java Specification Request (JSR) ist eine Anforderung einer neuen Java-Spezifikation oder einer wichtigen Änderung einer existierenden Java-Spezifikation, die im Rahmen des Java Community Process (JCP) an das von Oracle betriebene Process Management Office (PMO) gestellt wird. Über dieses Verfahren werden neue Java-Standards definiert und Erweiterungen der Programmiersprache Java oder der Java-Laufzeitumgebung gemeinschaftlich entwickelt.

Java Platform[edit]

Mit dem Java Development Kit (JDK) lassen sich Java Standard Edition (SE) Applikationen entwickeln. Beim Java SE Runtime Environment (JRE) ist nur die JVM zusammen mit den nötigen Bibliotheken gebündelt. Auch wenn Entwicklungsumgebungen wie Eclipse einen eigenen Java-Compiler mitbringen, ist das JRE doch das Mindeste dessen, was zur Ausführung nötig ist. Die Java Platform, Enterprise Edition (Java EE) ist ein Aufsatz für die Java SE und integriert Pakete, die zur Entwicklung von Enterprise-Applikationen nötig sind. Dazu zählen Technologien wie die Enterprise JavaBeans (EJBs), Servlets, JSP, Java-Mail-API, JTS und weitere.

JRE[edit]

Aufruf von Programmen:

java [-jar <jarfile>|<Classname>]

By default, the first non-option argument is the name of the class to be invoked. A fully-qualified class name should be used. If the -jar option is specified, the first non-option argument is the name of a JAR archive containing class and resource files for the application, with the startup class indicated by the Main-Class manifest header.

Command Line Parameters[edit]

-D<SystemProperty> set a system property e.g. -Djava.util.logging.config.file=/Uwes/eclipse/workspace/Ballaballa/bin/ballaballa_logging.properties
-Xdebug enables debugging
-Xrunjdwp:<sub-options> loads the implementation of JDWP in the target VM.
-cp <CLASSPATH> overrides all classpath entries, except the extension classes, that is obviously the jre libs. If the -jar option is used, -cp is ignored. Since java 6 it's possible tho specify multiple jar files with the wildcard *, but it must be just just with the * not with *.jar.

JDK[edit]

JDK includes JRE and development tools.

Versions[edit]

Ab 1.5 fällt 1. weg, allerdings selbst bei Sun manchmal dann doch nicht.

Version Datum Einige Neuerungen/Besonderheiten
1.0 Urversion 1995 Die 1.0.x-Versionen lösen diverse Sicherheitsprobleme.
1.1 Februar 1997 Neuerungen bei der Ereignisbehandlung, Umgang mit Unicode-Dateien (Reader/Writer statt nur Streams), Datenbankunterstützung via JDBC sowie innere Klassen und eine standardisierte Unterstützung für Nicht-Java-Code (nativen Code)
1.2 November 1998 Heißt nun nicht mehr JDK, sondern Java 2 Software Development Kit (SDK). Swing ist die neue Bibliothek für grafische Oberflächen und eine Collection-API für Datenstrukturen und Algorithmen.
1.3 Mai 2000 Namensdienste mit JNDI, verteilte Programmierung mit RMI/IIOP, Sound-Unterstützung
1.4 Februar 2002 Schnittstelle für XML-Parser, Logging, neues IO-System (NIO), reguläre Ausdrücke, Assertions
5 September 2004 Generische Typen, typsichere Enums, Variable Number of Arguments, Extended for, Autoboxing, Annotations
6 Ende 2006 Web-Services, Skript-Unterstützung, Compiler-API, Java-Objekte an XML-Dokumenten binden, System Tray
7 possibly begin 2008  

Kompatibilitätsprobleme hat es fast nie gegeben.

Executables[edit]

java.exe is the JVM runtime or JIT that lets you execute your class files. Usually it comes with the JRE or JDK.

Windows[edit]

The java.exe first on the path is used, which is normally the one in \Windows\System32 and which is a dummy that looks up entries in the registry ([HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\). There are also java.exe's in the JRE and JDK directory.

Difference between Java and C++[edit]

  • no pointer and pointer arithmetic
  • no unsigned type specifier
  • no confusion between assignment and equality test
  • no manual memory allocation
  • no difference between definition and declaration (only declaration)
  • no goto
  • in Java you can call another ctor in a ctor
  • no initialisation in ctor initialization list
  • erweiterte Array Declaration und Laufzeitabfrage der Länge
  • no multiple inheritance but interfaces
  • Aufruf des Basisctors durch super() und Basismethoden durch super.<MethodenName>()
  • no templates
  • alle Referenzvariablen müssen mit new angelegt werden
  • 'new Rectangle(100, 50).area()' is possible
  • alle Klassen haben als Basisklasse 'object'
  • garbage collection
  • methods can only be defined in the class body (no global functions); they are called methods rather than member functions.
  • es gibt nichts außerhalb des Kontextes einer Klasse
  • alle Elemente einer Klasse müssen in einer Quelldatei definiert werden
  • kein Präprozessor => kein include, keine Header
  • kein Überladen von Operatoren (Ausnahme ist + für Strings)
  • class declarations can be used in finy places e.g. as anonymous classes
  • alle Methoden von java Klassen sind virtual (ausser final,private,static)
  • different meaning of protected
  • multithreading is part of the Java language (synchronized)
  • different exception handling
  • variables declared in a for header go out of scope outside the for block
  • no line continuation with \
  • no use of booleans as ints
  • no comma operator except in the initialization and increment section of a for loop
  • + operator for strings
  • instanceof operator
  • >>> operator
  • & and | operators act a little bit different
  • labeled breaks (multi-level break)
  • There are no structs, pointer or unions
  • no enumerations
  • no bit fields
  • no variable length parameter list
  • weitaus eingeschränktere automatische casts
  • kein Zuweisung in expressions wie z.B. Method(x=getX(),a,b,c)

Structure[edit]

Identifier[edit]

Java is case sensitive. Any identifier must start with a java-letter, that is any unicode letter and continues with java-letters or java-numbers (not special chars like !, $, ...). Identifier z.B. auch Variablen können mit der Unicode-Notation \uxxxx angegeben werden.

Nameing Conventions[edit]

  • classnames start with a capital letter.
  • variables start with a lowercase letter, no _ and $
  • constants are completely in capital letters with _
  • packages completely in small letters and no underlines, and reverse order of domain name e.g. de.uweheuer. ...
  • methods start with a lowercase letter and a verb. A following substantive starts with a capital e.g. getOrders()

Keywords[edit]

const is a reserved word, but is not part of the language
goto is a reserved word, but is not part of the language


Comments[edit]

  • // <CommentText>
  • /* <CommentText> */
  • /** <Documentation text used by javadoc> */

Operators[edit]

+ i * / += -= *= /= %= &= |= ^= <<= >>= >>>= ++ -- == 
=== < <= > >= && || & | ^ ~ >> >>> << ? : ,===

Die Abarbeitung von conditions erfolgt von links nach rechts und stoppt sofort. Vorsicht ist jedoch bei den binären Vergleichsoperatoren geboten, denn dort wird nicht abgebrochen (no short circuit):

if (v == null | v.size() > 1)  // crash if v == null, use || instead.

Es sind mehrfach Zuweisungen der Form a = b = c; erlaubt.

remainder operator[edit]

Der % operator schmeißt eine ArithmeticException, wenn der zweite Operand 0 ist.

Control Flow[edit]

break|continue[edit]

continue|break [<label>];

Jumps out of the current loop. The label has to be defined right before the n loops which should be breaked; if the break keyword is followed by an identifier that is the label of an arbitrary enclosing statement execution transfers out of the enclosing statement. Required finally clauses are executed and control resumes at the statement following the terminated statement.

do while[edit]

for[edit]

Standard for loop:

for (<initialization>;  <test>;  <incrementation>)
{
  <statements>
  break; // ends the for loop
  continue; // jump to next loop
}

Using the extended for you cannot write into the array and you don't know the index:

for (<Type> <Varname> : <ArrayOfType>|<Collection> )
{
  x = <Varname>;
}
File[] files = sourceDir.listFiles();
for (File f : files)
{
  ...
}

A declared variable inside the for-statement goes out of scope at the end of the for block. this is different from c++; there is a comma operator in the initialization and increment section; although variables declared in the initialization section have their scope in the for block the names must not collide with other variables.

if[edit]

switch[edit]

als case values sind nur basic datatypes ohne float und double erlaubt.

Variables and Data Types[edit]

Java distinguishes two datatypes, primitive types and the reference type. The primitive data types are:

boolean 1 byte true, false  
byte 1 byte    
char 2 bytes   0xxxx - 0xffff
double 8 bytes    
float 4 bytes 1.14, 4.23E23, 1.4f  
int 4 bytes 0x1c, 0x1C, 0X1c, 034, 28 2^31 bis (2^31)-1, -2147483648 - 2147483647
long 8 bytes 400000000L,1l, 0xCAFE  
short 2 bytes   2^15 bis (2^15)-1, -32768 - 32767
void   only for return of a method, even not for an parameter  

The size and format and therefore the range of the primitive data types are defined by the language specification and so the language is platform independent. Char is a 16-bit Unicode character. Bei mathematischen Operationen wird automatisch (promotion) in den größten erforderlichen Datentyp gewandelt (widening), aber trotzdem ist gibt bei folgendem Beispiel Datenverlust:

class X 
{
  void printFloat(float f) 
  {
    System.out.println(f);
  }
}

X x = new X();
x.printFloat(12/5);  // da beide Werte integers sind, wird nicht gecastet

Das Gegenstück narrowing ist bis auf die Ausnahme der Zuweisung (nicht Methodenaufrufe) eines konstanten int in byte, short or char nur explizit erlaubt. Ein cast eines floats oder doubles auf ein numerischen Typ enthält ergibt den fractional part des floats bzw. doubles. Man kann nicht von boolean auf einen numerischen Typ casten. Implizite casts sind byte -> short -> int -> long -> float -> double. Ein literal value like "23.4" is considered as double. Example(u) zeigt, wie es zu einem impliziten Datenverlust kommen kann.


Konvertierung zwischen Datentypen[edit]

Für die Basisdatentypen gibt es sogenannte wrapper classes:

  • Spezialisierungen von java.lang.number: Integer, Float, Long, ...
  • Boolean
  • Character

so daß Variablen mit den Objekt-Methoden behandelt werden können wie z.B. in einem Object-Array abgespeichert zu werden. Objekte der wrapper classes sind leider immutable, und eignen sich daher nicht als in-out parameter. In diesem Fall kann man einen Array der Länge 1 verwenden.

Konvertierungen nach char bzw. Character[edit]

von int to char: c = (char)i von char to Character: new Character(c)

Konvertierung nach int[edit]

von char to int: i = (int)c;


Referenz Datentyp[edit]

All other types as arrays, objects or interfaces are references, that is even return values, so be carefully returning objects and check whether you shouldn’t better clone it . There are no structs, pointer or unions. Alle Referenzvariablen also nahezu alle Variablen müssen mit new instanziert werden.

C ObjectOfC;
ObjectOfC.DoSomething();  // does not compile because no new
ObjectOfC = new C();	  // this is correct (don’t forget the parantheses)	

Man kann alle Referenzvariablen explizit auf null setzen

ObjectOfC = null;

bzw. auf null abfragen. Local Variables are not automatically initialized with null. Am besten ist der Vergleich von Java Referenzvariablen zu Objekt-Pointern von C++. Dies ist ein enorm wichtiger Punkt. Wenn z.B. ein Objekt eine Referenz auf ein anderes Objekt als Methodenparamter erhält und sich dieses Objekt intern als Referenz merkt betreffen alle Änderungen an dem Objekt zu einem späteren Zeitpunkt natürlich auch Verwendungen innerhalb weiterer Methoden .

Speichert man beispielsweise in einem Array of Superclasses Subclasses und ruft Methoden auf, so geht werden bei derefernzierten Aufrufen über die Array-Elemente die Subclass Methoden aufgerufen, da im allgemeinen Fall alle Member virtuell sind.

You can declare a variable in any scope to be final, including parameters to methods and constructors. The value of a final variable cannot change after it has been initialized.

final int aFinalVar = 0;

Man kann auch quasi anonyme Variablen anlegen, z.B. beim Aufruf einer Methode, die ein Objekt als Parameter hat.

Casts[edit]

Man kann immer ein Subclass Objekt auf ein Superclass Objekt ohne expliziten cast casten, die umgekehrte Richtung geht nur mit einem expliziten cast. Geht ein cast schief z.B. weil ein downcast nicht korrekt ist wird eine Exception ausgelöst. Um zu prüfen, ob ein downcast erlaubt ist gibt es den instanceof-Operator der wie folgt eingesetzt wird:

if (<VariableName> instanceof <ClassInterfaceName>)

If <VariableName> == null dann ist es keine Instanz von <ClassInterfaceName>. Der folgende Ausdruck ist ebenfalls legal und liefert true:

if (<VariableName> instanceof Object)

Enum[edit]

The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type.

 [public] enum e
 {
   NORTH,
   SOUTH,
 }
 
 e x = e.NORTH;

Exception Handling[edit]

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The exception handler chosen is said to catch the exception.

Checked exceptions have to be catched. Checked exceptions are exceptions that must be declared in the throws clause of a method. They extend Exception and are intended to be an "in your face" type of exceptions. A checked exception indicates an expected problem that can occur during normal system operation. Some examples are problems communicating with external systems, and problems with user input.

Unchecked exceptions are exceptions that do not need to be declared in a throws clause. They extend RuntimeException. An unchecked exception indicates an unexpected problem that is probably due to a bug in the code. The most common example is a NullPointerException. Errors are serious problems that are almost certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError.

Since JDK 1.4 there is a new ctor for Throwable with a cause, another Throwable object. This feature is also known as exception chaining.

try
{
  throw ... // explicit throwing or
  x.method ... // method is throwing exception
}
catch (<ExceptionType> e)
{
  ...
}
finally
{
  ... // always executed
}

The code after the throw statement is not executed. The finally code is always executed no matter what happens inside the try block and it is a good place for general clean-up. If the clean-up itself produces exceptions they have to be handled inside finally or thrown.

Arrays[edit]

Array enthalten entweder:

  • basic types
  • object references
  • array references.

Für alle Typen wird bei der Konstruktion der Defaultwert des Datentyps (null bei objects) eingesetzt. Arrays are declared by

int[]   Array1;
int     Array[];

and constructed by

int[] Array1;
Array1 = new int[x];
int[] Array2 = new int[n];
char[] Array3 = {'\u0031','\u0033'};
int[] primes;
primes = new int[]{ 2, 5, 7, 11, 13 };

wobei n vom basic type byte, short oder int sein muß - long geht nicht. Arrays have the standard property length which can be used through

if (Array2.length > 1)
{
  ...
}
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
  System.out.println("Count is: " + item);
}

Creating an array of objects only allocates storage for object references, not the object themselves. Elements are initialized to their default value which is 0, 0.0, false or null.

If you pass an array to an method you would declare the method like this

<return type> <method name>(<type>[(<Space>)*][][(<Space>)*]<parameter name>) 

In this case you don’t have to call new. Another initialization is

<Method>( new <Type>[] { <Element1>, ..., <ElementN> } );

An java array remembers the type of elements. Java arrays are 0-based.

Arrays can be cast to Object and Clonable, but not to String. Die Klasse java.util.Arrays definiert nützliche Funktionen im Umgang mit Arrays.

If an array is created you cannot change its size. If you need to change the size at runtime and you only want to store subclasses of object you should use the class vector. Der Nachteil von vectors ist, dass es kein typisierter Speicher ist sondern alle Objekt-Subclasses speichert. Dies führt leicht zu Fehlern. Beim Auslesen aus einem vector muss man immer casten.

Packages and Imports[edit]

Java allows you to group classes in a collection called package. Just as you have nested subdirectories on your disk, you can organize packages using levels of nesting. To add a file to a package insert the line

package <PackageName>;

to your file. It must be the first line after any comment. Java code that is part of a package has access to all classes (public and non-public) in the package and to all non-private methods and fields in all those classes. Everything in the java.lang package is automatically imported into every Java program. There you do not need to specify a package prefix in front of e.g. the system object. The java.lang packages contains the following parts: Math ... You can import special classes of a package or all classes of a package (s. example (x)), e.g.:

import [static] <Part1>.<PartN>.(*|<ClassName>);
import java.applet.Applet;
import java.awt.*;            // * is only allowed for a single package

Importing all classes in a package is simpler. It has no negative effect on compile time or code size, so there is generally no reason not to do it. Wenn es zwei packages gibt, die eine Klasse mit dem gleichen Namen enthalten, können nicht beide importiert werden, sondern eine muss über den voll qualifizierten Namen verwendet werden. Wenn die Klasse die importiert wurde nicht als *.class file vorliegt, wird sie implizit durch das import statement übersetzt. Kann sie z.B. wegen Syntaxfehlern nicht übersetzt werden, wird auch die importierende Datei nicht übersetzt. All files of a package must be located in a subdirectory that matches the full package name. These subdirectories need not branch off from the root directory; they can branch from any directory in the CLASSPATH environment variable. JVM looks for <CLASSPATH>\<PACKAGENAME_PART1>\..\<PACKAGENAME_PARTN>\<CLASSNAME>.CLASS. The files can also be located in a CLASSES.ZIP file with the correct path information. If no package statement is specified the class is thrown into a default package with all other package-less classes and all the non-private members are visible there. In 1.4 you can no longer import a class from the default package. You can only import a class that is in a named package. If your classes are in the default package, you do not need to use the import statement. Otherwise, you will need to package the classes or only use the default package.

Classes[edit]

Classes are declared by

[public] [abstract] [final] class <ClassName> extends <BaseClassName> 
[implements <InterfaceName>]
{
  <Methods>
  <Attributes|Fields >
  <ctors>
  [static
  {
    <static initialization>
  }]
}

Class names can be used anywhere primitive data types can be used. Variables have to be defined before using them. Es ist keine Vorwärtsdeklaration innerhalb eines Moduls notwendig.

Final classes cannot be parent classes.

A class with one or more abstract methods must itself be declared abstract, also if the class doesn't implement all interface methodes of an extended interface. A class can also be declared as abstract if an instantiation is not useful.

Inner classes can even be declared private.

The static initialization is something like a ctor for static attributes. It is called when the class is loaded. There can be variables declared in the static initialization block, there can be even multiple static initialization blocks which are concatenated. Der Compiler überprüft, dass in diesen Blöcken nicht fälschlicherweise Variablen vor ihrer Initialisierung verwendet werden. Diese Überprüfung läßt sich leider umgehen, in dem man statische Methoden in diesen Blöcken aufruft, in denen auf nicht initialisierte member zugegriffen wird (24 page 25). Classes declared as abstract can have methods which have an implementation. They can also have static method which can be called anyway.


Attributes[edit]

[public|private|protected] 
[static|final|transient|volatile] <Type> <MemberName> [ = ...];

Private member without Getter and Setter werden field bezeichnet. Member with a Getter/Setter pair are called property. There is a difference while in JPA for annotations. For properties the getter is annotated.

A public member is accessible anywhere the class name is accessible. Private member besagen, dass die nur Methoden dieser Klasse auf sie zugreifen können. A protected member is throughout the package that contains the class in which the field is declared, and is also also accessible (unless shadowed) within the body of any subclass of that class. Variables may be marked transient to indicate to low-level parts of the Java virtual machine that they are not part of the persistent state of an object. The default package visibility (nothing specified) is more restrictive than protected but less restrictive than private. They are only visible by classes in the same package and not even by subclasses of different packages. A variable declared volatile is known to be modified asynchronously. The compiler arranges to use such variables carefully so that unsynchronized accesses to volatile variables are observed in some global total order. This means that variables which are declared volatile are reloaded from and stored to memory at each use, in a way that is coherent throughout a multiprocessor. Static variables or class variables are declared as static. They get unlike local variables a default initialization. Class variables are accessed by <Class¬name>.<Va¬riablename>.

Hidden member[edit]

Members can be hidden durch local variables or parameters of the same name or by members of a subclass with the same name. Such collisions can be resolved using ‘super.’ or ‘this.’ or ‘<Classname>.’ or ‘(<Classname>this).’. Something like ‘super.super.’ is not allowed. Im Unterschied zum Overriding von Methoden kann man von außen durch casts auf die hidden member der Basisklassen zugreifen. Ein weiterer Unterschied ist, daß ein statischer member einen nicht statischen member hiden kann.

Methods[edit]

[public|private|protected]
[static|abstract|final|native|synchronized] 
<Type>|void|<Type>[] <MethodName>(<Parameterlist> [...<ArrayName>]) [throws <Exception>{,<Exception}]  {...};

Für den Namen der Methode gibt es keine Beschränkung. Er kann auch wie die Klasse heissen und wird vom ctor nur durch den return type unterschieden. There can be only one method with the same signature. It is also possible to overload a method by using the same name and different parameters.

Calling a method is called invoking a method of an object or sending a message to an object.

All parameters are passed by value. The value of object parameters and arrays is a reference. To manipulate parameters you have to use objects or arrays. A method can never change the values of their parameters z.B. die Referenz umhängen, so daß diese Änderung den Methodenaufruf überdauert. Methods that change instance fields are called mutator methods and those that only access instance fields are called accessor methods.

<Parameterlist> := <Standardlist>|<Type>... <Varname>

Since Java 5 the second is a variable argument list. <Varname> is always an array and can be used e.g. with the extended for.

Beim Aufruf einer Methode kann der return value ignoriert werden d.h. man muss den return value im Code keiner Variablen zuweisen:

A.DoSomething(); // der return value von DoSomething() wird ignoriert

There is a this member available in every method. The this member can be used to discriminated between a parameter and an attribute e.g.

void <Operation>(int x)
{
  this.x = x;
}

or for ctor calling.

There is also a super member to access members or methods of the super class with

super.<MethodName>(<Parameter>);

but it is not possible to call the method an indirect base class.

Static methods[edit]

Static methods or class methods do not operate on objects. You can use them without creating an instance of the object like

<ClassName>.<StaticMethodName>(<Parameter>);

Final methods[edit]

Final methods can not be overwritten, d.h. Methoden in direkten oder indirekten subclasses mit der gleichen Signatur werden vom Compiler abgelehnt. Reasons can be efficiency (inline) and security (you know what you call).

Abstract methods[edit]

Abstract methods don’t have a body. If there is at least one abstract method the class must also be declared abstract.

Native methods[edit]

A method can be declared native, in which case the method is implemented in a platform-dependent way, for example, in C or assembly language. Because the implimentation is not provided by Java Language code, the method declaration contains no body (a semicolon appears instead of a block). Native methods are otherwise like normal Java methods; they are inherited, may be static or not, may be final or not, may override or be overridden by non-native methods, and so on.

ctors[edit]

[public|private|protected| <ClassName>(<ParameterList>)
{
  [this(<ParameterList>);|super(ParameterList);]
  <statements>}
}

A ctor has no return value and it is not allowed to use the return statement with an argument. The compiler decides depending on the parameters which base class ctor is used. If a default ctor (without parameters) is missing, the compiler adds on. If an explicit ctor call for the superclass or for another ctor is missing ‘super();’ is inserted implicitly at the first line, so all ctors are chained. If the base class does not have a ctor without an argument this will lead to a compile error. A call super ( ... ); to a superclass constructor, whether it actually appears as an explicit constructor call statement or is implicitly assumed, performs an additional implicit action after a normal return of control from the superclass constructor: all the instance variables that have initializers are initialized at that time. More precisely: for every instance variable declared in the class containing the call, taken in the order in which the instance variables appear in the class declaration: if that variable has an initializer and either the initialization expression is not a constant expression or its value is not the standard default value for the variable, then the initialization expression is executed and its value is assigned to the instance variable. It is a compile-time error for instance variable initializations to have a forward dependency. Wenn man fälschlicherweise eine Methode mit gleichem Namen wie die Klasse und einem return type definiert, so handelt es sich um eine normale Methode und nicht um einen ctor.

Private ctors verhindern, dass eine Klasse angelegt wird (s. Example (w)).

A special ctor feature is the possibility to call a different ctor by

ctor1(a,b,c)
{
  this(new X(), a, b, c);  // it must be the first line of a ctor 
}

which also must be the first statement in the ctor. A call this(... ); to another constructor in the same class does not perform the mentioned additional implicit action.

Bei ctor design ist generell zu beachten, daß subclasses damit zurechtkommen. Man ruft am besten keine privaten Methoden auf, und schreibt am besten immer auch einen parameterlosen ctor und eine Menge von u.U. private Methoden, die die Einzelschritte implementieren (s. 24 page 26).

Finalize[edit]

Before an object gets garbage-collected, the garbage collector gives the object an opportunity to clean up after itself through a call to the object's finalize method. This process is known as finalization. The finalize method must be declared as follows and it is good practice to apply the following pattern:

protected void finalize() throws Throwable
{
  try
  {
    <statements>
  }
  finally
  {
    super.finalize();
  }
}

There is a great difference between the C++ dtor and the finalize() method in java. The dtor is called when an object is deleted. The finalize() method is called by the garbage collector, so it might be called never. Finalize() methods are not chained automatically but have to be chained explicitly. There the last statement should be super.finalize();.

In einem standard java program finalize is not called for the object with the main method (logisch but Java 1.1 had added a static method called runFinalizerOnExit() in the system class that will guarantee the the finalize method is called before java shuts down. Remember that you do not know when it is called.

object class[edit]

The Object class is the top of Java's class hierarchy and the parent of everything even if it is not specified in the extension list (but it can be specified there).

Inner bzw. Nested Classes[edit]

Inheritance[edit]

public class <ClassName> extends <ClassName> 

Attributes[edit]

Private attributes of the superclass are not visible to the subclass.

Overriding Methods[edit]

A non-static method defined in a subclass with the same name and paramter list (signature) as a method in one of its ancestors classes overrides the method of the ancestor class from the subclass. Alle Methoden sind virtual. The access modifier of the overriding method must provide at least as much access as the overridden method, which seems a little bit strange. Overriden methods cannot be accessed outside of the class that overrides them.

A method with the same signature but different return types or a static method with a the same signature as one of one of the ancestor classes or a non-static method with the same signature as a static method of one of the ancestor classes generates a compiler error.

If you have an object of class B which extends class A and which overrides f() it is impossible to call f() of A but in methods of B using super.f(). Finding the correct method is called overloading resolution. Final methods cannot be overriden. Abstract methods must be overriden.

Überschriebene synchronized Methoden erben diese Eigenschaft nicht automatisch, sondern müssen ebenfalls als synchronized deklariert werden. Allerdings bleibt die Basisklassen Methode weiterhin synchronisiert.

Static methods can not be declared in interfaces, cannot be declared abstract and cannot be overriden (but hidden).

class Super {
  static String greeting() {
    return "goodnight";
  }
  String name() {
    return "Richard";
  }
}

class Sub extends Super {
  static String greeting() { // hidden
    return "hello";
  }
  String name() {            // override
    return "Dick";
  }
}

Super s = new Sub();
System.out.println(s.greeting() + " " + s.name());  // prints out 'goodnight dick'


It’s no problem to ‘override’ private methods because in reality it is no overriding.

Interfaces[edit]

An interface defines a protocol of behavior. A Java interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all of the methods defined in the interface, thereby agreeing to certain behavior. A class that implements an interface adheres to the protocol defined by that interface. To declare a class that implements an interface, include an implements clause in the class declaration. Your class can implement more than one interface (Java supports multiple interface inheritance), so the implements keyword is followed by a comma-delimited list of the interfaces implemented by the class.

class <ClassName> implements <Interfaces>
{
  ...
}

When a class declares that it implements an interface, it's basically signing a contract to the effect that it will provide at least an empty implementations for all of the methods in the interface.

An interface is defined by

[public] interface <InterfaceName> [extends <SuperInterfaces>]
{
  [public abstract] <ReturnType>  <MethodName>(<ParameterList>);
  ...
  [public static final] <Type>  <ConstantName> = <Value>;  // constants
}

Der default modifier einer Methode ist public. Es ist ein Fehler wenn Interfaces sich selbst direkt oder indirekt extenden. A method declaration in an interface body may not include any of the modifiers final, native, static, or synchronized.

Interfaces können Attribute definieren, die aber immer implicit statisch und final sind und explizit initialisiert werden müssen.

Interfaces können auch als Parameter übergeben werden oder als Typ einer lokalen Variablen verwendet werden. Eine andere Verwendung ist folgende:

<Interface>  <Variable> = new <ClassWithInterface>();

Interface with no methods are called marker interfaces, because they mark that the class capable of doing something.

At this point, many programmers wonder how an interface differs from an abstract class. An interface is simply a list of unimplemented, and therefore abstract, methods. Wouldn't the following Sleeper class do the same thing as the Sleeper interface?

abstract class Sleeper { public abstract void wakeUp();}

No. The two are not equivalent. If Sleeper is an abstract class, then all objects that wish to use AlarmClock must be instances of a class inherited from Sleeper. However, many objects that wish to use AlarmClock already have a superclass. For example, the GUIClock is an Applet; it must be an applet to run inside a browser. But Java doesn't support multiple inheritance. So GUIClock can't be both a Sleeper and an Applet. Hence, you use an interface instead. This is the practical explanation of the problem. The conceptual explanation is this: AlarmClock should not force a class relationship on its users. It doesn't matter what their class is. It simply matters that they implement a specific method. Often interfaces are touted as an alternative to multiple class inheritance. While interfaces may solve similar problems, interface and multiple class inheritance are quite different animals, in particular: A class inherits only constants from an interface. A class cannot inherit method implementations from an interface. The interface hierarchy is independent of the class hierarchy. Classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance. Yet, Java does allow multiple interface inheritance. That is, an interface can have multiple superinterfaces. You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following: Capturing similarities between unrelated classes without artificially forcing a class relationship Declaring methods that one or more classes are expected to implement Revealing an object's programming interface without revealing its class. (Objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers.)

Properties[edit]

Java definiert eine Reihe von properties wie z.B. user.home oder java.home. Diese können in Applikationen abgefragt werden, werden andererseits aber auch in den Security Files referenziert und legen fest, welche policy files angezogen werden.

Objects[edit]

Initialization[edit]

Bevor ein ctor aufgerufen wird werden alle numerischen Member mit 0, alle boolschen Member mit false und alle Referenzen mit null initialisiert (lokale Variablen werden im Gegensatz dazu nicht initialisiert), es sei denn in der Klassendefinition sind Defaultwerte (auch für Referenzen) angegeben.


Identity and Equality[edit]

Object identity (==) is defined by the virtual machine (same memory location). Equality is define by the equals() method, sometimes called equivalence.

Generics[edit]

"Java Generics" is a technical term denoting a set of language features related to the definition and use of generic types and methods . Generic types or methods differ from regular types and methods in that they have type parameters. Ziel war es u.a. die existierenden Containerklassen wie Vector oder Map wiederverwendbar zu halten, aber um Typsicherheit zu erweitern. Diese Typprüfung erfolgt nun zur Compilezeit, womit Fehler frühzeitig festgestellt werden können.

// adding a different type will result in a compile error
List<String> words = new ArrayList<String>();

// no cast neccessary
String s = words.get(i);
// iterating
for (Iterator<String> i = words.iterator(); i.hasNext();)
{
  String s = i.next();
}

wildcard parameterized type[edit]

Zusätzlich kann man bei der Declaration eine wildcard verwenden. Es muss der konkrete Typ aber feststehen (d.h. auf der rechten Seite einer Anweisung). Der Zweck der wildcards ist mir noch nicht klar. Die Deklaration hat ähnelt einer Interface-Deklaration.

Collection<?> coll = new ArrayList<String>();
List<? extends Number> list = new ArrayList<Long>(); 
Compararator<? super String> cmp = new RuleBasedCollator("< a< b< c< d"); 
Pair<String,?> pair = new Pair<String,String>();

Sources[edit]

Annotations[edit]

Als Annotation wird im Zusammenhang mit der Programmiersprache Java ein Sprachelement bezeichnet, das die Einbindung von Metadaten in den Quelltext erlaubt. Dieses Element wurde im JSR 175 festgelegt und mit der Version Java 5.0 eingeführt.

Annotationen werden durch ein @-Zeichen gefolgt vom Namen der Annotation gekennzeichnet. Optional kann eine kommagetrennte Parameterliste folgen, die in runden Klammern eingefasst wird. Wenn der einzige spezifizierte Parameter value heisst, kann der Paramter und das =-Zeichen weggelassen werden. Wenn keine Parameter angegeben werden, können die Klammern weggelassen werden.

Es gibt eine Reihe von vordefinierten Annotations.

@Override[edit]

Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

Annotations Types[edit]

Eigene Annotations können mit

@interface <Annotation> 
{
  <JavaType> <Parameter>() [default <Value>];
  ...
}

definiert werden.

Autoboxing[edit]

All primitive datatypes are converted to wrapper objects if neccessary and vice versa.

int i     = 4711; 
Integer j = i;               // steht für  j = Integer.valueOf(i)    boxing
int k     = j;               // steht für  k = j.intValue()          unboxing

There is one problem with autoboxing, there is no unboxing if the == operator is used. Sun tried to solve this with pool objects for the int values from -128 to 127.

Serialization[edit]

Damit Objekte serialisiert werden können, müssen die Klassen die Schnittstelle Serializable implementieren. Diese Schnittstelle enthält keine Methoden und ist nur eine Markierungsschnittstelle (engl. marker interface). Implementiert eine Klasse diese Schnittstelle nicht, folgt beim Serialisierungsversuch eine NotSerializableException.

Um Elemente bei der Serialisierung auszusparen, bietet Java zwei Möglichkeiten:

  1. ein spezielles Schlüsselwort: transient
  2. das Feld private final ObjectStreamField[] serialPersistentFields = {...}, das alle serialisierbaren Eigenschaften aufzählt

Statische Eigenschaften würden auch nicht serialisiert, aber das ist hier nicht unser Ziel.

A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

JavaBeans[edit]

The JavaBeans API provides a framework for defining reusable, embeddable, modular software components. They base on:

  • Introspection
  • Properties
  • Events
  • Persistence

Eine Bean sollte keine public member haben. Die genaue Spezifikation can be found here.


Conventions[edit]

Introspection[edit]

  • Öffentlicher Standardkonstruktor (Default constructor)
  • s. Properties

Properties[edit]

A bean defines a property <P> of type T if it has accessor methods

public <P>   get<P>() // if T is boolean public boolean  is&;ltP>()
public void     set<P>()

Persistence[edit]

  • implements Serializable


Bean Validation[edit]

Validating data is a common task that occurs throughout any application, from the presentation layer to the persistence layer. The technical objective of JavaBean validation speficied in JSR 303 implemented in Java EE and Java SE is to provide a class level constraint declaration and validation facility for the Java application developer, as well as a constraint metadata repository and query API. Bean validation can be set on different levels:

  1. field level
  2. property (method) level (if the class adheres to JavaBean specification)
  3. class level