The if-then Statement in Java
By: Ivan Lim Printer Friendly Format
if-then
statement is the most basic of all the control flow
statements. It tells your program to execute a certain section of code only
if a particular test evaluates to true
. For example, the Bicycle
class could allow the brakes to decrease the bicycle's speed only if the
bicycle is already in motion. One possible implementation of the applyBrakes
method could be as follows:
If this test evaluates tovoid applyBrakes(){ if (isMoving){ // the "if" clause: bicycle must moving currentSpeed--; // the "then" clause: decrease current speed } }
false
(meaning that the bicycle is not in
motion), control jumps to the end of the if-then
statement.
In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:
Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.void applyBrakes(){ if (isMoving) currentSpeed--; // same as above, but without braces }
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java