The Conditional Operator - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript The Conditional Operator - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Monday, March 18, 2019

The Conditional Operator

The Conditional Operator


üJava has a conditional operator that evaluates a boolean condition that determines which of two other expressions is evaluated
üThe result of the chosen expression is the result of the entire conditional operator
üIts syntax is:
ü  condition ? expression1 : expression2
üIf the condition is true, expression1 is evaluated;  if it is false, expression2 is evaluated.
The Conditional Operator

üThe conditional operator is similar to an if-else statement, except that it forms an expression that returns a value
üFor example:
ü  larger = ((num1 > num2) ? num1 : num2);
ü    if (num1 > num2)
  larger = num1;
else
  larger = num2;
üThe conditional operator is ternary because it requires three operands.
The Conditional Operator
üAnother example:
   System.out.println ("Your change is " + count +
           ((count == 1) ? "Dime" : "Dimes"));
If count equals 1, then "Dime" is printed
If count is anything other than 1, then "Dimes" is printed.
Repetition Statements

üRepetition statements allow us to execute a statement multiple times

üOften they are referred to as loops
üLike conditional statements, they are controlled by boolean expressions
üJava has three kinds of repetition statements:
üthe while loop
üthe do loop
üthe for loop
üThe programmer should choose the right kind of loop for the situation

No comments:

Post a Comment

Post Top Ad