Basic Conditionals in Java

In this tutorial, we will cover how to use conditional statements. Conditional statements work by executing code if a certain statement is true. There is also the option of running a different set of code if the conditional is not true. Conditionals use the "if" statement, and "else" is optional. Have a look at the code below, taking note of the comments.
  1. import java.util.Scanner;
  2.  
  3. public class conditionals
  4. {
  5.  
  6.         public static void main(String[] args)
  7.         {
  8.  
  9.                 Scanner input = new Scanner(System.in); //creation of scanner to accept input
  10.  
  11.                 System.out.print("Enter a number: ");
  12.  
  13.                 double userInput = input.nextDouble(); //declares a variable, userInput, and gives it the value that the user enters
  14.  
  15.                 calc(userInput); //calls calc method and passes it the value of userInput
  16.  
  17.         }
  18.  
  19.         public static void calc(double x) //assigns value passed to this method as x
  20.         {
  21.  
  22.                 double evenCheck = x % 2; //checks for a remainder when x is divided by 2
  23.  
  24.                 if (evenCheck == 0) //checks if the remainder is 0
  25.  
  26.                         System.out.println("Your number is even."); //output
  27.                
  28.                 else //if conditional is not satisfied (remainder not 0)
  29.  
  30.                         System.out.println("Your number is odd."); //output
  31.        
  32.         }
  33. }
The % operator is called a modulo. This is useful for finding remainders in division. The purpose of it here is to check for the remainder when the number is divided by 2. If the remainder is 0, the original number is even. Anything else, and the number is odd. Conditionals are very common in Java. The uses for them are endless. While the example used above is just a simple conditional, others can be quite complicated, dealing with nested if statements (one only executes if another is satisfied) and else-if statements (one only executes if the other is not satisfied). Questions? Please let me know in the comments below.

Add new comment