Skip to main content

Java For Python Programmers Edition 2

Section 4.7 Summary & Reading Questions

  1. Java requires parentheses around the condition and curly braces for code blocks in if statements, unlike Python which uses indentation alone.
  2. Java uses else if instead of Python’s elif, and allows optional curly braces for single-line blocks. However, it is considered good practice to use curly braces even for single-line blocks to improve readability.
  3. Java’s switch statement is similar to Python’s match statement, but it only supports equality checks against constant values and does not evaluate relational expressions like greater than or less than.
  4. Java uses the boolean data type to represent logical values true or false, commonly used in conditionals and control flow.

Reading Questions Reading Questions

1.

Which is a correct Java if statement syntax?
  • if (x > 0) { System.out.println("Positive"); }
  • Correct! Java requires parentheses and curly braces.
  • if x > 0: print("Positive")
  • No, that’s Python syntax, not Java.
  • if x > 0 { System.out.println("Positive"); }
  • No, Java requires parentheses around the condition.
  • if (x > 0) print("Positive");
  • No, print is not a valid method in Java. Use System.out.println.

2.

How do you write Python’s elif equivalent in Java?
  • elif (score > 90)
  • No, elif is used in Python, not Java.
  • else: if (score > 90)
  • Incorrect syntax; no colon in Java and not the right structure.
  • else if (score > 90)
  • Right! Java uses else if.
  • ifelse (score > 90)
  • No, ifelse is not a valid construct in Java.

3.

What is one limitation of Java’s switch statement, including in its modern versions?
  • It cannot evaluate relational expressions like greater than or less than.
  • No, while switch can compare values, it does not support relational expressions like > or <, even with modern enhancements of Java 14+
  • It cannot handle more than five case labels.
  • No, there is no such limit. You can have many case labels in a switch statement.
  • It always requires a break statement.
  • Incorrect. The break statement is actually an optional feature of switch, not a limitation.
  • It can only compare a variable to constant values using equality.
  • Correct! Java’s switch is limited to constant comparisons using equality.
You have attempted of activities on this page.