3.1.1 if Statement in Java

The if construct is used if we wish to execute a statement only if a condition is true. The basic format of the if statement is

if (condition)
{
one or more statements to be executed if condition is true;
}

The following code fragment illustrates the if statement:

public static void main(String[] args)
{
if (args.length == 1)
{
System.out.println(''Single argument = " + args[0] + " supplied");
}
System.out.println("no of args = " + args.length);
}



Note there is no then component in the if clause in Java. The relational equality operator
== is used in the statement

if (args.length == 1)



If only one statement is executed when the condition is true, then the enclosing braces are optional. The preceding code could
be rewritten as follows:


public static void main(String[] args)
{
if (args.length == 1)
System.out.println(''Single argument = " + args[0] + " supplied");
System.out.println("no of args = " + args.length);
}



However, it is good practice to always use braces even if a single statement follows the if condition. Otherwise, we might forget to add braces should a second embedded statement be subsequently added.

No comments:

Post a Comment