Java - for, while do...while

Java

  • while
  • do…while
  • for

Java5 for


while

while

while( ) { // }

true

Test.java

public class Test { public static void main(String[] args) { int x = 10; while( x < 20 ) { System.out.print("value of x : " + x ); x++; System.out.print("\n"); } } }

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

dowhile

while

dowhile while dowhile

do {
       //
}while();

true false

Test.java

public class Test { public static void main(String[] args){ int x = 10; do{ System.out.print("value of x : " + x ); x++; System.out.print("\n"); }while( x < 20 ); } }

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

for

while do...while Java for

for

for(; ; ) { // }

for

  • truefalse

Test.java

public class Test { public static void main(String[] args) { for(int x = 10; x < 20; x = x+1) { System.out.print("value of x : " + x ); System.out.print("\n"); } } }

value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

Java for

Java5 for

Java for :

for( : ) { // }

Test.java

public class Test { public static void main(String[] args){ int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ){ System.out.print( x ); System.out.print(","); } System.out.print("\n"); String [] names ={"James", "Larry", "Tom", "Lacy"}; for( String name : names ) { System.out.print( name ); System.out.print(","); } } }

10,20,30,40,50,
James,Larry,Tom,Lacy,

break

break switch

break

break

break;

Test.java

public class Test { public static void main(String[] args) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { // x 30 if( x == 30 ) { break; } System.out.print( x ); System.out.print("\n"); } } }

10
20

continue

continue

for continue

while dowhile

continue

continue;

Test.java

public class Test { public static void main(String[] args) { int [] numbers = {10, 20, 30, 40, 50}; for(int x : numbers ) { if( x == 30 ) { continue; } System.out.print( x ); System.out.print("\n"); } } }

10
20
40
50