Decision Structures: Conditional Statements

The syntax of conditional statements in Java is

If (condition) {

block of code executed when condition is true
}
ELSE {
block of code executed when condition is false
}

The following application will compare two variables, x and y, and print out a statement declaring which is larger.
The variables are initialized at the start of the program. Java allows you to declare and initialize variables simultaneously.

 

Copy the following code into a text editor and
save it as conditional.java.

class conditional {
public static void main (String args[]){
  int x = 35000;
  int y = 100000;

      System.out.println("x ="+ x );
      System.out.println("y ="+ y );

     if (x < y)
        System.out.println("x is smaller !");
     else
         System.out.println("y is smaller !");
  }
}

    
 


Lines 3 & 4 declare x and y as integer variables
and initialize x to 3500 & y to 100000

Line 5 & 6 print out the values for x & y.

Line 7 sets up the condition
if x is less than y we print x is smaller

Otherwise print y is smaller

If you would like to see the code for this, click here and, if you like, copy the contents of the screen that loads in your browser , paste it in a text editor and save it in a file: filename.java.

After compiling and running this program the output should be

 

x =35000
y =100000
x is smaller !

x and y values are set within the program. If we wanted to compare other values we would need to set them in the source code and then recompile.

We can also write the program to accept command line parameters.

Java programs that contain the following line will accept any number of string arguments as command line parameters.

public static void main (String args[]){

args[0] args[1] args[2] .... will hold the command line arguments as strings.

The next program will accept two arguments and perform the same comparison.

Conditional Statements With Arguments