Java: Difference between revisions

From Wiki RB4
(New page: !!!Introduction Java is a high-level programming language that is all of the following : *Simple *Object-Oriented – everything in Java, except for a few basic types, is an object *Distr...)
 
 
(16 intermediate revisions by 2 users not shown)
Line 1: Line 1:
 
==Topics==
!!!Introduction
* [[JavaLanguage|The Language]]
Java is a high-level programming language that is all of the following :
* [[JavaAPI|API]]
*Simple
* [[JEE|JEE]]
*Object-Oriented – everything in Java, except for a few basic types, is an object
* [[JavaProgrammingConcepts|Programming Concepts]]
*Distributed
* [[log4j|log4j]]
*Interpreted
* [[JavaLiterature|Further Readings and Resources]]
*Robust
* [[POI|Apache POI]]
*Secure
* [[JUnit|JUnit]]
*Architecture-neutral
*Portable (write once, run (debug) anywhere)
*High-Performance
*Multithreaded
*Dynamic
*strongly typed
*Easy to learn – close to C++, but its far easier to turn out bug-free code e.g. no manual memory allo- and deallocations.
Java is also unusual in that each Java program is both compiled and interpreted. With a compiler, you translate a Java program into an intermediate language called ''Java bytecode'', the platform-independent code interpreted by the Java interpreter. With an interpreter, each Java bytecode instruction is parsed and run on the computer. Compilation happens just once; interpretation occurs each time the program is executed.
 
Die Java-Technologie besteht aus den folgenden Kernbausteinen:
*the java language
*the java core packages
*the java compiler
*the Java Virtual Machine (JVM)
Weitere Komponenten sind JavaDoc, JavaBeans, JavaOS, HotJava und Java Server .\\
J2ME bedeutet Java 2 Micro Edition, J2SE bedeutet Java 2 Standard Edition \\
Profile sind an bestimmte Aufgaben angepaßte Klassenbibliotheken wie z.B. Handhelds.\\
KVM implementiert eine schlanke virtuelle Maschine.
 
!![Java Standard Edition (J2SE)|JavaJ2SE]
 
!![Java Enterprise Edition (J2EE/JEE)|JavaJEE]
 
!!The Java Runtime Environment (JRE)
JRE is an implementation of the Java (1.2,1.3,...) platform, including a Java virtual machine, class libraries, and other supporting files. These files support the execution of programs written in the Java programming language, including programs you develop, and those JDK development tools written in the Java programming language. It consists of the Java virtual machine, the Java platform core classes, and supporting files. It contains no development tools -- no compiler, debugger, or other tools.\\
The JDK has its own internal, complete, non-redistributable Java runtime environment in the jre subdirectory.
 
!!Java Source Files
Java verlangt das Quellcode für jede public Klasse oder jedes public Interface in einer eigenen Datei abgespeichert werden muss, die den gleichen Namen trägt wie die Klasse und die Endung '.java' hat . D.h in einem source file dürfen maximal eine public class bzw. ein public interface sein, es dürfen aber mehrere nicht public classes vorkommen z.B. kann man auch mehrere classes ohne access modifier definieren. Java ist case sensitive und dies wird auch bei Dateinamen erwartet, d.h. heißt eine Klasse XyZ muss die zugehörige Datei XyZ.java heißen. Befinden sich mehrere nicht public Klassen werden entsprechend viele *.class Files generiert, jeweils mit dem Klassennamen als Base, die aber aber von der public Klasse verwenden werden können, wenn die generierten *.class Files im Pfad liegen . Inner class definitions produce additional class files. These class files have names combining the inner and outer class names, such as MyClass$MyInnerClass.class. $<n>.class files are generated for anonymous classes.
 
!!The Java Compiler
Java solves the fragile superclass problem from C++ (permanent recompilation). It solves it by compilating only symbolic references and runtime memory layout. Der java compiler uebersetzt in einem multi pass die java sources (*.java) in einen plattform-unabhängigen java byte code (JBC) (*.class).
 
!javac
__Aufruf__:
{{{
<b>javac</b> [<Command Line Options>] [<sourcefiles>] [<@files>]
}}}
Beispiele:
{{{
javac HelloWorld.java
javac MyPackage\MyClass.java
}}}
 
!!Finding the classes
When the compiler needs type information, it looks for a source file or class file which defines the type. The compiler searches first in the bootstrap and extension classes, then in the user class path.\\
The Java launcher, __java__, initiates the Java virtual machine. The virtual machine searches for and loads classes in this order:
*__Bootstrap classes__ - Classes that comprise the Java platform, including the classes in rt.jar and i18n.jar.
*__Extension classes__ - Classes that use the Java Extension mechanism. These are bundled as .jar files located in the extensions directory.
An implementation of an optional package may consist of code written in the Java programming language and, less commonly, platform-specific native code. In addition, it may include properties, localization catalogs, images, serialized data, and other resources specific to the optional package.
*__User classes__ - Classes defined by developers and third parties that do not take advantage of the extension mechanism. You identify the location of these classes using the -classpath option on the command line the preferred method) or by using the CLASSPATH environment variable.
 
!Setting the CLASSPATH
To find *.class files the classpath must contain the path, where the files are located. To find *.class files in jar files the jar-filename must be in the classpath. Each classpath should end with a filename or directory depending on what you are setting the class path to:
*For a .jar or .zip file that contains .class files, the class path ends with the name of the .zip or .jar file.
*For .class files in an unnamed package, the class path ends with the directory that contains the .class files.
*For .class files in a named package, the class path ends with the directory that contains the "root" package (the first package in the full package name).
A successful type search may produce a class file, a source file, or both. Here is how __javac__ handles each situation:
*Search produces a class file but no source file: __javac__ uses the class file.
*Search produces a source file but no class file: __javac__ compiles the source file and uses the resulting class file.
*Search produces both a source file and a class file: __javac__ determines whether the class file is out of date. If the class file is out of date, __javac__ recompiles the source file and uses the updated class file. Otherwise, __javac__ just uses the class file. By default, __javac__ considers a class file out of date only if it is older than the source file. (The __-Xdepend__ option specifies a slower but more reliable procedure.) \\
 
Note that __javac__ can silently compile source files not mentioned on the command line. Use the __-verbose__ option to trace automatic compilation. \\
*__Command Line Options\\__
 
|-classpath <;-seperated path>|
|-d|where to put the class files e.g. –d \XXX\YYY\ZZZ
|-Xbootclasspath|the ''bootstrap classpath'' contains the path to Java platform classes that are contained in rt.jar. If you need to override the location where Java platform classes are found, you must use the [''-Xbootclasspath''|java.html] option -- this is a big change from 1.1 where -classpath provided this functionality.
 
!!Java Decompiler
{{{
javap <Options> <classes>
}}}
liefert den u.a das Interface einer Klasse oder den ByteCode für die VM z.B. durch
{{{
javap aves.navtree.Tree
}}}
 
Der class-file muss in diesem Fall vom aktuellen Verzeichnis unter aves/navtree/Tree.class liegen.
Mocha erzeugt Quellcode.
 
!!JAR-Files
The JavaTM Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file will contain the class files and auxiliary resources associated with applets and applications. Die Pfadinformationen der *.class Files als Package-Information müssen nicht vorhanden sein, weil eine Klasse über ihren full-qualified name gesucht wird .\\
The JAR file format provides many benefits: \\
*''Security'': You can digitally sign the contents of a JAR file. Users who recognize your signature can then optionally grant your software security privileges it wouldn't otherwise have. \\
*''Decreased download time'': If your applet is bundled in a JAR file, the applet's class files and associated resources can be downloaded to a browser in a single HTTP transaction without the need for opening a new connection for each file. \\
*''Compression'': The JAR format allows you to compress your files for efficient storage. \\
*''Packaging for extensions'' (version 1.2): The extensions framework provides a means by which you can add functionality to the Java core platform, and the JAR file format defines the packaging for extensions. By using the JAR file format, you can turn your software into extensions as well. \\
*''Package Sealing'' (version 1.2): Packages stored in JAR files can be optionally sealed so that the package can enforce version consistency. Sealing a package within a JAR file means that all classes defined in that package must be found in the same JAR file. \\
*''Package Versioning (version 1.2)'': A JAR file can hold data about the files it contains, such as vendor and version information. \\
*''Portability'': The mechanism for handling JAR files is a standard part of the Java platform's core API. \\
To perform basic tasks with JAR files, you use the JavaTM Archive Tool provided as part of the Java Development Kit.
|__Operation__|__Command__
|To create a JAR file|jar cf ''jar-file input-file(s)''
|To view the contents of a JAR file|jar tf ''jar-file''
|To extract the contents of a JAR file|jar xf ''jar-file''
|To extract specific files from a JAR file|jar xf ''jar-file archived-file(s)''
|To run an application packaged as a JAR file
(version 1.1)|jre -cp ''app.jar MainClass''
|To run an application packaged as a JAR file
(version 1.2 -- requires Main-Class
manifest header)|java -jar ''app.jar''
|To invoke an applet packaged as a JAR file|<applet code=''AppletClassName.class''\\\\        archive="''JarFileName.jar''"\\\\        width=''width'' height=''height''>\\\\</applet>
 
!!The Java Virtual Machine
Java wird weder interpretiert noch im klassischen Sinn compiliert, sondern der java compiler übersetzt die Quellen in java byte code, der von der JVM ausgeführt wird. \\
!Running an Application
Die JVM wird durch:
{{{
java <CLASSFILENAME ohne Extension>
}}}
aufgerufen. In Kapitel 1.23.1 ist der Aufruf von Applets beschrieben.
 
A class is loaded when it is needed, either because it is implicitly needed by another class, or because its is explicitly requested to be loaded using a ClassLoader or the forName() method of the class Class. This is sometimes called dynamic loading.
 
!java, javaw
 
The __java__ tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's __main__ method. 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. \\
 
The Windows version of the JDK contains a command javaw, that starts the java interpreter as a seperate Windows process and keeps it running. It’s better to use ‘start java’ because Windows has no tool to kill the process (it doesn’t show up in the task list) and all outputs are not displayed anywhere.
 
!Microsoft JVM
Aktuelle Version der MS Java VM erhält man durch einfaches Aufrufen von 'jview'  (s. Kapitel 5.2.9) oder durch 'jview version' .
 
 
!Dokumentation
Die Dokumentation muss in der Regel mit einem eigenen Setup installiert werden . Um eine besondere Operation zu suchen geht man am besten ueber den Index.
 
!!JIT
 
The standard model of a virtual machine continually interprets a sequence of bytecodes that describe the intent of a Java applet or application. Each time the VM encounters a bytecode, whether it has interpreted it many times before or not, there is a (relatively) lengthy translation process. Even though various approaches exist for speeding up this approach somewhat, this interpretation process accounts for significantly slower execution performance compared to equivalent compiled native code.\\
To improve this performance, JIT compilers interact with the VM and compile appropriate bytecode sequences into an equivalent piece of native machine code. This process occurs at run time (that is, as the particular piece of code is going to be executed) rather than at compile time, as is traditionally the case with compiled languages such as C and C++. Rather than interpret the same bytecodes repeatedly, the hardware (the CPU) can run ("interpret") the native code. This can allow quite dramatic performance gains in the execution speed. There is, however, a tradeoff.\\
The time that the JIT compiler takes to compile the bytecodes is added to the overall execution time. For example, when a method executes only once and does not contain any loops, the overall performance might be reduced when JIT compilation occurs.\\
Note that JIT compilation has potential advantages over traditional code compilation techniques in some aspects: for example, it can target the specific machine on which the program is actually running (for example, 486 versus Pentium), rather than for a general CPU (or "the most likely" one), which is the best that traditional approaches (such as targeting a generic x86 platform) can achieve.\\
 
!Microsoft JVM
 
When the Microsoft Java Virtual Machine (VM) installs, it enters the value C:\Windows\Java\Classes\Classes.zip;.; into the registry key 'HKEY_LOCAL_MACHINE\Software\Microsoft\Java VM\Classpath'. \\
When a Java program runs, Visual J++ and the VM first look for the CLASSPATH value in the registry. If the application executes from the command line, Visual J++ and the VM also use the CLASSPATH environment variable if one has been set. When execution launches from the development environment, they also search the directories listed in the Directories tab on the Options dialog box of the Tools menu. See also [[12].\\
 
!!!The Language
 
!!Identifier
 
Java is case sensitive. Any identifier can start with a letter, even with an Ä,ö,... . Als special chars sind nur _____ und __$__ zugelassen.\\
 
!!Keywords
 
|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
 
__//__ <CommentText>\\
__/*__ <CommentText> __*/__\\
__/**__ <Documentation text used by javadoc> __*/__
 
!!Operators
 
+ 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\\__
\\
Der % operator schmeißt eine ArithmeticException, wenn der zweite Operand 0 ist.\\
!!Control Flow\\
 
|__break;__ |jumps out of the current loop
|__break__ <label>__;__  |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.
|__continue;__|
|__continue__ <label>__;__|[[20] page 38
|do while|
|__for (__<initialization>__;__  <test>__;__  <incrementation>__)__\\__{__\\  <statements>\\__}__|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 then else|
|switch|als case values sind nur basic datatypes ohne float und double erlaubt.
|while|
 
!!Variables and Data Types
Java is a strongly typed language. The primitive data types are:
|boolean|1 bit| |!! no use with arithmetic expression
|byte|1 byte| |
|char|2 bytes|‘\FA01’ or '\u1F23'|0 bis (2^32)-1\\\\"a" is not a valid literal
|double|8 bytes|1.1d|
|float|4 bytes|1.14, 4.23E23, 1.4f|
|int|4 bytes|0x1c, 0x1C, 0X1c, 034, 28|2^31 bis (2^31)-1
|long|8 bytes|400000000L,1l, 0xCAFE|
|short|2 bytes| |2^15 bis (2^15)-1
 
Ein weiterer impliziter Datentyp ist:
 
|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
Für die Basisdatentypen gibt es sogenannte __wrapper classes__:
*Spezialisierungen von java.lang.number: Integer, Float,..
*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
von int to char: c = (char)i\\
von char to Character: new Character(c)\\
!Konvertierung nach int
von char to int: i = (int)c;
 
!Referenz Datentyp
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;
}}}
 
By convention variables start with a lowercase letter and classes with an uppercase letter.
 
Man kann auch quasi anonyme Variablen anlegen, z.B. beim Aufruf einer Methode, die ein Objekt als Parameter hat.
 
!Casts
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)
}}}
 
!!Arrays
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[] Array2 = new int[n];
char[] Array3 = {'\u0031','\u0033'};
}}}
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)
{
  ...
}
}}}
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 for int for instance or null for references .\\
 
If you pass an array to an method you would declare the method like this
{{{
<return type> <method name>(<type>[[(<Space>)*][][[(<Space>)*]<parameter name>)
}}}
The initialization of an array can be
{{{
<Class> <VarName>;
<type>[] <array name> = { [<Varname> = ] <element> {,<element>} };
}}}
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.
 
Der java compiler übersetzt allerdings einen Ausdruck wie i = xxx[[-1];
 
Arrays can be cast to Object and Clonable, but not to String.
 
Under some conditions (obviously if the accessed element is actually used) the access of array elements outside the arrays bounds generates an java.lang.ArrayIndexOutOfBoundsException exception . This is the behavior if you compile with the JDK compiler, if you compile within Visual Cafe you get an exception even if you use the JDK JVM, if you compile with the command line compiler sj you won’t get the exception.\\
 
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.
 
!!Enumeration/Iteratoren
 
Für Iteratoren definiert die Java-Bibliothek zwei unterschiedliche Schnittstellen. Das hat historische Gründe. Die Schnittstelle Enumeration gibt es seit den ersten Java-Tagen; die Schnittstelle Iterator gibt es seit Java 1.2, seit der Collection-API. Der Typ Iterator ist jedoch deutlich weiter verbreitet.
 
Iterator hasNext() next()
 
Beiden Schnittstellen ist eine Funktion gemeinsam, die das nächste Element erfragt, und eine Funktion, die ermittelt, ob es überhaupt ein nächstes Element gibt. So wandert der Iterator einen Datengeber (in der Regel eine Datenstruktur) Element für Element ab. Die Namen der Operationen unterscheiden sich in den Schnittstellen ein wenig und sind beim Iterator kürzer.  Die Schnittstelle Iterator bietet eine Möglichkeit, die Enumeration nicht bietet. Das zuletzt aufgezählte Element lässt sich aus dem zugrunde liegenden Container mit remove() entfernen. Vor dem Aufruf muss jedoch next() das zu löschende Element als Ergebnis geliefert haben. Eine Enumeration kann die aufgezählte Datenstruktur grundsätzlich nicht verändern. Sie stellt quasi eine Pointer-Liste darstellen und es aus diesem Grund gefährlich ist, die Quelle zu modifizieren, während man interiert. In der Regel löst dies eine ConcurrentModificationException aus.
 
{{{
import java.util.Enumeration;
 
for ( Enumeration e = ds.elements(); e.hasMoreElements(); )
System.out.println( e.nextElement() );
}}}
 
Die Collection liefert mit iterator() einen typisierten Iterator und überträgt somit den generischen Typ der Datenstruktur auf den Iterator.
 
!Bitsets
 
!Hash Tables
 
!Property Sets
 
!Hash Sets
 
!Linked Lists
 
!Queues
 
!Stacks
 
!Multi-Dimensional Array
 
!Vector
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.\\
 
!!Access Modifiers
access modifier := __public__ {{{|}}} __protected__ {{{|}}} __package__ {{{|}}} __private__\\
 
Wenn keiner angegeben wird ist der Default package.
 
!!Packages and Imports\\
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__ <Part1>.<PartN>.(__*__{{{|}}}<ClassName>)__;__\\
 
import java.applet.Applet;\\
import java.awt.*;            // * is only allowed for a single package\\
                              // you cannot write import java.*\\
Normally 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
Classes are declared by\\
 
[[__public__] [[__abstract__] [[__final__] __class__ <ClassName> [[__extends__ <BaseClassName>] \\
    [[__implements__ <InterfaceName>]\\
__{\\__
  <Methods>\\
 
  <Attributes{{{|}}}Fields >\\
 
  <ctors>\\
 
  {\\
  __static\\__
  __{\\__
    <static initialization block>\\
  __}\\__
  }\\
__}\\__
\\
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.\\
 
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 bzw. Fields
[[__public__{{{|}}}__private__{{{|}}}__protected__] \\
[[__static__{{{|}}}__final__{{{|}}}__transient__{{{|}}}__volatile__] <Type> <MemberName> [[ = ...];\\
 
Attribute werden manchmal fields oder member genannt. 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
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
[[__public__{{{|}}}__private__{{{|}}}__protected__]\\
[[__static__{{{|}}}__abstract__{{{|}}}__final__{{{|}}}__native__{{{|}}}__synchronized__] \\
<Type>{{{|}}}__void__{{{|}}}<Type>__[[]__ <MethodName>() [[__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.\\
Calling a method is called invoking a method of an object or sending a message to an object. \\
 
All primitive type parameters are passed by value and all object parameters and arrays are passed by 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:\\
 
Method(Object o)\\
{\\
  Object p;\\
  o.DoSomething();  // ok and will survive after the method call\\
  o = p;  // ok but will not survive after the method call\\
}\\
\\
Methods that change instance fields are called mutator methods and those that only access instance fields are called accessor methods.\\
 
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 (see chapter 1.11.11.2.1).\\
 
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 or class methods do not operate on objects. You can use them without creating an instance of the object like \\
 
<ClassName>__.__<StaticMethodName>__(__<Parameter>__);__\\
 
Static methods can not be declared in interfaces, cannot be declared abstract and cannot be overriden (but hidden).\\
 
__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 don’t have a body. If there is at least one abstract method the class must also be declared abstract.\\
 
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.\\
*ctor\\
 
[[__public__{{{|}}}__private__{{{|}}}__protected__{{{|}}} <ClassName>(<ParameterList>)\\
{\\
  [[__this(__<ParameterList>__);__{{{|}}}__super(__ParameterList__);__]\\
  <statements>\\
}\\
 
If no special ctor is specified and only if no special ctor is specified java will provides one with no arguments and which does nearly nothing (alle member werden mit ihren default values initialisiert und der super.ctor() wird aufgerufen). Wenn mindestens ein ctor spezifiziert wird, generiert der Compiler keinen default ctor mehr. 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. \\
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.\\
 
The base class has to be constructed by a special call in the ctor which has to be the first statement\\
 
__super__(....);              // it must be the first line of a ctor !!!\\
 
If an explicit ctor call for the base or for another ctor is missing ‘super();’ is inserted implicitly so all ctors are chained (s. Example (w)). 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.\\
 
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 \\
 
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: \\
 
__protected void finalize()__ [[__throws__ __Throwable__]\\
{\\
  <statements>\\
}\\
 
Finalize() methods are not chained automatically but have to be chained explicitly.\\
 
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. \\
!Objects\\
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).\\
*__Initializing an Object\\__
\\
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 .\\
 
![Inner bzw. Nested Classes|JavaNestedClasses]
 
!Inheritance\\
 
__public__ __class__ <ClassName> __extends__ <ClassName> \\
 
*__Overriding Methods \\__
\\
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, static methods cannot be overriden but hidden.\\
''\\''
__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 are hidden and not overriden e.g.\\
 
class Super\\
{\\
  static String M() { return "X"; }\\
}\\
class Sub extends Super\\
{\\
  static String M() { return "Y"; }\\
}\\
 
Super s = new Sub();\\
System.out.println(s.M()); // will print 'X', because casting to Super is \\
                          // something like a qualified name\\
 
It’s no problem to ‘override’ private methods because in reality it is no overriding.\\
!Interfaces\\
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__ <InterfaceName>[[__,__<InterfaceName>]\\
{\\
  ...\\
}\\
 
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__ <SuperInterfaceName> [[,<SuperInterfaces>]]\\
{\\
<AccessModifier> <ReturnType>  <MethodName>__(__<ParameterList>__);__\\
...\\
<AccessModifier> __final__ <Type>  <ConstantName> __=__ <Value>__;  // __constants\\
}\\
 
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:\\
 
<InterfaceName>  <VariableName> __= new__ <ClassWithInterfaceName>__();__\\
 
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.)
 
!Multi-Threading Support\\
Im java.lang package existiert die Klasse Thread (s 1.11.21). Threads can be in one of four states:\\
*new\\
*runnable\\
*blocked\\
*dead\\
 
\\[2.jpg]\\\\
 
Ein Thread ist entweder ein User-Thread oder ein Daemon-Thread, wobei erstere das Beenden der JVM verhindern.\\
Alle Objekte, die in einem Thread laufen sollen, müssen das Interface Runnable implementieren, das als einzige Methode run() enthält. Dieses implentierende Objekt wird einem Thread-Objekt im ctor übergeben und dann dessen start()-Methode aufgerufen. Eine Alternative ist die Klasse Thread zu spezialisieren, hat aber den Nachteil, daß diese Klasse von Thread erben muß, somit nicht von anderen Klassen erben kann und die Funktionalität nicht unbedingt erweitert. Daher ist die Realisierung mit dem Runnable Interface zu bevorzugen.\\
Das Erzeugen eines Threads ist eine sehr aufwendige Angelegenheit, daher ist eine Thread-Pooling Lösung anzustreben.\\
First methods can be declared as synchronized (see 1.11.11.2). Additionally java provides the synchronized statement to protect critical section by\\
 
__synchronized__ __(__<expression>__)__ <statements>\\
 
<expression> is an expression the must resolve to an object or an array. The synchronized statement attempts to acquire an exclusive lock for the object or array und garantiert, dass nur ein Thread auf das Objekt zugreift. Synchronität wird durch ein lock auch monitor genannt, daß für jedes java object und für jedes java class object existiert, verwaltet wird. Angeblich ist die Synchronisation über Methoden etwas schneller als über blocks. Die class Synchronisation kann auch durch \\
__\\__
__synchronized__ __(__<ClassName>__.class)__ <statements>\\
 
erreicht werden.\\
Beim Zugriff auf static variables ist besondere Vorsicht geboten, da es durchaus möglich ist, daß zwei Instanzen, die in unterschiedlichen Threads verwendet werden, auf diese eine statische Variable zugreifen. Deshalb gibt es ein per-class lock, der wiederum nur static Methoden lockt.\\
 
Außerdem besitzt die Klasse java.lang.Object die Methoden wait(), notify() und notifyAll().\\
!Properties\\
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.\\
!Class ‘Object’\\
 
Every java class extends Object but you don’t have to write \\
 
__class__ <ClassName> __extends Object__\\
 
Your classes may want to override the following Object methods: \\
 
|protected\\\\native|clone|The JVM requires classes to implement the java.lang.Cloneable interface to explicitly declare an object to have the capability to be cloned. The Object.clone() method will create a shallow copy of the current object, that is only the primitives and reference values are copied, so sharing all referenced objects. Um ein Objekt zu kreieren sollte nie ein ctor verwendet werden sondern super.clone() (s. [[24] page 70).
| |equals|in der Standardimplementierung von Object wird nur verglichen ob zwei zu vergleichende Objektereferenzen auf das gleiche physikalische Objekt zeigen, d.h. if a == b.
| |finalize|
| |getClass|
| |hashCode|wird im Zusammenhang mit Hashtable class verwendet. Damit ein Objekt korrekt in einer Hashtable verwaltet werden kann, muß dieses Objekt die equals() und hashCode() Methode überschreiben.
|final|notify()|removes one thread by random from the waiting list of this object.
|final|notifyAll()|removes all threads waiting for this object from the waiting list
| |String toString()|
| |wait()|calling wait() causes the thread to release control of the object's lock, which means that other threads are able to obtain the monitor for this object.
 
!Class ‘Class’\\
 
Java always maintains what is called run-time type information. You can access this information by working with the class Class and calling <Object>.getClass() or by <Object>.class. The class Class contains the following methods:\\
 
| |forName(String ClassName)|
| |Method getDeclaredMethod(
<MethodName>,\\\\<ArrayOfArgumentClasses>)|
| |getInterface()|
| |getName()|
| |getSuperClass()|
| |isArray()|
| ||
| |newInstance()|this calls only the default ctor
| |isInterface()|
| |toString()|
 
Interfaces are also stored in Class objects.\\
 
An object can also be created by a call to the newlnstance method of class Class, which performs these steps:\\
 
*A new object is created of the type represented by the class object for which the newlnstance method was invoked. As the new object is created, all its instance variables are initialized to their standard default values (§ Standard Default Values).\\
*The constructor for the newly created object is invoked with no actual arguments.\\
*After the constructor has returned, a reference to the newly created and initialized object is returned as the value of the call to the newlnstance method. The compile-time type of this reference will be Object, which is the declared return type of the newlnstance method, but its run-time type will be the type represented by the class object for which the newlnstance method was invoked.
 
![Class String, StringBuffer, StringTokenizer|JavaString]
 
!Class ‘Thread’ \\
The Thread class has the following operations:\\
 
|interrupt()|
|isalive()|
|join()|waits for the specified thread to cease to be alive or for the specified amount of milliseconds
|run()|is executed when the thread is running; override this operation to perform your task
|static void sleep(Millis)|puts the currently executing thread to sleep for the specified Time.
|start()|the run method will be called; returns immediately
|stop()|kills the thread
|yield()|aufgeben, abtreten
 
 
!Class ‘Runtime’\\
Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the static Runtime.getRuntime() method. \\
Über die Runtime-Instanz kann dann beispielsweise eine andere Applikation aufgerufen werden:\\
Process p = rt.exec("C:\\Programme\\Microsoft Office\\Office\\winword.exe");
 
!![I/O|JavaIO]
 
!!Reflection\\
A program that can analyze the capabilities of classes is called reflective. There are four classes in java.lang.reflect called Class, Field, Method and Constructor that allow analyzing the capabilities of a class. These classes describe the data fields, the operations and the constructors of a class.\\
!!Security \\
JDK 1.2 introduces a number of improvements over JDK 1.1. First, all code, regardless of whether it is local or remote, can now be subject to a security policy. The security policy defines the set of permissions available for code from various signers or locations and can be configured by a user or a system administrator. Each permission specifies a permitted access to a particular resource, such as read and write access to a specified file or directory or connect access to a given host and port.\\
At the heart of this access control lies the SecurityManager, a class defined in the java.lang package. Whenever a request is made to access a resource, the request is passed through the SecurityManager.\\
The runtime system organizes code into individual domains, each of which encloses a set of classes whose instances are granted the same set of permissions. It’s important to understand that a permission granted in a policy file applies to a class or a group of classes and not to an entire application or JVM instance. A domain can be configured to be equivalent to the sandbox, so applets can still be run in a restricted environment if the user or the administrator so chooses. Applications run unrestricted, as before, by default but can optionally be subject to a security policy.\\
[3.jpg]\\\\
 
A policy file is an ASCII text file and can be composed via a text editor or the graphical Policy Tool utility.\\
A security manager can be used in one of two ways:\\
*by explicitly installing it within your application by System.setSecurityManager(new SecurityManager())\\
*by specifying the –Djava.security.manager option when activating the JVM\\
!Security Tools\\
JDK 1.2 introduces three new tools: \\
*The keytool is used to create pairs of public and private keys, to import and display certificate chains, to export certificates, and to generate X.509 v1 self-signed certificates and certificate requests that can be sent to a certification authority.\\
*The jarsigner tool signs JAR (Java Archive format) files and verifies the authenticity of the signature(s) of signed JAR files.\\
*The Policy Tool (policytool) creates and modifies the policy configuration files that define your installation's security policy. \\
*__Policy Tool\\__
Whenever Policy Tool is started, it tries to fill in this window with policy information from what is sometimes referred to as the "user policy file". The user policy file is by default a file named .java.policy in your home directory. If Policy Tool cannot find the user policy file, it reports the situation and displays a blank Policy Tool window.\\
!Setting Security \\
Whenever you run an applet, or an application with a security manager, the policy files that are loaded and used by default are the ones specified in the "security properties file", which is located at one of the following <JRE>\lib\security\java.security.\\
The default is to have a single system-wide policy file and a policy file in the user's home directory which is on a NT system C:\WINNT\profiles\<User>\.java.policy und unter XP unter C:\Dokumente und Einstellungen\<User>\.java.policy. Aktuell liegen hier die Einstellungen auf dem Laptop. Wichtig ist hier das in java.security die beiden files relativ zum java.home Verzeichnis festgelegt werden (wird mit (z) u.a. ausgegeben).\\
In der aktuellen Java-Runtime (der IE benutzt (c:\program files{{{|}}}c:\Programme)\javasoft¬\jre¬\<Version>) gibt es ein Verzeichnis \lib\security\ in dem sich eine Datei java.policy befindet in der generelle Einstellungen gemacht werden können.\\
Alternativ kann man den policy file über die Kommandozeile festlegen, ob ein zusätzlicher oder ein anderer policy file verwendet werden soll. In erstem Fall muss ein einfaches Gleichheitszeichen, im zweiten Fall ein doppeltes Gleichheitszeichen verwendet werden soll z.B.:\\
 
__java –Djava.security.policy==WriteFile.policy WriteFile\\__
\\
Um den Zugriff auf Resourcen für bestimmte Klassen aus einer bestimmten Lokation festzulegen muss folgende Syntax verwendet werden:\\
 
__grant__ [[__codeBase__] __“__[[ __${__<PropertyName>__}__ {{{|}}} [[__jar:__]__file:/__<PathWithSlash>__/__[[ __* __{{{|}}} __- __{{{|}}} <JARFileName> [[__! __<Re¬la¬tive¬Classpath>]]] __{__\\
  __permission__ __java.util.PropertyPermission__ __“__<PropertyName>__”,__ __“__<AccessRight>”__;\\__
__}__\\
 
*wenn codeBase fehlt, gelten die Berechtigungen für alle Klassen\\
*PropertyName könnte z.B. ${user.home} sein\\
*jar: legt ein jar-file fest, der durch einen RelativeClasspath genauer spezifiziert werden kann\\
*legt fest, dass nicht nur Klassen aus class-files, sondern auch aus jar-files die Berechtigung haben.\\
*legt fest, dass auch Klassen aus class- und jar-files von subdirectories die Berechtigung haben.\\
 
Um den Zugriff auf Resourcen für bestimmte Klassen, die von einem bestimmten User gesignt sind,  festzulegen muss folgende Syntax verwendet werden:\\
 
__grant signedBy “__<Name>__”__ ...\\
 
Um alle Berechtigungen zu vergeben verwendet man:\\
 
__grant {\\__
__  permission java.security.AllPermission;\\__
__}\\__
\\
Um Applets Zugriff auf das System-Clipboard zu gewährleisten muß folgende Zeile eingefügt werden:\\
 
permission java.awt.AWTPermission "accessClipboard";\\
 
!!Internationalization\\
Eine wichtige Klasse in diesem Zusammenhang ist NumberFormat aus java.text. Funktioniert über property files und resource bundles. Es gibt im Java Tutorial einen speziellen Pfad für Internationalisierungsaspekte.\\
!!Difference between Java and C++\\
*no pointer and pointer arithmetic\\
*no unsigned type specifier\\
*no confusion between assignment and equality test\\
*no manual memory allocation\\
*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)\\
 
!!Exceptions \\
An ''exception'' is an event that occurs during the execution of a program that disrupts the normal flow of instructions. When such an error occurs within a Java method, the method creates an exception object and hands it off to the runtime system. The exception object contains information about the exception, including its type and the state of the program when the error occurred. The runtime system is then responsible for finding some code to handle the error. In Java terminology, creating an exception object and handing it to the runtime system is called ''throwing an exception''. \\
After a method throws an exception, the runtime system leaps into action to find someone to handle the exception. The set of possible "someones" to handle the exception is the set of methods in the call stack of the method where the error occurred. The runtime system searches backwards through the call stack, beginning with the method in which the error occurred, until it finds a method that contains an appropriate ''exception handler''. An exception handler is considered appropriate if the type of the exception thrown is the same as the type of exception handled by the handler. Thus the exception bubbles up through the call stack until an appropriate handler is found and one of the calling methods handles the exception. The exception handler chosen is said to ''catch the exception''. \\
If the runtime system exhaustively searches all of the methods on the call stack without finding an appropriate exception handler, the runtime system (and consequently the Java program) terminates if its a non-graphical application. A GUI application will return to the message loop.\\
A method informs its callers about the exceptions that it can throw, so that the callers can intelligently and consciously decide what to do about those exceptions. \\
Java exceptions must be instances of Throwable or any Throwable descendant. Im catch statement kann genau angegeben werden, ab welcher Hierachiestufe die Exceptions gecatcht werden sollen. Exception handlers that are too general, can make your code more error prone by catching and handling exceptions that you didn't anticipate and therefore are not correctly handled within the handler. It is not recommended writing general exception handlers as a rule. \\
Das runtime system throws sogenannte error Objekte, die durch interne Fehler ausgelöst werden. Objekte dieser Klasse sollten nie geworfen werden.\\
 
\\[4.jpg]\\\\
Runtime Exceptions werden ausgelöst durch bad cast, out-of-bounds array access oder null pointer access. Man sagt, dass bei diesen Exceptions in der Regel der Programmierer Schuld ist. \\
The java language specification calls any exception that derives from the class Error or RuntimeException an ''unchecked'' exception. All other exceptions are called ''checked''.\\
The Java language requires that methods either ''catch'' or ''specify'' all checked exceptions that can be thrown within the scope of that method. If a method chooses not to catch an exception, the method must specify that it can throw that exception. \\
If you override an operation from a parent class the child class cannot throw more checked exceptions than the parent class operation. It can throw fewer if it likes. \\
 
The compiler is somewhat selective as to which exceptions must be handled. For example when you access an array or perform a cast, you need not to supply an exception handler. However for other operations such as input and output you must specify what you want to happen.\\
Java has different types of exceptions, including I/O Exceptions, runtime exceptions, and exceptions of your own creation, to name a few. ''Checked exceptions'' are exceptions that are not runtime exceptions and are checked by the compiler; the compiler checks that these exceptions are caught or specified. \\
 
Die Vorteile von Exceptions sind\\
*Fehlerbehandlung an einer zentralen Stelle und nicht verteilt im Code\\
*Fehler werden automatisch auf dem Callstack hochgereicht\\
*Fehler können über Ableitungen von Throwable kategorisiert werden\\
 
The first step in constructing an exception handler is to enclose the statements that might throw an exception within a try block. In general, a try block looks like this: \\
 
__try \\__
{\\
    ''<''statements''>''\\
}\\
 
A try statement ''must'' be accompanied by at least one catch block or one finally block. \\
You associate exception handlers with a try statement by providing one or more catch blocks directly after the try block: \\
 
__try \\__
__{\\__
  ''<''statements>\\
__} \\__
__catch__ (<ThrowableObject> <variableName>) \\
__{\\__
  ''<''statements>\\
__} \\__
[[<catch statement>]\\
[[__finally\\__
__{__\\
  <statement>\\
__}\\__
\\
There can be no intervening code between the end of the try statement and the beginning of the first catch statement. The finally block is executed at any rate.\\
 
Not all bad things throw an exception. Floating-point operations do not throw an exception at all.\\
 
Exceptions are slow so don’t replace a simple test.\\
!!Garbage Collection and Finalization \\
To decrease the reference counter of an object just set the reference variable to null:\\
 
<VarName> = null;\\
 
It is also decreased when a variable goes out of scope. The garbage collector can even detect cycles of references when objects are referencing each other but are not referenced anywhere else.\\
 
The Java platform has a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector. A mark-sweep garbage collector scans dynamic memory areas for objects and marks those that are referenced. After all possible paths to objects are investigated, unmarked objects (unreferenced objects) are known to be garbage and are collected. (A more complete description of Java's garbage collection algorithm might be "a compacting, mark-sweep collector with some conservative scanning.") \\
The garbage collector runs in a low-priority thread and runs either ''synchronously'' or ''asynchronously'' depending on the situation and the system on which Java is running. It runs synchronously when the system runs out of memory or in response to a request from a Java program. \\
The Java garbage collector runs ''asynchronously'' when the system is idle, but it does so only on systems, such as Windows 95/NT, that allow the Java runtime environment to note when a thread has begun and to interrupt another thread. As soon as another thread becomes active, the garbage collector is asked to get to a consistent state and terminate. \\
 
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'' (see chapter 1.11.11.2.2 Finalize). If the finalization method of an object ‘resurrect’ the object by assigning the this reference to something and if the reference is deleted the finalization method isn’t called twice. Exception thrown by an finalization methods are ignored by the system. If the finalization method doesn’t call the base finalization the base finalization will never be called. The java interpreter might exit without calling the finalization method.\\
!!The Java Core Packages\\
In Java nennt man Bibliotheken packages. Folgende packages muessen bei jeder java Implementierung vorhanden sein:\\
 
java.lang\\
java.util\\
java.io\\
 
Folgende packages sind fast immer vorhanden:\\
 
java.awt.image  \\
java.awt.peer\\
java.awt\\
java.applet\\
java.net\\
!System Object\\
Methoden des system objects sind:\\
 
|arraycopy()|
|exit()|
|getProperty(String)|properties can be defined by java –D<PropertyName>=<PropertyValue>;\\\\es handelt sich dabei nicht um Umgebungsvariablen;\\\\u.a. kann man die Versionen der JVM und des JDK auslesen\\\\Applets can access some, but not all system properties
 
\\
 
!AWT\\
Das AWT (abstract window toolkit) abstrahiert die verschiedene Windows Plattformen und ist ein Teil der zum JDK zugehörigen Klassenbibliothek. Das AWT stellt folgende Objekte zur Verfügung:\\
 
|Button |
|Canvas|rechteckiger Bereich zum Zeichnen
|Checkbox|
|Choice|Drop-Down Liste
|Container|die darin enthaltenen Objekte können mit einem Layout-Manager angeordnet werden
|Label|Text
|List|Listbox
|Menu, MenuBar, MenuItem|
|PopUpMenu|
|TextArea|
|TextField|
\\
Die absolute Position kann mit setLocation() angegeben werden. \\
 
A window that is not contained in another window is called frame. \\
*__Class hierachy\\__
\\
 
\\[5.jpg]\\\\
 
*__Component\\__
\\
A generic Abstract Window Toolkit(AWT) container object is a component that can contain other AWT components. \\
Components added to a container are tracked in a list. The order of the list will define the components' front-to-back stacking order within the container. If no index is specified when adding a component to a container, it will be added to the end of the list (and hence to the bottom of the stacking order).\\
[6.jpg]\\\\
 
\\
*__Window\\__
\\
[7.jpg]\\\\
 
\\
*__Frame\\__
\\
In the AWT a top-level window (that is a window that is not contained inside another window) is called a frame . \\
 
\\[8.jpg]\\\\
 
*__Events\\__
\\
In the 1.1 AWT event model in contrast to Java 1.0, events are generated by event ''sources''. One or more ''listeners'' can register to be notified about events of a particular kind from a particular source. Sometimes this model is called ''delegation'', since it allows the programmer to delegate authority for event handling to any object that implements the appropriate listener interface. \\
Event handlers can be instances of any class. As long as a class implements an event listener interface, its instances can handle events. \\
Es gibt mehrere Event-Klassen wie z.B. ActionEvent, MouseEvent,... .\\
Es gibt mehrere Event Interfaces wie z.B. ActionListener, MouseListener,... , die jeweils die Methoden für die verschiedenen Action- bzw. Mouse-Events spezifizieren.\\
 
*Handling Events\\
 
__!!! deprecated\\__
Damit ein Applet auf Ereignisse reagieren kann muss es die action()-method der Klasse Component überschreiben. Die action()-method hat folgendes Interface:\\
 
public boolean action(Event event, Object object);\\
 
Das 'Event' Objekt enthält alle Informationen darüber, welches Ereignis eingetreten ist, in welchem Objekt es eingetreten ist sowie weitere Informationen, z.B. welche Taste gedrückt wurde oder wo ein Mausklick erfolgte. Bei einem Mausklick auf ein Button wird ein ACTION_EVENT verschickt und nur dadurch wird die action()-method aufgerufen. Das 'object' enthält einen String welcher Button gedrückt wurde. \\
__!!! deprecated end\\__
\\
 
Die neue Art des Event-Handling erfolgt über Listener. Dies kann sehr einfach durch folgende vier Schritte geschehen:\\
 
*import java.awt.*\\
*class <CLASSNAME> implements ActionListener \\
*<OBJECT>.addActionListener(this);\\
*public void actionPerformed(ActionEvent e){...};\\
 
Besser ist es eine Klasse zu entwickeln, die das ActionListener Interface implementiert und deren Objekte spezifisch angemeldet werden. \\
 
Weitere Möglichkeiten sind folgende :\\
 
addActionListener\\
(\\
  new ActionListener()\\
  {\\
    public void actionPerformed(ActionEvent event)\\
    { \\
      <statements which access the outer class>\\
    }\\
  }\\
)\\
 
\\
 
|__Listener Interface __|__Adapter Class __|__Methods __
|ActionListener |''none'''' ''|actionPerformed
|AdjustmentListener |''none'''' ''|adjustmentValueChanged
|ComponentListener |ComponentAdapter |componentHidden
componentMoved
componentResized
componentShown
|ContainerListener |ContainerAdapter |componentAdded
componentRemoved
|FocusListener |FocusAdapter |focusGained
focusLost
|ItemListener |''none'''' ''|itemStateChanged
|KeyListener |KeyAdapter |keyPressed
keyReleased
keyTyped
|MouseListener |MouseAdapter |mouseClicked
mouseEntered
mouseExited
mousePressed
mouseReleased
|MouseMotionListener |MouseMotionAdapter |mouseDragged
mouseMoved
|TextListener |''none'''' ''|textValueChanged
|WindowListener |WindowAdapter |windowActivated
windowClosed
windowClosing
windowDeactivated
windowDeiconified
windowIconified
windowOpened
\\
!!Applications\\
Every application must have a main()-method with a signature like :\\
class X\\
{\\
  public static void main(String[[] args)\\
  {\\
    ...\\
  }\\
} \\
Die Klasse muss nicht public sein, damit sie gerunt werden kann.\\
args[[0] enthaelt nicht wie in C/C++ den Programmnamen sondern das erste Argument. Wird ein Programm mit ‘java xx yy’ gestartet so enthält args[[0] den String ‘yy’. main() must be declared with a return type. To give back a return value call System.exit() which causes the interpreter to return immediately. The java interpreter runs until the method returns, or until the interpreter reaches the end of main. If no threads have been created the interpreter exits, otherwise the interpreter continues running until the last thread terminates.\\
!!RMI\\
The Java Remote Method Invocation (RMI) system allows an object running in one Java Virtual Machine (VM) to invoke methods on an object running in another Java VM. \\
Distributed object applications need to:\\
 
*__Locate remote objects__: Applications can use one of two mechanisms to obtain references to remote objects. An application can register its remote objects with RMI's simple naming facility, the rmiregistry, or the application can pass and return remote object references as part of its normal operation. \\
*__Communicate with remote objects__: Details of communication between remote objects are handled by RMI; to the programmer, remote communication looks like a standard Java method invocation. \\
*__Load class bytecodes for objects that are passed around__: Because RMI allows a caller to pass objects to remote objects, RMI provides the necessary mechanisms for loading an object's code, as well as for transmitting its data. \\
The following illustration depicts an RMI distributed application that uses the registry to obtain a reference to a remote object. The server calls the registry to associate (or bind) a name with a remote object, so the registry is running on the server. The client looks up the remote object by its name in the server's registry and then invokes a method on it. The illustration also shows that the RMI system uses an existing Web server to load class bytecode, from server to client and from client to server, for objects when needed. \\
 
\\[9.jpg]\\\\
 
\\
An object becomes remote by implementing a __remote interface__, which has the following characteristics:\\
*A remote interface extends the interface java.rmi.Remote. \\
*Each method of the interface declares java.rmi.RemoteException in its throws clause, in addition to any application-specific exceptions. \\
 
\\[10.jpg]\\\\
 
RMI treats a remote object differently from a non-remote object when the object is passed from one virtual machine to another. Rather than making a copy of the implementation object in the receiving virtual machine, RMI passes a remote __stub__ for a remote object. The stub acts as the local representative, or proxy, for the remote object and basically is, to the caller, the remote reference. The caller invokes a method on the local stub, which is responsible for carrying out the method call on the remote object. \\
A stub for a remote object implements the same set of remote interfaces that the remote object implements. This allows a stub to be cast to any of the interfaces that the remote object implements. However, this also means that only those methods defined in a remote interface are available to be called in the receiving virtual machine.\\
\\
When you use RMI to develop a distributed application, you follow these general steps. \\
*Design and implement the components of your distributed application. \\
*Compile sources and generate stubs. \\
*Make classes network accessible. \\
*Start the application. \\
 
Any entity of any type can be passed to or from a remote method as long as the entity is an instance of a type that is a primitive data type, a remote object, or a serializable object. The rules governing how arguments and return values are passed are as follows:\\
*Remote objects are essentially passed by reference. A remote object reference is a stub, which is a client-side proxy that implements the complete set of remote interfaces that the remote object implements. \\
*Local objects are passed by copy, using object serialization. By default all fields are copied, except those that are marked static or transient. Default serialization behavior can be overridden on a class-by-class basis.\\
In remote method calls objects -parameters, return values, and exceptions - that are not remote objects are passed by value. This means that a copy of the object is created in the receiving virtual machine. __Any changes to this object's state at the receiver are reflected only in the receiver's copy, not in the original instance__. \\
All programs using RMI must install a security manager, or RMI will not download classes (other than from the local class path) for objects received as parameters, return values, or exceptions in remote method calls. This restriction ensures that the operations performed by downloaded code go through a set of security checks. \\
The system provides a particular remote object, the RMI registry, for finding references to remote objects. The RMI registry is a simple remote object name service that allows remote clients to get a reference to a remote object by name. The registry is typically used only to locate the first remote object an RMI client needs to use. That first remote object then provides support for finding other objects. \\
Once a server has registered with the local RMI registry, it prints out a message indicating that it's ready to start handling calls and then the main method exits. The RMI system takes care of keeping the server’s process up. The server is available to accept calls and won't be reclaimed until its binding is removed from the registry, and no remote clients hold a remote reference to the server object.\\
!Threading and RMI\\
According to the rmi specs: "A method dispatched by the RMI runtime to a remote object implementation (a server) may or may not execute in a separate thread. Some calls originating from the same client virtual machine will execute in the same thread; some will execute in different threads. Calls originating from different client virtual machines will execute in different threads. Other than this last case of different client virtual machines, the RMI runtime makes no guarantees with respect to mapping remote object invocations to threads”.\\
What this means is that if you are maintaining state in the object between method calls or need synchronization, then the remote method must be synchronized in the interface, or it should use synchronizing in its implementation with synchronize(object). In other words, the remote object must be ''thread-safe''. \\
If RMI calls from the same JVM are packed into one thread, it can not be thread-safe. Because client may have multiple threads in one JVM, and in each thread it can call remote methods. In such a condition, the call sequence from different thread is not determined when they are put to one thread. If these calls change some status of server, then the result returned to each thread is not determined too.\\
!class UnicastRemoteObject\\
UnicastRemoteObject is a convenience class, defined in the RMI public API, that can be used as a superclass for remote object implementations. The superclass UnicastRemoteObject supplies implementations for a number of java.lang.Object methods (equals, hashCode, toString) so that they are defined appropriately for remote objects. UnicastRemoteObject also includes constructors and static methods used to export a remote object, that is, make the remote object available to receive incoming calls from clients. By extending UnicastRemoteObject, it is easy to create a simple remote object that supports unicast (point-to-point) remote communication and that uses RMI's default sockets-based transport for communication. \\
If extending UnicastRemoteObject is not possible than you can instead export the remote object by passing it to one of the static UnicastRemoteObject.exportObject() methods.\\
!class Activatable\\
Activatable Objects allow clients to reconnect to servers at different times across server shutdowns and restarts.\\
!!Applets\\
Ein einfaches Applet ist von der Klasse java.applet.Applet oder von javax.swing.JApplet abgeleitet .\\
!Aufruf und Test\\
Es gibt mehrere Möglichkeiten:\\
 
*AppletViewer <HTML file with APPLET-tag>\\
*jview /a <Class File with Extension>\\
*IE mit HTML file with APPLET-tag\\
!Difference between Applet and Application\\
Ein Applet läuft in einer anderen Laufzeitumgebung als eine Application .\\
In terms of source code, the basic differences between an applet and an application are as follows:\\
*An applet must define a class derived from the Applet class. An application can do the same, but it is not required to do so\\
*An application must define a class with a method named main() that controls its execution. An applet does not use a main() method; its execution is controlled by various methods defined by the Applet class.\\
!Methoden eines Applets
|method:|comment:
|action()|__deprecated__; Component::action(); der Code der Superklasse 'Applet' registriert automatisch, daß es über Ereignisse inder Benutzeroberfläche informiert werden möchte, indem seine action() Methode aufgerufen wird, daher muß ein Applet diese Methode überschreiben, wenn es darauf reagieren möchte.
|destroy()|wird aufgerufen, wenn das Applet beendet oder entladen wird
|getAppletContext()|
|getAppletInfo()|gibt ein String zurück der alles mögliche enthalten kann
|getCodeBase()|URL that specifies the directory from which the applet's classes were loaded
|getDocumentBase()|URL that specifies the directory of the HTML page that contains the applet and the filename of the java byte code appended
|getParameter()|
|getParameterInfo()|gibt ein Array von String-Arrays zurück, daß die Parameter in der Syntax <Name>, <Type>, <Beschreibung> beschreibt, die für ein Applet gesetzt werden können
|init()|wird aufgerufen, wenn ein Applet erstmals geladen oder neu geladen wird; hier können Applet-Parameter mit getParameter() eingelesen werden und ist daher dem ctor vorzuziehen
|mousedown()|__deprecated__;
|paint()|
|start()|wenn die Seite, die das Applet enthält, erstmals auf dem Schirm erscheint
|showStatus()|
|stop()|wenn die Seite mit Applet nicht mehr auf dem Schirm erscheint
!Debugging Applets\\
*Use showStatus() which shows string on browser's status window. \\
*Create a TextArea or TextField for displaying intermediate results. \\
*Use JDB that comes with JDK. \\
*Use tools such as Jbuilder, Visual cafe, MS J++. \\
*s. http://www.javaworld.com/javaworld/jw-01-1997/jw-01-applet.to.app-2.html\\
 
!!Java Naming and Directory Interface (JNDI)
 
!Basics
A fundamental facility in any computing system is the naming service - the means by which names are associated with objects and objects are found based on their names. \\
A naming service's primary function is to map people-friendly names to objects, such as addresses, identifiers, or objects typically used by computer programs. For example, the Internet Domain Name System (DNS) maps machine names (such as www.sun.com) to IP addresses (such as 192.9.48.5). A file system maps a filename (for example, c:\bin\autoexec.bat) to a file handle that a program can use to access the contents of the file. The Lightweight Directory Access Protocol (LDAP) naming convention orders components from right to left, delimited by the comma character (","). Thus the LDAP name cn=Rosanna Lee, o=Sun, c=US names an LDAP entry cn=Rosanna Lee, relative to the entry o=Sun, which in turn, is relative to c=us. The LDAP has the further rule that each component of the name must be a name/value pair with the name and value separated by an equals character ("="). \\
The association of a name with an object is called a __binding__. For example, a file name is bound to a file. The DNS contains bindings that map machine names to IP addresses. An LDAP name is bound to an LDAP entry. \\
A __context__ is a set of name-to-object bindings. Every context has an associated naming convention. A context provides a lookup (resolution) operation that returns the object and may provide operations such as those for binding names, unbinding names, and listing bound names. A name in one context object can be bound to another context object (called a subcontext) that has the same naming convention. \\
For example, a file directory, such as /usr, in the UNIX file system is a context. A file directory named relative to another file directory is a subcontext (some UNIX users refer to this as a subdirectory). That is, in a file directory /usr/bin, the directory bin is a subcontext of usr. In another example, a DNS domain, such as COM, is a context. A DNS domain named relative to another DNS domain is a subcontext. For example, in the DNS domain Sun.COM, the DNS domain Sun is a subcontext of COM.\\
A __naming system__ is a connected set of contexts of the same type (they have the same naming convention) and provides a common set of operations. For example, a system that implements the DNS is a naming system. A system that communicates using the LDAP is a naming system. A __naming system__ provides a naming service to its customers for performing naming-related operations.\\
[12.jpg]\\\\
 
Many naming services are extended with a directory service. A __directory service__ associates names with objects and also allows such objects to have attributes. Thus, you not only can look up an object by its name but also get the object's attributes or search for the object based on its attributes. An example is the telephone company's directory service. It maps a subscriber's name to his address and phone number. A computer's directory service is very much like a telephone company's directory service in that both can be used to store information such as telephone numbers and addresses. The computer's directory service is much more powerful, however, because it is available online and can be used to store a variety of information that can be utilized by users, programs, and even the computer itself and other computers. \\
A __directory object__ represents an object in a computing environment. A directory object can be used, for example, to represent a printer, a person, a computer, or a network. A directory object contains attributes that describe the object that it represents. \\
A directory object can have attributes. For example, a printer might be represented by a directory object that has as attributes its speed, resolution, and color. A user might be represented by a directory object that has as attributes the user's e-mail address, various telephone numbers, postal mail address, and computer account information. \\
An __attribute__ has an attribute identifier and a set of attribute values. An attribute identifier is a token that identifies an attribute independent of its values. For example, two different computer accounts might have a "mail" attribute; "mail" is the attribute identifier. An attribute value is the contents of the attribute. The email address, for example, might have an attribute identifier of "mail" and the attribute value of "john.smith@somewhere.com".\\
A __directory__ is a connected set of directory objects. A __directory service__ is a service that provides operations for creating, adding, removing, and modifying the attributes associated with objects in a directory. The service is accessed through its own interface. \\
You can look up a directory object by supplying its name to the directory service. Alternatively, many directories, such as those based on the LDAP, support the notion of __searches__. When you search, you can supply not a name but a query consisting of a logical expression in which you specify the attributes that the object or objects must have. The query is called a __search filter__. This style of searching is sometimes called reverse lookup or content-based searching. The directory service searches for and returns the objects that satisfy the search filter.\\
[13.jpg]\\\\
 
!Overview\\
The Java Naming and Directory InterfaceTM (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the JavaTM programming language. It is defined to be independent of any specific directory service implementation. Thus a variety of directories - new, emerging, and already deployed - can be accessed in a common way.\\
The JNDI architecture consists of an API and a service provider interface (SPI). Java applications use the JNDI API to access a variety of naming and directory services. The SPI enables a variety of naming and directory services to be plugged in transparently, thereby allowing the Java application using the JNDI API to access their services. See the following figure. \\
[14.jpg]\\\\
 
The JNDI is divided into five packages: \\
 
javax.naming \\
javax.naming.directory \\
javax.naming.event \\
javax.naming.ldap \\
javax.naming.spi \\
 
The javax.naming package defines a Context interface, which is the core interface for looking up, binding/unbinding, renaming objects and creating and destroying subcontexts.\\
The most commonly used operation is lookup(). You supply lookup() the name of the object you want to look up, and it returns the object bound to that name. For example, the following code fragment looks up a printer and sends a document to the printer object to be printed. \\
 
Printer printer = (Printer)ctx.lookup("treekiller");\\
 
The javax.naming.directory package extends the javax.naming package to provide functionality for accessing directory services in addition to naming services. This package allows applications to retrieve attributes associated with objects stored in the directory and to search for objects using specified attributes. \\
!!JavaDoc\\
JavaDoc comments start with __/**__ and end with __*/__. Documentation comments are recognized only when placed immediately before class, interface, constructor, method, or field declarations. The ''description'' begins after the starting delimiter /** and continues until the tag section. The tag section starts with the first character __@__ that begins a line (ignoring leading asterisks, white space and comment separator). The description cannot continue after the tag section begins. There can be any number of tags -- some types of tags can be repeated while others cannot. A ''''''tag'''''' is a special keyword within a doc comment that Javadoc can process. Javadoc has standard tags, which appear as @tag, and in-line tags, which appear within braces, as {@tag}. \\
The text must be written in HTML, in that they should use HTML entities and can use HTML tags. Java allows declaring multiple fields in a single statement, but this statement can have only one documentation comment, which is copied for all fields. Therefore if you want individual documentation comments for each field, you must declare each field in a separate statement. Tags are:\\
 
|@author| |Class
|@deprecated| |Package, Class, Field, Method
|@exception|Is synonym for @throws|
|@param| |Method
|@return| |Method
|@see| |Package, Class, Field
|@serial| |Field, Method
|@since| |Package, Class, Field
|@throws| |Method
|@version| |Class,
\\
 
Package tags are tags that can appear in the documentation comment for a package (which resides in the source file named package.html). \\
!!Debugging\\
Um bedingte Compilierung zu implementieren wird in [[20] auf S.22 vorgeschlagen eine boolsche Variable zu definieren und if (Variable) { DebugCode; } zu implementieren, da offensichtlich Compiler diesen Code nicht erzeugen würden, wenn zur Compilezeit feststeht, daß Variable immer false ist.  Beispiel:\\
 
public class debug \\
{ \\
  public static final boolean DEBUGGING_ON = true; \\
} \\
 
Now, wherever you want debug code, use that in a conditional e.g. \\
 
if (debug.DEBUGGING_ON) \\
{ \\
  System.out.println("I am in here"); \\
} \\
 
\\
'Enable java logging' in the IExplore 4.0 and IE5 creates a file javalog.txt in WinNT4.0\Java directory. This file contains all system object output and therefore can be used as a trace file. It contains all output written with system.out.print[[ln]().\\
 
\\
!!Ausgaben / User Interface \\
 
In einer Konsolenapplikation kann über die Klasse PrintStream bzw. deren Methods Ausgaben mit den verschiedenen Datentypen gemacht werden, z.B. über das Systemobjekt.\\
 
System.out.print(3.11);\\
System.out.println(2);\\
 
Die Ausgaben eines Applet werden browserabhängig behandelt. Im IE werden bei enableten Logging die Ausgaben in eine Datei (s. Kapitel 1.30) bzw. in eine speziell zu öffnende Konsole geschrieben.\\
!Graphics\\
Eine andere Möglichkeit sind Graphik-Objekte vom Typ 'graphics' mit deren Memberfunktionen wie 'drawString()' oder 'fillOval()' graphische Ausgaben gemacht werden können. Einheiten sind Pixel.\\
!Layout Manager\\
Layout-Manager können einem java.awt.Container (die Applet-Klasse ist eine Spezialisierung davaon) über Container.setLayout(LayoutManager) zugewiesen werden. Diese übernehmen die Positionierung der darin enthaltenen Elemente. Alle Layout-Manager des JDK sind in der Lage, auf Größenänderungen ihres Containers zu reagieren und passen die in ihnen angeordneten Objekte entsprechend an. Jeder Containertyp hat seinen speziellen Default-LayoutManager.\\
 
*BorderLayout\\
*CardLayout\\
*FlowLayout\\
*GridLayout(rows,cols,hgap,vgap)\\
*GridBagLayout\\
 
\\[15.jpg]\\\\
 
Dem Container werden über Container.add(Component) Elemente hinzugefügt, die vom LayoutManager positioniert werden.\\
Bei einem Applet kann man über <Applet>.add() Elemente hinzufügen, bei JApplet kann dies nur über die zugehörigen ContentPane also durch <JApplet>.getContentPane().add() geschehen.\\
!!!ANT\\
Ant ist das Make für Java (s. [Ant])
 
!!![Swing]
 
!!!JDBC\\
Die Standard-Sequenz lautet:\\
*Treiber laden\\
try\\
{\\
  Class.forName(“<DriverName>”)\\
}\\
catch (ClassNotFoundException e)\\
{\\
}\\
*Verbindung herstellen\\
connection = DriverManager.getConnection(“<ConnectionString>”);\\
*Anweisung erzeugen\\
statement = connection.createStatement();\\
*Verbindung schliessen\\
connection.close();\\
Die Verbindung wird auch im ctor von connection geschlossen.\\
!!Anfragen stellen\\
queryString = “SELECT * FROM T_X”;\\
ResultSet rs = statement.executeQuery(queryString);\\
!!über Abfrageergebnis iterieren\\
while (rs.next())\\
{\\
  ...\\
}\\
!!Feld auslesen\\
z.B. mit\\
int ID = rs.getInt(“AttributeName”);\\
 
!!Transaction Handling\\
A transaction consists of one or more statements that have been executed, completed, and then either committed or rolled back. When the method commit or rollback is called, the current transaction ends and another one begins. \\
Generally a new Connection object is in auto-commit mode by default, meaning that when a statement is completed, the method commit will be called on that statement automatically. In this case, since each statement is committed individually, a transaction consists of only one statement. If auto-commit mode has been disabled, a transaction will not terminate until the method commit or rollback is called explicitly, so it will include all the statements that have been executed since the last invocation of either commit or rollback. In this second case, all the statements in the transaction are committed or rolled back as a group. \\
The beginning of a transaction requires no explicit call; it is implicitly initiated after disabling auto-commit mode or after calling the methods commit or rollback. The method commit makes permanent any changes an SQL statement makes to a database, and it also releases any locks held by the transaction. The method rollback will discard those changes. \\
Sometimes a user doesn't want one change to take effect unless another one does also. This can be accomplished by disabling auto-commit and grouping both updates into one transaction. If both updates are successful, then the commit method is called, making the effects of both updates permanent; if one fails or both fail, then the rollback method is called, restoring the values that existed before the updates were executed. \\
Most JDBC drivers will support transactions. In order to be designated JDBC Compliant, a JDBC driver must support transactions. \\
The JDBC 2.0 Standard Extension API makes it possible for Connection objects to be part of a distributed transaction, a transaction that involves connections to more than one DBMS server. When a Connection object is part of a distributed transaction, a transaction manager determines when the methods commit or rollback are called on it. Thus, when a Connection object is participating in a distributed transaction, an application should not do anything that affects when a connection begins or ends. \\
!!JDBC-ODBC Bridge \\
JavaSoft decided to deliver an experimental JDBC-ODBC bridge. The JDBC-ODBC Bridge driver is recommended for use in prototyping efforts and for cases where no other JDBC technology-based driver exists. \\
!!JDBC-MySQL\\
Der MySQL-JDBC Treiber liegt z.Zt. unter c:\uwes\mm.mysql-2.0.8. Dieses Verzeichnis wird an den CLASSPATH angehängt und muss beim Austausch aktualisiert werden.\\
!!!Tools\\
 
!!Symantec’s Cafe\\
SC.INI\\
!!Visual J++\\
Visual J++ ist eine vollständige Implementation der gesamten Java-Technologie und enthält darüber hinaus eine Reihe von Microsoft-eigenen Erweiterungen. Was das 'Visual' angeht ist es aber bzgl. C++ oder Basic die schlechteste Unterstützung. \\
 
Mit der MS VJM ist es möglich sowohl von Java aus ActiveX Komponenten aufzurufen oder ActiveX Komponenten in Java zu schreiben.\\
 
\\
!SDK\\
 
The __Microsoft SDK for Java™ __provides the tools, information, and samples to help you develop Java programs and applets based on JDK 1.1 and the Microsoft Win32 Virtual Machine for Java (Microsoft VM). The current version is SDK 3.1. \\
!Packages\\
 
Microsoft liefert mit VJ++ neben den Standard-Packages eine Reihe zusätzlicher Packages aus:\\
 
*com.ms.com (activeX)\\
*com.ms.applet  (activeX)\\
*com.ms.awt (activeX) \\
*com.ms.lang    (registry access)\\
*com.ms.wininet (windows internet)\\
 
Für alle Klassen gilt, daß sie nur auf der MS VJM laufen.\\
!Creating a Java Project\\
 
File-> New-> Java Project\\
 
\\
!Building a Java Project\\
 
Build-> Build <Project>\\
 
\\
!Creating an Project Using the Applet Wizard\\
 
The Applet Wizzard lets you create a normal applet or an applet which can be run as an application.\\
 
File-> New-> Java Applet Wizzard-> ...-> \\
 
Applet Wizard has generated code to handle this difference, giving the program a graphical user interface even when it's run as an application. Applet Wizard does this by defining a class derived from the Frame class. This class, in conjunction with the program's Applet-derived class, provides a window for the application, allowing the same graphical user interface code to run. This Frame window class is used only when the program is executed stand-alone.\\
 
\\
!Creating a Project out of a .java File\\
 
Just open a .java file and try to build it. You will be asked for creating a project.\\
 
!Specify a HTML Page for an Applet\\
 
Project-> Settings-> Debug Tab-> Browser Entry\\
 
\\
!Running an Applet with and without a HTML Page or as standalone Applet\\
 
Build-> Execute -> type <ClassName>\\
 
use JVIEW.EXE\\
 
Project-> Settings-> General Tab -> check 'stand-alone interpreter' which internaly calls JVIEW.EXE\\
 
\\
!JView\\
 
The Visual J++ Java interpreter is named JView. You can run an application from the command line by typing JView and the name of the class that defines a main() method or you can run an applet by specifying the '/a' command line option.\\
 
!Resource Wizard\\
 
Resource Wizard is a tool for converting Windows resource templates into equivalent Java code. Resource Wizard uses a resource template (.RCT or .RES) file as input.\\
 
*__Adding or Changing a Resource\\__
\\
File-> New-> Resource Template-> ...\\
 
Not all control types are supported by the AWT. To get more information which controls are supported see chapter 'Using Java GUI Components' of the books online information.\\
For each box or menu in the resource template, Resource Wizard creates a .JAVA file containing a class whose name is the ID of the dialog box or menu. In addition, when there are dialog boxes in the resource template, Resource Wizard also creates a separate file for a DialogLayout class, which is used by the dialog class(es) to manage the layout of controls. \\
 
There's no need to edit the source code in the Resource Wizard-generated .JAVA file(s). If you want to make any changes to your menu or dialog box, use the Menu editor or Dialog editor, re-save the resource template, and run Resource Wizard to regenerate the .JAVA file(s).\\
 
\\
*__To use the dialog class in your Java program\\__
\\
Add the following line to the source file where you want to use the dialog:\\
 
import <FileName>;\\
 
Create a member variable of the type of the class for the dialog\\
 
<ClassName> <MemberName>;\\
 
In the applet's init() method, remove the call to resize() and add the following lines: \\
 
<MemberName> = new <ClassName>(this);\\
<MemberName>.CreateControls();\\
 
\\
*Fill a Dialog with Life\\
 
\\
 
!Java and COM \\
 
Um ein COM-Objekt innerhalb eines Applet verwenden zu können, müssen zunächst einige *.class Files erstellt werden, die die Schnittstellen beschreiben. Diese Aufgabe wird vom Typbibliothek-Assisten (der offensichtlich das Kommandozeilen –Tool ‘jactivex.exe’ aufruft bzw. genau dasselbe macht’) unterstützt. Der Assistent erzeugt für jede Schnittstelle eine seperate Klasse. Die Klassen werden als Java-Paket im Unterverzeichnis \<NTDIR>\java\trustlib abgelegt.\\
Es gibt leider viele Interface-Definitionen , aus denen zwar eine Type-Library generiert werden kann, die aber nicht mit dem Typbibliotheks-Assisten bzw. mit ‘jactivex’ weiterbearbeitet werden kann. Man kann aber die Type-Library mit dem OLE/COM Object Viewer anschauen und es befinden sich alle Information darin.\\
 
\\
*____Find out HRESULT\\____
\\
!!JBuilder von Borland/Inprise\\
 
!!Visual Age von IBM\\
 
\\
!!!Offene Fragen\\
 
Q: Wie funktioniert das mit den System- bzw. globalen Objekten wie z.B. System und offensichtlich auch NumberFormat.\\
A: Es kann sich auch um statische Methoden handeln, da von diesen kein Objekt angelegt werden muss, die aber über die Syntax <ClassName>.<StaticMethodName> aufgerufen werden.\\
 
Q: Wie funktioniert System.out.println(“xxx“ + this) ? toString?\\
A: Offensichtlich ist es Bestandteil der Sprache, weil toString() method von der Klasse Object ist und daher der Compiler genau weiss, welche Methode aufzurufen ist .\\
 
Q: What has to be listed in the CLASSPATH Variables? directories, files or both?\\
A: Der classpath is a list of directories or zip/jar files to search for class files (see 1.5 Finding the classes).\\
 
Q: Oben stand mal Im Gegensatz zu C++ kann man schon in der new Anweisung Methoden aufrufen z.B.new Rectangle(100, 50).area(). Stimmt das?\\
A: int i = new X().getInt(); geht.\\
 
\\
Q: Aufruf einer bestimmten Basisklassenfunktionalität in einer Hierachie, ist das möglich?\\
A:\\
 
Q: Wie funktionieren Default-Implementationen in abstrakten classes bzw. interfaces?
A: \\
 
Q: Kann ein ctor Exceptions werfen?\\
A:\\
 
Q: Was ist, wenn eine überschriebene Methode eingeschränktere Zugriffsrechte hat z.B. weil clone() protected ist?\\
A:\\
 
!!!Problems\\
 
Real-time capability\\
Carbage-Collector behavior is not deterministic\\
 
!!!Beispiele\\
 
*unter D:\java\ActiveVJ sind die Beispiele aus [[1]\\
*Applet2 ist das CTANA-Faceplate\\
*Count.Java  D:\JAVA\MYPROJECTS\COUNTCHARSINFILE\\\
*Multi.Java  D:\JAVA\MYPROJECTS\MULTIPLECLASSESINONEFILE\\\
*Version.Java  D:\JAVA\MYPROJECTS\VERSION\\\
*HelloWorldApp D:\JAVA\MYPROJECTS\CONSOLEAPPLICATION\\\
*Initialization D:\ JAVA\MYPROJECTS\INITIALIZATION\\
*VariableDeclaration D:\JAVA\MYPROJECTS\VARIABLEDECLARATION\\\
*WrongFileExtension D:\JAVA\MYPROJECTS\WRONGFILEEXTENSION\\
*Breaks D:\JAVA\MYPROJECTS\BREAKS\\
*ReturnReferences D:\JAVA\MYPROJECTS\RETURNREFERNCES\\
*Overriding D:\JAVA\MYPROJECTS\OVERRIDE\\
*ArrayTest D:\JAVA\MYPROJECTS\ARRAYTEST\\
*Shadow D:\JAVA\MYPROJECTS\SHADOW\\
*Strings D:\JAVA\MYPROJECTS\STRINGS\\
*FrameApplication D:\JAVA\MYPROJECTS\FRAMEAPPLICATION\\
*Dependencies D:\JAVA\MYPROJECTS\DEPENDENCIES\\
*Identy D:\JAVA\MYPROJECTS\IDENTY\\
*SimpleApplet D:\JAVA\MYPROJECTS\VISUALCAFE\SIMPLEAPPLET.JAVA\\
*Threads \JAVA\MYPROJECTS\THREADS\\
*Promotion \JAVA\MYPROJECTS\PROMOTION\\
*MyFirstServlet \TOMCAT\WEBAPPS\ROOT\WEB-INF\CLASSES\MyFirstServlet.java\\
*Ctor D:\JAVA\MYPROJECTS\CTOR\\\
*Import D:\JAVA\MYPROJECTS\IMPORT\\\
*launchword D:\Uwes\java\myprojects\launchword\\\
*GetProps D:\JAVA\MYPROJECTS\SECURITY\GETPROPS\\\
*JarClassLoader c:\uwes\java\myprojects\JarClassLoader\\\
 
\\
!!!Abbrevations\\
 
!!!Index\\
 
accessor method  22\\
class variables  21\\
jactivex  67\\
Java API  6\\
javac  8\\
mutator method  22\\
\\
 
!!!Newsgroup\\
 
*comp.lang.java.programmer \\
*comp.lang.java.help \\
*comp.lang.java.gui \\
*comp.answers. \\
 
!!!LITERATURE\\
 
*Schlabach, Thorsten: Visual J++ 1.1, Addison-Wesley\\
*[''www.javasoft.com''|http://www.javasoft.com/] – the JavaSoft homepage\\
*The Java Language Specification. From [[2]\docs\books. Already downloaded as langspec-1_0.pdf and readable with an acrobat reader. Ist auch bei Addison Wesley aufgelegt (2.Auflage).\\
*Understanding the JAVA/COM Integration Model; Dev-Studio Help; printed\\
*[[http://www.javasoft.com/docs/books/tutorial]|http://www.javasoft.com/docs/books/tutorial] currently installed at D:\JAVA\TUTORIAL\\
*[[http://java.sun.com/docs/books/tutorial/java/index.html]|http://java.sun.com/docs/books/tutorial/java/index.html] currently installed at D:\JAVA\TUTORIAL\\
*[[http://www.microsoft.com/java/]|http://www.microsoft.com/java/]\\
*http://www.www-net.com/java/faq\\
*MSDEV Online Help: Visual J++/Java and COM\\
*Scott Robert Ladd: Active Visual J++\\
*D:\java\tutorial\essential\exceptions\index.html\\
*SDK 3.1 Documentation in file JSDK31.CHM currently in D:\JAVA\SDK-Java.31\docs\sdkdocs\\
*How Does the JVM Search for Java Classes in [[http://support.microsoft.com/support/kb/articles/q177/1/68.asp]|http://support.microsoft.com/support/kb/articles/q177/1/68.asp] \\
*Core Java 1.1 by Cay S. Horstmann and Gary Cornell, Volume I\\
*newsgroup comp.lang.java.programmer\\
*Java Spektrum; SIGS Verlag\\
*[''www.jdc.com''|http://www.jdc.com/] (Java Development Cooperation)\\
*Core Java 1.1 by Cay S. Horstmann and Gary Cornell, Volume II\\
*JDK1.2 documentation; currently installed in D:\java\JDK1.2\docs\index.html\\
*JAVA in a nutshell; David Flanagan\\
*The Java Language Environment; A White Paper; James Gosling & Henry McGilton; print out\\
*Java calling; Entwicklerkonferenz JavaOne in San Fransisco;\\
*file:///C{{{|}}}/jdk1.2/docs/relnotes/features.html\\
*Java Pitfalls; Wiley Computer Publishing\\
*diverse geladene Seiten unter d:\java\docs\security\\\
*D:\java\docs\Security\Java 1_2 Unleashed -- Ch 3 -- The Extended Java Security Model.htm\\
*Verzaubertes Java; ct 20/01; S. 188\\
 
\\

Latest revision as of 21:13, 21 December 2013