Java provides selection statements where you can select various courses of action.
For example:
if (radium < 0) { System.out.println("Incorrect input"); } else { area = radius * radius * 3.14159 System.out.println("Area is " + area); }
Selection statements use conditions that are Boolean expressions, ie. true or false. Boolean declares data type variable with the value either true or false.
There are six relational operators:
Boolean variable holds boolean value which is either true or false (true and false are also reserved words). Here is an example.
import java.util.Scanner; public class AdditionQuiz { public static void main(String[] args) { int number1 = (int)(System.currentTimeMillis() % 10); int number2 = (int)(System.currentTimeMillis() / 10 % 10); // Create a Scanner Scanner input = new Scanner(System.in); System.out.print( "What is " + number1 + " + " + number2 + "? "); int answer = input.nextInt(); System.out.println( number1 + " + " + number2 + " = " + answer + " is " + (number1 + number2 == answer)); } }
Check Point Questions:
3.1 List six relational operators:
3.2 Assuming that x is 1, show the result of the following Boolean expressions:
3.3 Can the following conversions involving casting be allowed? Write a test program to verify your answer
boolean b = true; i = (int)b; int i = 1; boolean b = (boolean)i;
Java has several selection statements:
The following statement:
if (i > 0) { System.out.printlin("i is positive"); }
is the same as (the brace has been omitted):
if (i > 0) System.out.printlin("i is positive");
Check Point Questions:
3.4 Write an if statement that assigns 1 to x if y is greater than 0.
import java.util.Scanner; public class Assign1toX { public static void main(String[] args) { int x = 0; Scanner input = new Scanner(System.in); System.out.print("Enter a y value"); int y = input.nextInt(); if (y > 0) { x += 1; System.out.println("x is " + x); } } }
3.5 Write an if statement that increases pay by 3% if score is > 90.
import java.util.Scanner; /* * * @author Haresh Vaswani * @date 10/16/2021 */ public class IncreasePayby3 { public static void main(String[] args) { double pay = 1000; Scanner input = new Scanner(System.in); System.out.print("Enter score: "); int score = input.nextInt(); if (score > 90) { pay *= 1.03; System.out.println("pay increased by " + pay); } } }
Two-way if-else statements performs a function when the condition is false. Unlike the one-way if statement which performs function when the statement is true.
import java.util.Scanner; /* * * @author Haresh Vaswani * @date 10/16/2021 */ public class IncreasePayby3 { public static void main(String[] args) { double pay = 1000; Scanner input = new Scanner(System.in); System.out.print("Enter score: "); int score = input.nextInt(); if (score > 90) { pay *= 1.03; System.out.println("pay increased by " + pay); } else { pay *= 1.01; System.out.println("pay increased by " + pay); } } }