If/Else Statement Syntax

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which of the following is the correct syntax for a basic if statement in Java?

  • if (boolean-expression) { statement; } (correct)
  • if {boolean-expression} (statement;)
  • if (boolean-expression) then { statement; }
  • if boolean-expression then statement;

In a Java if / else statement, what happens if the boolean-expression in the if condition is false?

  • The program throws an exception.
  • The code block within the `else` statement is executed. (correct)
  • The program skips the entire `if / else` statement.
  • The code block within the `if` statement is executed.

Which of the following code snippets demonstrates the preferred style for handling a condition where you want to execute code only when x is not equal to 0?

  • if (x == 0) { flag = false; } else { flag = true; }
  • if (x == 0) { // do nothing } else { flag = true; }
  • else { if (x != 0) { flag = true; }}
  • if (x != 0) { flag = true; } (correct)

Consider the code: if (!("Yes".equalsIgnoreCase(answer) || "Y".equalsIgnoreCase(answer))) { flag = true; }. Under what condition will flag be set to true?

<p>When <code>answer</code> is neither &quot;Yes&quot; nor &quot;Y&quot; (case-insensitive). (C)</p> Signup and view all the answers

What is a nested if statement?

<p>An <code>if</code> statement that is inside another <code>if</code> statement or <code>else if</code> block. (D)</p> Signup and view all the answers

Which of the following demonstrates the preferred way to structure nested if statements when checking multiple exclusive conditions?

<p>if (x &lt; 20) { // some statements } else if (x &lt; 40) { // some other statements } else { // still other statements } (A)</p> Signup and view all the answers

In the provided speeding fine example, if speedLimit is 65 and vehSpeed is 70, what will be the value of diff?

<p>5 (A)</p> Signup and view all the answers

Based on the speeding fine example, if diff is 25, what will be the fine?

<p>100 (D)</p> Signup and view all the answers

In Java, which operator has the highest precedence among the following: <, >=, &&, ||?

<p>&lt; (C)</p> Signup and view all the answers

According to De Morgan's Laws, which expression is equivalent to !((a == 0) || (b == 0))?

<p>(a != 0) &amp;&amp; (b != 0) (B)</p> Signup and view all the answers

Which of the following years is considered a leap year according to the provided information?

<p>2000 (C)</p> Signup and view all the answers

What is the correct condition to determine if a year is a leap year?

<p>Divisible by 4, except for years divisible by 100 unless also divisible by 400. (B)</p> Signup and view all the answers

Why is it important to check if a String variable is not null before calling .equals() or .equalsIgnoreCase() on it?

<p>To prevent a NullPointerException at runtime. (D)</p> Signup and view all the answers

In the context of String comparisons in Java, what is the difference between .equals() and .equalsIgnoreCase()?

<p><code>.equals()</code> is case-sensitive, while <code>.equalsIgnoreCase()</code> ignores case. (C)</p> Signup and view all the answers

In the coin flip example, what determines whether the coin is assigned "heads" or "tails"?

<p>A random number generated by <code>Math.random()</code>. If it's greater than 0.5, it's &quot;heads&quot;; otherwise, it's &quot;tails&quot;. (B)</p> Signup and view all the answers

In the coin flip example, what determines whether the user wins or loses?

<p>Whether the user's input (heads or tails) matches the randomly determined coin flip. (B)</p> Signup and view all the answers

In the Rock, Paper, Scissors example, how is the computer's pick determined?

<p>Using <code>Math.random()</code> to generate a number between 1 and 3, corresponding to Rock, Paper, or Scissors. (B)</p> Signup and view all the answers

In the Rock, Paper, Scissors example, what happens if the user enters an invalid choice?

<p>The program displays an error message indicating the choice is not valid. (A)</p> Signup and view all the answers

What is the purpose of the break statement in a Java switch statement?

<p>To skip the rest of the cases in the <code>switch</code> statement once a match is found. (A)</p> Signup and view all the answers

What happens if a default case is not included in a switch statement and none of the case values match the switch-expression?

<p>The <code>switch</code> statement is skipped, and execution continues with the next statement after the <code>switch</code> block. (C)</p> Signup and view all the answers

In the Switch Statement Example 1, what will be the output if dayOfWeek is equal to 4?

<p>Thursday (B)</p> Signup and view all the answers

In Switch Statement Example 2, what will be the output if the current day is Saturday?

<p>Weekend restaurant hours are 10 AM - 9 PM (C)</p> Signup and view all the answers

In the Switch Statement Example 3, what happens if the user enters " Yes " (with leading and trailing spaces)?

<p>You said 'yes' (B)</p> Signup and view all the answers

Which of the following best describes the purpose of an if statement?

<p>To execute a block of code only if a specified condition is true. (A)</p> Signup and view all the answers

What is the role of the else block in an if / else statement?

<p>To specify the code to be executed if the condition in the <code>if</code> statement is false. (D)</p> Signup and view all the answers

Why is proper style important when using if / else statements?

<p>It makes the code easier to read and understand. (A)</p> Signup and view all the answers

In a nested if structure, how are the conditions evaluated?

<p>The outer <code>if</code> condition is evaluated first, and the inner <code>if</code> conditions are evaluated only if the outer condition is true. (C)</p> Signup and view all the answers

What is the purpose of relational operators in Java?

<p>To compare two values and determine the relationship between them. (C)</p> Signup and view all the answers

In Java, what is the difference between the && and || operators?

<p><code>&amp;&amp;</code> is the logical AND operator, requiring both conditions to be true, while <code>||</code> is the logical OR operator, requiring at least one condition to be true. (C)</p> Signup and view all the answers

What is the result of the expression true && false in Java?

<p>false (D)</p> Signup and view all the answers

According to the provided leap year logic, what is the primary reason why the year 2100 is not a leap year?

<p>It is divisible by 100 but not by 400. (D)</p> Signup and view all the answers

In the context of the String equals() method, what is being compared?

<p>The content of the strings, character by character. (A)</p> Signup and view all the answers

Why is it important to use equalsIgnoreCase() when comparing strings where case should not matter?

<p>It ensures that the comparison is not affected by the case of the characters. (D)</p> Signup and view all the answers

In the coin flip example, if Math.random() returned 0.7, what would be the value of the coin variable?

<p>heads (C)</p> Signup and view all the answers

In the provided Rock, Paper, Scissors game, what is the outcome if the user chooses "rock" and the computer also picks "rock"?

<p>It's a tie. (A)</p> Signup and view all the answers

What is the main purpose of the switch statement in Java?

<p>To select one of several code blocks to execute based on the value of a single variable or expression. (A)</p> Signup and view all the answers

Flashcards

What is an 'if' statement?

Executes code based on a boolean condition.

What is an 'else' statement?

The section of code executed when the 'if' condition is false.

What is a 'nested if' statement?

Used for multiple conditions by chaining 'if-else' statements.

What does the '==' operator do?

Checks for equality. Returns true if operands are equal.

Signup and view all the flashcards

What does the '!=' operator do?

Checks for inequality. Returns true if operands are not equal.

Signup and view all the flashcards

What does the '&&' operator do?

Returns true only if both operands are true.

Signup and view all the flashcards

What does the '||' operator do?

Returns true if either operand is true.

Signup and view all the flashcards

What is De Morgan's Law (1)?

NOT (P OR Q) is equivalent to (NOT P) AND (NOT Q).

Signup and view all the flashcards

What is De Morgan's Law (2)?

NOT (P AND Q) is equivalent to (NOT P) OR (NOT Q).

Signup and view all the flashcards

What is a 'switch' statement?

Tests a variable against multiple cases.

Signup and view all the flashcards

What is a 'case' in a switch?

Indicates a specific value to match in a 'switch' statement.

Signup and view all the flashcards

What does 'break;' do in switch?

The keyword to exit a switch statement.

Signup and view all the flashcards

What is the 'default' case?

The action when none of the cases match.

Signup and view all the flashcards

Study Notes

If Statement Syntax

  • The basic structure of an if statement involves a boolean expression within parentheses.
  • If the expression evaluates to true, the code block within the curly braces is executed.
  • If the expression is false, the block is skipped.
  • An example shows how to calculate and display the cost of an item based on a boolean flag that indicates in-state status.
  • If inStateFlag is equal to 1, the cost is updated to include tax, and the item cost is printed.

If/Else Statement Syntax

  • An if/else statement provides an alternative code block to execute when the boolean expression in the if statement is false.
  • If the boolean expression evaluates to true, the code block directly following the if condition is executed.
  • Otherwise, the code block following the else keyword is executed.

If/Else Statement Example

  • An if/else statement determines if a number is even or odd based on whether the value is divisible by 2.
  • If the remainder of number divided by 2 is 0, the program outputs that the number is even using System.out.println.
  • Otherwise, the program outputs that the number is odd.

If/Else Statement Style - 1

  • Avoid using an if/else statement where the if block does nothing and the else block performs an action.
  • Instead, negate the condition in the if statement to directly execute the desired action when the condition is met.
  • It streamlines the code and makes it more readable.

If/Else Statement Style - 2

  • Refrain from using an if/else structure where the if condition checks for specific string values.
  • The code block does nothing, and the else block executes an action.
  • A better approach is to use the "not" operator (!) and include the desired action within the if block when the condition is not met, improving readability and efficiency.

Nested If Statement

  • A nested if statement involves one or more if statements inside another if statement.
  • This allows for multiple conditions to be checked in sequence, executing different code blocks based on the boolean expression.
  • Each else if condition provides an additional condition to check if the previous if or else if conditions were not met.
  • The final else block is executed if none of the previous conditions were true.

Nested If Statement Style - 1

  • Avoid nesting multiple layers of if/else statements.
  • The resulting code is harder to read and understand.
  • A cleaner and more maintainable solution is to use else if statements to handle multiple conditions at the same level.

Nested If Statement Style - 2

  • Multiple conditions can be checked at the same level using else if statements.
  • The code becomes more readable and easier to maintain, avoiding deep nesting.
  • The else block handles any cases that do not match the specified conditions.

Nested If Statement Example

  • A complete example shows how to use nested if statements to compute a speeding fine based on the difference between a vehicle's speed and the speed limit.
  • The program first prompts the user to enter the speed limit and the vehicle speed and calculates the difference.
  • Different fine amounts are assigned based on the speed difference.
  • If the difference is less than or equal to 0, the fine is 0.
  • If the difference is less than 10, the fine is 25.
  • Further ranges of speed difference result in fines of 50, 100, or 250.
  • Differences beyond that incur a fine of 500.
  • The program outputs "Driver was not speeding" if the fine is zero or displays a message stating the fine amount.
  • The example demonstrates the program setting a speed limit of 65 and a vehicle speed of 84.
  • Because the vehicle exceeds the limit by 19 mph, the driver receives a $50 fine.

Equality, Relational, and Conditional Operators

  • The <, <= , >, >= group has the highest precedence in Java. These operators are used for comparing numerical values.
  • An example includes less than, less than or equal to, greater than, and greater than or equal to.
  • == and != test for equality and inequality, respectively, and have the second-highest precedence.
  • The && operator is a conditional AND, and the || operator is a conditional OR.
  • The conditional AND has a higher precedence than the conditional OR.

Truth Tables: AND, OR Operators

  • The AND (&&) operator returns true only if both operands are true.
  • The OR (||) operator returns true if either operand is true.

De Morgan's Laws

  • De Morgan's Laws provide rules to transform logical expressions involving negations, ANDs, and ORs.
  • The first law states: NOT (P OR Q) is equivalent to (NOT P) AND (NOT Q).
  • The second law states: NOT (P AND Q) is equivalent to (NOT P) OR (NOT Q).
  • An example shows how to rewrite an if statement using De Morgan's Laws.
  • The condition !((a == 0) || (b == 0)) is equivalent to ((a!=0) && (b!=0)).

Leap Year Example

  • A year is a leap year if it is divisible by four.
  • There is an exception for years divisible by 100 but not by 400.
  • 2017is not a leap year, 2016 and 2000 are leap years, and 2100 is not a leap year.
  • The leap year calculator prompts the user to enter a year.
  • The code checks if the year satisfies the leap year conditions.
  • A nested if statement determines whether the year is divisible by 4 and either not divisible by 100 or divisible by 400.
  • A message indicates whether the year is a leap year or not.
  • For an input of 1984, the output is "The year 1984 is a leap year".
  • For an input of 2000, the output is "The year 2000 is a leap year".
  • For an input of 2017, the output is "The year 2017 is not a leap year".
  • For an input of 2100, the output is "The year 2100 is not a leap year".

Relational Operators: Strings

  • To compare a String variable named mystr with a literal such as "Yes", you can use .equals() or .equalsIgnoreCase().
  • The first is case-sensitive, while the second ignores case.
  • To compare a String variable mystr with another String variable otherstr.
  • It's important to first check if mystr is not null to avoid run-time errors.
  • If the mystr variable has not been initialized, it will be null.

String Relational Operators Continued

  • The ! is the NOT operator.
  • if (! “Yes”.equals(mystr)) checks if mystr is NOT equal to “Yes”.
  • if (! "Yes".equalsIgnoreCase(mystr)) checks if mystr is NOT equal to "Yes", ignoring case.

Relational Operators: Strings - Example

  • Multiple string relational operators are presented in an example using else-if statements that use .equalsIgnoreCase() and the logical OR operator.
  • It checks conditions for string values, such as "yes", "y", "true", "t" for confirmation.
  • The code also checks "no", "n", "false", and "f" for negation.
  • If there is no match, it defaults to printing nothing.

Coin Flip Example

  • A coin flip program simulates a coin toss and lets the user guess heads or tails.
  • After initializing variables and the scanner, it randomly selects either "heads" or "tails".
  • The system prints, "I flipped a coin."
  • The user is prompted to guess heads or tails.
  • The guess the user entered is stored in the choice variable.
  • The game outputs "You win" if the user's choice matches the coin result and "You lose" if they do not match.

Rock, Paper, Scissors Game Example

  • A rock, paper, scissors game simulates a game against the computer.
  • The program asks the user to enter a pick.
  • The computer generates a random integer to decide if it will pick rock, paper, or scissors.
  • The user input and computer's choice are changed to lowercase.
  • Conditional statements are executed to print the game's outcome.
  • The user will win, lose, or tie with the computer.

Java Switch Statement

  • A java switch statement tests a variable or expression for one of several possible matching values.
  • switch (switch-expression)
  • The switch-expression is most often an integer, character, or enumerated type.

Switch Statement Example 1

  • The given switch statement example outputs the day of the week.
  • The ISO-8601 standard assigns Monday with the value 1 and Sunday with the value 7.

Switch Statement Example 2

  • The given switch statement provides restaurant hours based on the day of the week.
  • Monday through Friday restaurant hours are noon to 8 PM.
  • Saturday and Sunday restaurant hours are 10 AM to 9 PM.

Switch Statement Example 3

  • The provided switch statement asks the user a question and processes their answer.
  • Using toLowerCase() allows a user to enter, "yes" for example, regardless of which letters are capitalized.
  • Using trim() removes whitespace.
  • The user is prompted to enter their answer.
  • If the user enters "yes", the confirmation message prints, "You said 'yes'".
  • If the user enters "no", the negation message prints, "You said 'no'".
  • If the user enters "maybe", the hesitation message prints, "You are not sure".
  • If the user enters any other input, the default statement prints, "No match".

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

More Like This

Use Quizgecko on...
Browser
Browser