76
1 Teil 4 - Java Programmstruktur Datentypen Schlüsselwörter Operatoren Kontrollstrukturen

Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

1

Teil 4 - JavaProgrammstrukturDatentypen SchlüsselwörterOperatoren Kontrollstrukturen

Page 2: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS20082

Kommentare in Java

Alle Zeichen zwischen dem „/**“ und dem „*/“werden ignoriert.

für das javadoc-Programm des JDK. Mit ihrer Hilfe wird eine einfache Online-Dokumentation erstellt.

/*** javadoc-Kommentar* @since JDK1.0* /

Alle Zeichen zwischen dem „/*“ und dem „*/“werden ignoriert.

auskommentieren von Programmteilen.Die Schachtelung der „Kommentar-klammern“ ist nicht erlaubt.

/* Kommentar über mehrere Zeilen */

Alle Zeichen nach dem „//“ werden ignoriert.für „normale“ einzeilige Kommentare.

// Kommentar

In Java gibt es drei Möglichkeiten zur Kommentierung:

Page 3: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS20083

Javadoc

Homepage: http://java.sun.com/j2se/javadoc/

Aufruf (unter dem „bin“-Ordner des JDK):javadoc [ options ] [ packagenames ] [ sourcefilenames ] [-subpackages pkg1:pkg2:... ] [ @argfiles ]

Tags @author; {@code}; {@docRoot}; @deprecated; @exception; {@inheritDoc}; {@link}; {@linkplain}; {@literal}; @param; @return; @see; @serial; @serialData; @serialField; @since; @throws; {@value}; @version

Page 4: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Javadoc Beispiel

/** * Returns an Image object that can then be painted on the screen. * The url argument must specify an absolute {@link URL}. The name* argument is a specifier that is relative to the url argument. * <p> * This method always returns immediately, whether or not the* image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives * that draw the image will incrementally paint on the screen. * * @param url an absolute URL giving the base location of the image * @param name the location of the image, relative to the url argument* @return the image at the specified URL * @see Image */ public Image getImage(URL url, String name)

{ try{ return getImage(new URL(url, name));

} catch (MalformedURLException e) { return null; }}

Page 5: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS20085

Regeln für Namensgebung

• es wird zwischen Groß- und Kleinschreibung unterschieden,

• das erste Zeichen muß ein Buchstabe sein,

• Rest kann aus Zahlen, dem '_' und Buchstaben bestehen,

• Leerzeichen und andere Sonderzeichen ( +, © , # , ~, etc) sowie reservierte Wörter (Schlüsselwörter, siehe nächste Folie) sind nicht erlaubt.

Page 6: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS20086

Bezeichner - Konvention

RestAnfang

durchgehen groß mit UnterstrichengrossKonstante

Teilworte aneinandergereiht ohne Unterstriche, z.B. setText

kleinMethode

kleinVariable

Teilworte aneinandergereiht ohne Unterstriche, z.B. TextConverter

grossKlasse

durchgehend klein, TeilwortkleinPaket

Page 7: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS20087

Schlüsselwörter in JavaIn Java gibt es eine Reihe von reservierten Schlüsselworten.

Sie dürfen nicht für eigene Bezeichner verwendet werden.

Die mit * gekennzeichneten Wörter sind zwar reserviert, werden aber in der Version 1.5 von Java (noch) nicht verwendet.

trystaticlongfinallyconst*

trueshortinterfacefinalclasstransientreturnintfalsechar

throwspublicinstanceofextendscatchthrowprotectedimportenumcasethisprivateimplementselsebytesynchronizedpackageifdoublebreak

whileswitchnullgoto*doboolean

volatilesupernewfordefaultassertvoidstrictfpnativefloat continueabstract

Page 8: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS20088

Primitive Datentypen in JavaDie übliche Struktur in Java ist das Objekt. Es gibt in Java aber auch einfache (primitive) Datentypen.

Einfachen Datentypen haben also einen vorgegeben Standardwert.±4.9E-324 bis ±1.8E+3080.0Gleitkommazahl (64 Bit)double±1.4E-45 bis ±3,4E+380.0Gleitkommazahl (32 Bit)float

-263 bis 263-10Ganze Zahl mit Vorzeichen (64 Bit)long

-231 bis 231-10Ganze Zahl mit Vorzeichen (32 Bit)int

-32768 bis 327670Ganze Zahl mit Vorzeichen (16 Bit)short-128 bis 1270Ganze Zahl mit Vorzeichen (8 Bit)byte

\u0000 bis \uFFFF\u0000Unicode-Zeichensatz (16 Bit)char

true oder falsefalseWahrheitswert true oder false (8 Bit)booleanBereichDefaultInhaltTyp

Page 9: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS20089

Primitive DatentypenGanzzahltypen

• byte, short, int, long

• werden intern im 2er-Komplement dargestellt (vorzeichenbehaftet).

– 1. Bit gibt Vorzeichen an (0 == positiv; 1 == negativ)– Positive Zahlen werden binär dargestellt, z.B.:

4(10) = 00000100(2)

– Bei negative Zahlen wird der Wert ohne Vorzeichen binär dargestellt, invertiert und +1 gerechnet; z.B. -4:Wert ohne +/-: 4(10) = 0000100(2)invertieren: 1111011(2)1 addieren: 1111100(2)

-4(10) = 11111100(2)

Page 10: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200810

Primitive Datentypen

Gleitkommatypen• float – 32 Bit: 1 Bit Vorzeichen

8 Bit Exponenten23 Bit Mantisse

• double – 64 Bit: 1 Bit Vorzeichen11 Bit Exponenten52 Bit Mantisse

• werden intern nach IEEE (Institute of Electrical and Electronics Engineers) dargestellt (IEEE 754)

System.out.println( 2345678.88f ); // 2345679.0

Page 11: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200811

Primitive Datentypen

Zeichentyp• char (ein Zeichen aus dem Unicode)

• ASCII Code ist ein Untermenge vom Unicode

• Unicode (Norm zur Zeichendarstellung) 2 Byte (65536 Zeichen)http://de.selfhtml.org/inter/unicode.htm

• ASCII Code \u0000 bis \u007F http://www.unicode.org/charts/PDF/U0000.pdfBeispiel: char wasIstDas= '\u0040';

@

Page 12: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200812

Primitive DatentypenWahrheitstyp(für logische Abfragen)

• booleanDer Wert kann nur false oder true annehmen.

• Anmerkung: In C/C++ können die Wahrheitswerte falseund true durch die Zahlen 0 und 1 ausgedrückt werden.Das ist aber in JAVA nicht möglich.

Page 13: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200813

VariablenJede Variable muß deklariert werden

(Deklarationen sind Anweisungen)

byte b;

long l;

char einZeichen;

boolean warOderFalsch;

int i1, i2;

Page 14: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200814

VariablenZuweisungen und Initialisierungen

• Eine Integer Zahlint i; // Deklaration

i = 37; // Wert zuweisen

• Ein einzelnes Zeichenchar jaZeichen;

jaZeichen = 'J'; // nicht 'j'

Page 15: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200815

Variablen• Die Zuweisung und Initialisierung ist auch in einem

Schritt möglichint i = 37;

char c = 'X';

boolean stimmts = true;

double db = 0.3245;

float myFloat1 = 0.5;

float myFloat2 = 5;

Fehler, da 0.5 als double interpretiert wird!

Richtig: float myFloat1 = 0.5f;

Page 16: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200816

Variablen• Eine (Klassen-)Variable kann überall im

Quellcode deklariert werden

• Konvention: Variablendeklaration nur am Anfang oder am Ende einer Klasse (bessere Lesbarkeit)

• Variablen innerhalb einer Methode müssen vor deren Nutzung deklariert werden!

Page 17: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200817

VariablenTypumwandlung

byte --> short --> int --> long --> float --> double

• Binäre Operationen auf numerischen Werten unterschiedlichen Typs sind möglich und werden intern umgewandelt.

• Bei der Umwandlung in einen kleineren Typ können Informationen verloren gehen.

• Ebenso kann die Umwandlung von long nach float verlustbehaftet sein!

Page 18: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200818

VariablenBeispiel:

float f = 2.5F;

int i = 3;

int j = i * f;//Fehler, da Ergebnis float

float g = i * f; // OK

Page 19: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200819

VariablenExplizite Typumwandlung (casting)

double x = 9.97;

int i;

i=(int)x;

//Informationen gehen verloren

• Gültigkeitsbereich sollte vorher überprüft werden

Wert von i? … 9 oder 10? Antwort: 9

Page 20: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200820

Explizites Umwandeln (Casting)Beispiel: Typwandlung von short nach byte

short s;byte b;…b = (byte)s;

0000000000110001 (16 Bit, Wert entspricht 49) ...

00110001 ( 8 Bit, Wert entspricht 49)

0000000100110001 (16 Bit, Wert entspricht 305) ...

00110001 ( 8 Bit, Wert entspricht 49)

Page 21: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200821

KonstantenKonstanten - einmalige Zuweisung

final double g = 9.81;

• eine weitere Zuweisung ist nicht mehr möglich (z.B. g = 10.03;)

• es gibt globale und lokale Konstanten.

Page 22: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200822

Wrapper-KlassenAlle primitive Datentypen haben eine korrespondierende Klasse.

Z.B. kapselt die Klasse Integer einen int Wert:int a = 5;

Integer intOb = new Integer(a);

siehe API: java.lang.Integer

Page 23: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200823

Operatoren in Java

von rechts nach linksZuweisungsoperatoren= += -= *= /=von rechts nach linksBedingungsoperator?:von links nach rechtsLogisches UND&&von links nach rechtsBitoperator inklusives ODER|von links nach rechtsBitoperator exklusives ODER^von links nach rechtsBitoperator UND&von links nach rechtsGleichheitsoperatoren== !=von links nach rechtsVergleichsoperatoren< <= > >= von links nach rechtsVerschiebeoperatoren<< >> >>>von links nach rechtsAdditionsoperatoren+ -von links nach rechtsMultiplikationsoperatoren* / %

-Unäre Operatoren++ -- + - ~ !AuswertungsreihenfolgeArt der OperatorenOperatorzeichen

• Treten mehrere Operatoren zusammen auf, werden sie in der Reihenfolge ihrer Priorität ausgeführt. ( vgl. mit der Mathematik: „Punkt vor Strich“)

• Die Priorität nimmt in der Tabelle von oben nach unten ab.

Page 24: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200824

Operatoren - Beispiele• bei ganzen Zahlen (byte, short, int, long)

15 / 4 = 3 liefert ganzzahligen Anteil

15 % 2 = 1 liefert den Rest

• Bei Gleitkommazahlen

9.5 / 2 = 4.75 normale Division

• Normale Division erzwingen:

(double)10 / 4 = 2.5

Page 25: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200825

Abkürzungen

x = x+3; x += 3;

• Äquivalent für die anderen Operatoren

x = x / 9; x /= 9;x = x * 9; x *= 9; x = x - 9; x -= 9;x = x % 9; x %= 9;

Page 26: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200826

Inkrement und Dekrement• Inkrementieren

int m = 7;

m++; m hat nun den Wert 8

• Dekrementieren

int m = 7;

m--; m hat nun den Wert 6

Page 27: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200827

OperatorenVorsicht!:

int m = 7;

Präfix:int a = 2 * ++m; // a=16, m=8

oder Postfix:int b = 2 * m++; // b=14, m=8

Page 28: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200828

Funktionen• Für weitere Operationen, die man in der Regel auf einem

Taschenrechner findet, wie z.B.

– log(double x)

– pow(double x, doubel y)

– sqrt(double x)

gibt es die Klasse java.lang.Math, in der diese Funktionen

vorgefertigt sind.

Page 29: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200829

Relationale und bool´sche Operationen(3 == 7) Gleichheit, Ergebnis false

(3 != 7) Ungleichheit, Ergebnis true

(3 >= 7) false

(3 <= 7) true

bool´sche Werte können auch verknüpft werden:(3 == 7) && (4 > 2) logisches UND, Ergebnis false

(3 == 7) || (4 > 2) logisches ODER, Ergebnis true

Page 30: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200830

Bitoperationenkönnen auf die Ganzzahltypen angewendet werden

>> shift right

<< shift left

& AND

| OR

^ XOR

~ NOT

Page 31: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200831

Bitoperationen - Beispieleint foo = 16; //0000000000010000

int intOr = foo | 8; //0000000000011000

//24

int intAnd = foo & 24; //0000000000010000

//16

int schieb = foo << 1; //0000000000100000

//32

Page 32: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200832

Kontrollstrukturen in Java• if

• switch

• while

• for

Page 33: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200833

Bedingungsanweisungen (if)

if (Bedingung) Anweisung1;

if (Bedingung) {Block}

if (Bedingung) Anw1 else Anw2;

if (Bedingung) {Block} else {Block}

• Abkürzung: Bedingung ? Anw1 : Anw2Bsp: (x<y) ? x : y

Page 34: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200834

Mehrfachauswahl (switch)

• Soll eine Variable auf mehrere Werte überprüft werden, dann kann die If-Anweisung unübersichtlich werden.

• Eine switch-Anweisung ist für solche Fälle besser geeignet.

Page 35: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200835

Mehrfachauswahl (switch)int wahl = 3;

switch (wahl)

{

case 1: . . . break;

case 2: . . . break;

case 3: . . . break;

case 4: . . . break;

default: . . . break;

}

Page 36: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200836

Mehrfachauswahl (switch)• Die Variable wahl muß vom Typ

–char

–byte

–short

–int

• Nicht erlaubt sind:–long

–float

–double

–boolean

Page 37: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200837

Unbestimmte Schleifen (while)Nur wenn die Bedingung wahr ist, wird der Block ausgeführt:

while (Bedingung){

Block}

Der Block wird auf jeden Fall einmal durchlaufen:do{

Block}while (Bedingung);

Page 38: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200838

Bestimmte Schleifen (for)Anzahl der Durchläufe muss vorher bekannt sein:

int i;

for (i = 1; i <= 10; i++)

{

System.out.println(i);

}

Page 39: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200839

Bestimmte Schleifen (for)

for (x=0; x !=10; x+=0.01) {

….

}

Page 40: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200840

Übersicht der Klammerarten• () Methodenperson.getName();ma.getGehalt(int jahr);

• {} Blöcke {Anw1 {Anw2;Anw3} Anw4}

• [] Index der FelderneZahl = stapel[3];

Page 41: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

41

Teil 5 - JavaNOCHMAL:Klassen Methoden, Attribute

Page 42: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200842

Noch mal im Detail:Grundlegende Programmstruktur

Ende der Klasse (des ~körpers)}

Die verschiedenen Methoden, welche die eigentliche Funktionalität einer Klasse ergeben.

Methode1 {...}Methode2 {...}

Konstruktor (heißt wie die Klasse, erzeugt das Objekt, hat kein Rückgabewert)

X {...}

KlassenkörperEnthält Variablen, ...

int nummer=0;float zahl;...

Name der Klasseclass X {

Verfügbarmachen anderer Klassen

import ...Sichtbarkeit / Ordnersystempackage ...

Page 43: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200843

KlassenSyntax für eine Klasse

ZugriffsSpezifikator class NameDerKlasse[extends Oberklasse] [implements Schnittstelle]

{

// Attribute/Merkmale der Klasse;

// Konstruktor der Klasse;

// Methoden der Klasse;

}

Page 44: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200844

Zugreifbarkeit auf Methoden und Variablen

public

protected

ohne

private

private – nur innerhalb der Klasse sichtbar und somit zugreifbar.

ohne – nur innerhalb des Pakets, das die Deklaration der Klasse enthält (Standardzugriffsrecht).

protected – zugreifbar von Methoden der eigenen Klasse, der davon abgeleitete Klassen und von Klassen im selben Paket.

public – für Methoden aller Klassen zugreifbar (welche die Klasse importieren).

Zugriffsmodifizierer

Page 45: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200845

KlassenIn einer Datei darf nur eine Klasse public sein.

Konvention : Pro Datei eine Klasse

Page 46: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200846

Klassen, Methoden und VariablenObjekt student1 erzeugen:Student student1 = new Student();

Methode aufrufen und Rückgabewert speichern:int semanzahl = student1.getSemester();

Konstruktor:Student() { … }

Student(int semester) { … }

Page 47: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200847

AttributeSyntax für ein Attribut:

ZugriffsSpezifierer Typ NameDesAttributs

private int eineZahl = 11;

public int nochneZahl; // default=0

Der Typ eines Attributs kann ein einfacher/primitiver Datentyp, ein Feld oder eine Klasse sein.Damit hat man die Möglichkeit, von einem Objekt auf ein anderes zu verweisen.Der Name muss innerhalb des Klassenrumpfes eindeutig sein.

Page 48: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200848

Attributeeinfache/primitive Typen

private int neZahl;

komplexe Typen (auch eigene Klassen)

private Anschrift seineAnschrift;

public Button druckKnopf;

Page 49: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200849

Attribute: Klassenattribut (static)Ein Klassenattribut ist nur für die Klasse gegeben, sein Wert ist unabhängig von den vorhandenen Exemplaren

private static int anzahlKunden;

Konstante: wie Klassenattribut und zusätzlich nicht änderbar

public static final MAX_KUNDEN = 100;

Page 50: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200850

Klassenattribut (static)Mit Hilfe von static kann man Klassenvariablen und Klassenmethoden erzeugen, die für alle Objekte derKlasse gleich sind.

public class Person {…

static int countPerson;public Person() {countPerson++;

}public static int getCountPersonen() {

return countPerson;

} …

Die Variable countPerson ist für alle Instanzen der Klasse Person gleich!

Page 51: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200851

Attributeprivate = Datenkapselung!

nur das Objekt kann auf seine Variablen zugreifen (Black Box).

Empfehlung: Alle Attribute privat

Page 52: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200852

Attributepublic class Kunde

{

// Attribute

private String name;

private Anschrift seineAnschrift;

private static int anzahlKunden;

public static final MAX_KUNDEN = 100;

...

// Methoden

...

}

Page 53: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200853

KonstruktorKonstruktor

• Operation, die ein neues Objekt einer Klasse erzeugt. Der Konstruktor heißt wie die Klasse. Die Syntax ist wie bei Methoden, jedoch ohne Rückgabewert!

public Kunde(){

kundenId = getNewId();}

• versetzt bei Aufruf das Objekt in einen Anfangszustand.

einKunde = new Kunde();

Page 54: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200854

KonstruktorEine Klasse kann mehrere Konstruktoren besitzen (Überladen).

public Mitarbeiter(String n, double g){ name = n;

gehalt = g;}

public Mitarbeiter(){}

Die Parametertypen und deren Anzahl können unterschiedlich sein.

Page 55: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200855

Methoden• Eine Methode/Operation ist eine Funktion, die auf die

internen Daten (Attribute) eines Objekts Zugriff hat.

• Sie kann Botschaften an andere Objekte senden

• Auf alle Objekte einer Klasse sind dieselben Methoden anwendbar

Page 56: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200856

MethodenSyntax der Methoden:

ZugriffsSpezifikator Rückgabetyp NameDerMethode(Parametertyp Parametername, ...)

{// Anweisungen

}

Der Rückgabetyp void bedeutet, dass nichts zurückgegeben wird.public void nixZurueck()

ZugriffsSpezifikator ist optional.

Page 57: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200857

Methoden

Die Signatur einer Methode besteht aus dem Namen

der Operation, den Namen und Typen aller

Parameter, dem Typ des Ergebnistyps und der

Bezeichnung der Ausnahmebehandlung (siehe

nächste Vorlesung).

double getGehalt(String name) // kein -

{ // Semikolon!

}

Page 58: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200858

getter-, setter-MethodenAccessor-Methode

• meldet den Zustand des Objektes

String name = Kunde.getName();

Mutator-Methode• ändert den Zustand eines Objektes

Kunde.setName(„Mueller“);

Page 59: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200859

Beispiel:package mypackage;import java.util.*; /* nicht nötig *//*** Klasse die Studenten darstellen soll. */public class Student {

private int semester;public Student() {} // default Konstruktor optional!

/*** Setzt die Semesterzahl. */public void setSemester(int sem) {

semester=sem;}/*** Gibt die Semesterzahl zurück. */public int getSemester() {

return semester;} ...

}

Page 60: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200860

MethodenCALL BY VALUE

In Java können Methoden die Werte ihrer Parameter nicht ändern, also kein call by reference wie in C:

Zeiger in C++:void swap(int &a,int &b) {

int tmp=a; a=b; b=tmp;

}; void main() {

int a=1, int b=2; swap(a,b); cout<<"a: "<<a<<endl; cout<<"b: "<<b<<endl;

};

Page 61: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200861

MethodenFunktioniert nicht:

static void kundeTauschen(Kunde a, Kunde b)

{

Kunde temp = b; // Objektvariable : erster

b = a; // Buchstabe klein

a = temp;

}

Page 62: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200862

MethodenABER: das funktioniert:

static void kundeTauschen(Kunde a, Kunde b)

{

String name_a = a.getName();

String name_b = b.getName();

a.setName(name_b);

b.setName(name_a);

}

Page 63: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

63

Teil 6 - JavaStringsArraysPakete

Page 64: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200864

StringsZeichenketten (String)

• Folgen von Zeichen String s = "Hallo";

// char 'J' , String "J"

String b = "Du";

System.out.println(s + b + "!!!");

// Ausgabe c:\>HalloDu!!!

Page 65: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200865

Strings• Die Klasse String liefert viele Methoden, um eine

Zeichenkette zu bearbeiten.

int i = s1.length();

// Länge des Strings s1

char ch = s1.charAt(2);// Zeichen des Strings s1 an der Position 2

Page 66: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200866

Strings - Methoden

Weitere Methoden der Klasse String

int compareTo(String anotherString)

String concate(String str)

String toUpperCase()

String trim() //entfernt Leerzeichen

String valueOf(char c)

String replace(char oldChr,char newChr)

• und weitere

Page 67: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200867

Strings - StringTokenizerUm eine Zeichenkette zu analysieren kann die Klasse StringTokenizer verwendet werden.

Constructor SummaryStringTokenizer(String str)

Constructs a string tokenizer for the specified string.

StringTokenizer(String str, String delim) Constructs a string tokenizer for the specified string.

StringTokenizer(String str, String delim, boolean returnDelims) Constructs a string tokenizer for the specified string.

Page 68: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200868

Strings - StringTokenizer

Beispiel

String str ="Dies ist; ein String!";

StringTokenizer stkn;

stkn = new StringTokenizer(str, ";“);

while (stkn.hasMoreTokens())

{

System.out.println(stkn.nextToken());

}

Page 69: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200869

String Vergleich

int a=1, b=1;

String x=“abc“, y=“abc“;

if(a==b) …

if(x==y) …

if(x.equals(y)) …

Page 70: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200870

Felder (Arrays)Felder werden benötigt, um temporäre Listen von primitiven Typen oder Objekten zu verwalten.

z.B.: Eine Liste der Mitarbeiter…

Von jedem Typ lassen sich Felder definieren.

Deklaration:int[] i; // ein Integer-Feld

Mitarbeiter[] m; //Mitarbeiterfeld

Instanzierung:i = new int[10];

m = new Mitarbeiter[100];

Page 71: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200871

ArraysZuweisung

i[0] = 100;

i[1] = 258;

...

i[9] = 300;

int zahl = i[9]; //zahl = 300

int zahl2 = i[10]; // exception!

Numerierung beginnt bei 0!int[] myArray = {1,2}; // alles zusammen

Page 72: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200872

Arrays• Es gibt vorgefertigte Methoden, um Felder zu

kopieren, zu sortieren, auszugeben etc.:

Klasse java.util.Arrays

• Mehrdimensionale Felder:

int[][] i = new int[5][10] /* Matrix */

Page 73: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200873

Arrays• Hinweis: auch unregelmäßige Felder sind möglich

(z.B. Pyramide)

int[][] intFeld = new int[5][];

for (int i=0; i<5; i++)

{

intFeld[i]= new int[i+1];

}

Page 74: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200874

Ansprechbar mit intFeld[3][2]

Arrays

intFeld

0

1

2

3

4

0

0

0

0

0

1

1

1

1

2

2

2

3

3 4

Page 75: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200875

Pakete• Mehrfachverwendung von Klassen• Übersichtlichkeit, zusammengehörige Klassen in

einem Paket

• Namensaufbau wie ein URL nur umgedreht (Vorschlag)

• Importieren aller Klassen eines Paketes mit dem * (Sternchen)

Beispiel:import de.uni-frankfurt.cs.dbis.*;

Page 76: Teil 4 - Javaprg2/SS2008/folien/zicari/java_teil2.pdf · * image exists. When this applet attempts to draw the image on * the screen, the data will be loaded. The graphics primitives

Grundlagen der Programmierung II DBIS - SS200876

Wichtige Paketejava.lang

• einfache Datentypen, Ausnahmebehandlung

java.util• Datum, Liste, Stack, ZIP, Hashtable, Random

java.io• Ein-/Ausgabe, Filesystem

java.math• Bitoperationen