if and if...else(one way selection)

The following is a simple Java application program that uses if and if…else(one way selection). There are only two logical values, true and false, they are extremely useful because they permit programs to incorporate decision making that alters the processing flow. . I will be using the JCreator IDE in developing the program.
  1. if (expression)
  2. statement
Note the elements of this syntax. It begins with the reserved word if, followed by an expression contained within parentheses, followed by a statement. The expression is sometimes called the decision maker because it decides whether to execute the statement that follows it. The expression is logical expression, if the value of the expression is true, the statement executes, if the value is false, the statement does not execute and the computer goes on to the next statement in the program. Here is the sample program that uses if and if…else (one way selection) To start in this tutorial, first open the JCreator IDE, click new and paste the following code.
  1. import javax.swing.JOptionPane;
  2.  
  3. public class AbsoluteValue
  4.  
  5. {
  6. public static void main(String[] args)
  7. {
  8. int number;
  9. int temp;
  10. String numString;
  11.  
  12. numString = JOptionPane.showInputDialog("Enter an integer:");
  13.  
  14. number = Integer.parseInt(numString);
  15. temp=number;
  16.  
  17. if(number < 0)
  18. number = -number;
  19. JOptionPane.showMessageDialog(null, "The Absolute value of " + temp
  20. + " is " + number,
  21. "Absolute Value",
  22. JOptionPane.INFORMATION_MESSAGE);
  23.  
  24. System.exit(0);
  25. }
  26. }
Sample run: sample1sample2sample3 The statement numString = JOptionPane.showInputDialog("Enter an integer:"); displays the input dialog box and prompts the user to enter an integer. The entered number is stored as a string numString. The statement number = Integer.parseInt(numString); uses the method parseInt of the class Integer, converts the value of numString into the number and stores the number in the variable number. The statement temp=number; copies the value of number into temp. The statement if(number < 0) checks whether number is negative. If the number is negative, the statementnumber = -number;changes number to positive number. The statement
  1. JOptionPane.showMessageDialog(null, "The Absolute value of " + temp
  2. + " is " + number,
  3. "Absolute Value",
  4. JOptionPane.INFORMATION_MESSAGE);
displays the message dialog box and shows the original number, stored in temp, and the absolute value of the number stored in number. The statement System.exit(0); terminates the program.

Add new comment