1 Instrukcje sterujące
W języku Java przyjęto wszystkie instrukcje sterujące języka C/C++
If-else
if(Boolean-expression) statement
if(Boolean-expression) statement else
statement
return
• Pozwala określić wartość zwracaną przez metodę (wyjątek typ void)
• Wymusza natychmiastowy powrót
Iteracje
while(Boolean-expression) statement
do statement
while(Boolean-expression);
for(initialization; Boolean-expression; step) statement
for(inti = 0, j = 1; i < 10 && j != 11; i++, j++) // body of for loop
W części inicjującej i wyznaczającej krok iteracji wyraŜenia sterującego pętli for moŜe wystąpić szereg oddzielonych przecinkami instrukcji, które są wykonywane sekwencyjnie
2 break i continue
for(inti = 0; i < 100; i++) { if(i == 74)break; // Out of for loop if(i % 9 != 0)continue; // Next iteration System.out.println(i);
} inti = 0;
// An "infinite loop":
while(true) { i++;intj = i * 27;
if(j == 1269)break; // Out of loop if(i % 10 != 0)continue; // Top of loop System.out.println(i);
}
Jakie będą wydruki?
goto
goto nie jest w Javie uŜywane, chociaŜ słowo jest zarezerwowane
label1:
outer-iteration { inner-iteration { //...
break; // 1 //...
continue; // 2 //...
continuelabel1; // 3 //...
breaklabel1; // 4 }
}
Kiedy uŜywamy etykiety w Javie
1. A plain continue goes to the top of the innermost loop and continues.
2. A labeled continue goes to the label and reenters the loop right after that label.
3. A break “drops out of the bottom” of the loop.
4. A labeled break drops out of the bottom of the end of the loop denoted by the label.
switch
switch(integral-selector) {
caseintegral-value1 : statement;break;
caseintegral-value2 : statement;break;
caseintegral-value3 : statement;break;
caseintegral-value4 : statement;break;
caseintegral-value5 : statement;break;
// ...
default: statement;
}
3 Łańcuchy znakowe
Klasa String
Strings are constant; their values cannot be changed after they are created, zmieniany moŜe być obiekt klasy
StringBuffer
Konkatenacja
• Specjalne traktowanie operatora „+”
String cde = "cde";
System.out.println("abc" + cde);
String aGirlName, aName, zz;
aGirlName = “Alice” ;
aName = aGirlName.substring(0, length());
zz = aName ;
Porównanie
• aGirlName == aName true or false ?
• zz == aName true or false ?
• aGirlName == zz true or false ?
• Hint: always use equals()
Metody
• public int compareTo(StringanotherString)
• public boolean equals(ObjectanObject)
• public char charAt(int index)
• public Stringconcat(Stringstr)
• public int indexOf(int ch)
• public int length()
• public Stringreplace(char oldChar, char newChar)
4 Metody c.d.
• public boolean startsWith(Stringprefix)
• public Stringsubstring(int beginIndex)
• public Stringsubstring(int beginIndex, int endIndex)
• public StringtoLowerCase()
• public StringtoUpperCase(Localelocale)
• public Stringtrim()
• public boolean endsWith(Stringsuffix)