The Java if Statement

The if statement is used to execute a statement or block of statements conditional on some expression being true. The expression to be tested must evaluate to a Boolean value, that is, one that is either true or false. In addition, the expression must and appear in parentheses directly after the keyword "if". The statement or block of to be conditionally executed appears after this. In the following example the expression is (args.length>0).
/*
Example of the if statement, String[] args and of array access.
*/
class  TheJavaifStatement
{

 
public static  void main(String[] args)
  {
   
if (args.length>0)
    {
     
System.out.println("At least one argument was provided it was:");
      System.out.println
(args[0]);
   
}
  }
}

To use this source code cut and paste it into your text editor and save the file as "TheJavaifStatement.java". To compile the program use the javac compiler. This translates the source code into byte code suitable for execution by the java run time environment. To run the program use the java command with the argument TheJavaifStatement and with one or more program arguments of your own choice. So, to compile and run from the command line:
$
$javac TheJavaifStatement.java
$java TheJavaifStatement one two three
At least one argument was provided it was:
one
$java TheJavaifStatement 'one two three'
At least one argument was provided it was:
one two three
$java TheJavaifStatement
$
$
Note
  1. When the program was provided with at least one argument the length of the args array larger than 1 and the program executed the System.out.println methods.
  2. When the program was provided with no arguments the length of the args array was 0 and the program did not execute the System.out.println methods.
  3. To access the first element of the args array the syntax args[0] is used. If we were sure there were at least two elements in the array we could use args[1] to access the second element.
  4. An argument of in quotes is treated as a single argument even if it contains spaces.

The if else Statement

/*
Example of the  if else statements, String[] args and of array access.
*/
class  TheJavaifelseStatements
{

 
public static  void main(String[] args)
  {
   
if (args.length>0)
    {
     
System.out.println("At least one argument was provided it was:");
      System.out.println
(args[0]);
   
}
   
else
   
{
     
System.out.println("No argument was provided");
   
}
  }
}
$
$javac TheJavaifelseStatements.java
$java TheJavaifelseStatements
No argument was provided
$java TheJavaifelseStatements a b c
At least one argument was provided it was:
a
$
$


Previous More Strings in Java Next Loops in Java

Custom Search

Tutorial
Your First Java Program
Primitive data types in Java
Basic arithmetic operations in Java
Using Strings in Java
More Strings in Java
The Java if statement
Loops in Java
The entire content of this site is subject to copyright.