Skip to content
singhalmanu9 edited this page Dec 9, 2014 · 5 revisions

If and Else

When your program needs to make a decision, use an if statement. The form of the if statement follows this generic pattern: if(whatever your condition is){stuff to do if the condition is true}. Try it out; type

if(1 == 1){

System.out.println("If is working!");

}

and run the resulting program. You will see that If is working!

Else

Else is the default condition if the conditional is false. For example,

if(1 == 2){

System.out.println("Something is wrong...");

}

else{ // no conditional here

System.out.println("else is working too!");

}

Running this program will show you that else is working too! Note that else does not require a conditional statement; in fact, the compiler will be very unhappy when you try to put the conditional there.

For Loops

When you want something to happen over and over again a number of times, you can use a loop instead of typing it over and over. For example, say you want to print out all the numbers between 1 and 100. Instead of writing 100 System.out.println statements, you can write

for(int i = 1; i <= 100; i ++){

System.out.println(i);

}

These three lines give the same result as typing the 100 print statements. For loops follow the pattern: 'for(initialize whatever you are iterating; the ending statement; how much to iterate by){/stuff you want to iterate/}`

Clone this wiki locally