5. If, Then, Else

Home » Java Quick Start » Quick Start Tutorial » 5. If, Then, Else


Probably one of the most used functions in programming... Comparing different values, to perform specific actions, which is done with if/then/else.

The line starting with "//" is a comment line, so Java ignores it. By changing the testValue to 2, 3, or something else on line 4, you will see the text output of the several if blocks.

The second part of this example script shows how to compare string-values. Because a String is an object, you can only correctly compare the content (= text) of the String by using the equals() or equalsIgnoreCase() methods.

The output of this example looks like this:

$ java IfThenElse.java

The value is 1 or smaller
Are string1 and string2 equal? true
Are string1 and string3 equal? false
Are string1 and string3 equal ignoring the case? true
string1 and string3 are equal ignoring the case

Subscribe to foojay updates:

Copied to the clipboard