1. Conditional ( ?
: )
public class Test {
public static void main(String args[]) {
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "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;
System.out.println( 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 ) {
System.out.print("Nilai x : " + x );
x++;
System.out.print("\n");
}
}
}
4. For Loop
public class Test {
public static void main(String args[]) {
for(int x = 1; x < 10; x = x + 1) {
System.out.print("Nilai x : " + x );
System.out.print("\n");
}
}
}
5. Do While Loop
public class Test {
public static void main(String args[]) {
int x = 1;
do{
System.out.print("Nilai x : " + x );
x++;
System.out.print("\n");
}while( x < 10 );
}
}
6. Simple If
public class Test {
public static void main(String args[]) {
int x = 10;
if( ( x % 2 ) == 0 ){
System.out.println("Genap");
}
}
}
7. If Else
public class Test {
public static void main(String args[]) {
int x = 7;
if( ( x % 2 ) == 0 ){
System.out.println("Genap");
}else{
System.out.println("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 ){
System.out.println("Lulus");
}else{
System.out.println("Lulus bersyarat");
}
}else{
System.out.println("Tidak Lulus");
}
}
}
9. Switch Case
public class Test {
public static void main(String args[]) {
char nilai = 'B';
switch( nilai ){
case 'A' :
System.out.println("Amazing");
break;
case 'B' :
System.out.println("Bagus");
break;
case 'C' :
System.out.println("Coba lagi jangan patah semangat");
break;
default:
System.out.println("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 System.out.println($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 System.out.println($i);
6 }
7 }
9 }
10 }
4. Apa yang dimaksud dengan infinite looping?
5. Kode
1 import java.util.Scanner;
2
3 public class loop2{
4 public static void main(String[] args){
5 Scanner myInput = new Scanner(System.in);
6 System.out.println("Berapa kali perulangan?");
7
8 int jumlahLoop = myInput.nextInt();
9
10 System.out.println("Berikut ini perulangannya");
11 for(int $i = 1; $i <= jumlahLoop; $i++){
12 System.out.println($i);
13 }
14 }
15 }
Jelaskan line of code:
a. 1
b. 5
c. 8
d. 11-13