1. Conditional ( ?
: )
public class Test {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
[Link]( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
[Link]( "Value of b is : " + b );
}
}
Hasil:
Value of b is : 30
Value of b is : 20
Instance Of Operator
2. Instance Of
public class Test {
public static void main(String args[]) {
String name = "James";
boolean result = name instanceof String;
[Link]( result );
}
}
Loop / Perulangan
Pernyataan loop memungkinkan kita untuk mengeksekusi pernyataan atau kelompok pernyataan
beberapa kali.
3. While Loop
public class Test {
public static void main(String args[]) {
int x = 1;
while( x < 10 ) {
[Link]("Nilai x : " + x );
x++;
[Link]("\n");
}
}
}
4. For Loop
public class Test {
public static void main(String args[]) {
for(int x = 1; x < 10; x = x + 1) {
[Link]("Nilai x : " + x );
[Link]("\n");
}
}
}
5. Do While Loop
public class Test {
public static void main(String args[]) {
int x = 1;
do{
[Link]("Nilai x : " + x );
x++;
[Link]("\n");
}while( x < 10 );
}
}
6. Simple If
public class Test {
public static void main(String args[]) {
int x = 10;
if( ( x % 2 ) == 0 ){
[Link]("Genap");
}
}
}
7. If Else
public class Test {
public static void main(String args[]) {
int x = 7;
if( ( x % 2 ) == 0 ){
[Link]("Genap");
}else{
[Link]("Ganjil");
}
}
}
8. Nested If
public class Test {
public static void main(String args[]) {
int nilai = 95;
int absen = 100;
if( nilai >= 60 ){
if( absen >= 70 ){
[Link]("Lulus");
}else{
[Link]("Lulus bersyarat");
}
}else{
[Link]("Tidak Lulus");
}
}
}
9. Switch Case
public class Test {
public static void main(String args[]) {
char nilai = 'B';
switch( nilai ){
case 'A' :
[Link]("Amazing");
break;
case 'B' :
[Link]("Bagus");
break;
case 'C' :
[Link]("Coba lagi jangan patah semangat");
break;
default:
[Link]("Tidak terdefinisi");
break;
}
}
}
Latihan
1. Apa output dari kode ini?
1 public class loop1{
2 public static void main(String[] args){
3 for( int $i = 1; $i <= 10; $i++ ){
4 [Link]($i);
5 }
6 }
7 }
2. Ganti kode soal pertama tapi menggunakan:
a. While
b. Do While
3. Apa output dari kode ini?
1 public class loop1{
2 public static void main(String[] args){
3 for( int $i = 1; $i <= 50; $i++ ){
4 if( $i % 5 == 0 ){
5 [Link]($i);
6 }
7 }
9 }
10 }
4. Apa yang dimaksud dengan infinite looping?
5. Kode
1 import [Link];
2
3 public class loop2{
4 public static void main(String[] args){
5 Scanner myInput = new Scanner([Link]);
6 [Link]("Berapa kali perulangan?");
7
8 int jumlahLoop = [Link]();
9
10 [Link]("Berikut ini perulangannya");
11 for(int $i = 1; $i <= jumlahLoop; $i++){
12 [Link]($i);
13 }
14 }
15 }
Jelaskan line of code:
a. 1
b. 5
c. 8
d. 11-13