Wednesday, October 21, 2015

If Selection Statements used in JAVA

The selection statements allow to choose the set of instructions for execution depending upon an expression’s truth value. Java provides two types of selection statements: if and switch. In this article we will learn about if selection statement and then next one.

In addition, in certain circumstances ?= operator can be used as an alternative to if statement. The selection statements are also called conditional statements or decision statements.

If Statement

An if statement tests a particular condition ; if the condition evaluates to true, a course of action is followed i.e., a statement or set of statements is executed. Otherwise (if the condition evaluates to false), the course of action is ignored. The syntax of the if statement is as shown below:

If (expression)
statement;

where a statement may consist of a single statement, a compound statement, or nothing (in case of empty statement). The expression must be enclosed in parentheses. If the expression evaluates to true i.e. a nonzero value, the statement is executed, otherwise ignored. Look out following code fragment:

if (ch == ‘’)
spaces++;

This statement will checks whether the character variable ch stores a space or not; if it does, the number of spaces are incremented by one. Next example will clarify some more conditions with if statement:

if (ch == ‘’)
label.setText(“It is a space character”);
if (ch >= ‘0’ && ch <= ‘9’)
label.setText(“It is a digit”);

This will compare a character variable ch. If it stores a space, it flashes a message and if it will be a digit, it flashes another message as specified in above.

No comments:

Post a Comment