Study Guides/Computer Science/Control Statements in Java
Study Guide ยท Computer Science

Control Statements in Java: Types and Examples

By default, a Java program executes code sequentially, line by line from top to bottom. However, in real-world applications, you often need to skip lines of code, repeat lines of code, or choose between different blocks of code based on a condition. This is achieved using Control Statements.

Question (Click to Flip)

What is an enhanced for-loop in Java?

Answer

Also known as the 'for-each' loop, it is a specialized loop introduced in Java 5 to iterate through arrays and collections much easier without needing an index variable.

Card 1 of 1 free previews

Key Facts

In Java, omitting the break statement inside a switch block will cause 'fall-through', meaning it will execute all subsequent cases even if they don't match.

An infinite loop occurs when the condition in a while or for loop never evaluates to false.

1. Decision-Making Statements (Conditional)

These statements evaluate a boolean expression (true or false) and decide which block of code to run.

  • if statement: Runs the code inside it only if the condition is true.
  • if-else statement: Provides an alternative block of code to run if the condition is false.
  • switch statement: Allows a variable to be tested for equality against a list of values (cases). It is a cleaner alternative to writing many nested if-else if statements.

2. Iteration Statements (Loops)

These statements allow a block of code to be repeated multiple times until a certain condition is met.

  • for loop: Used when you know exactly how many times you want to loop through a block of code.
  • while loop: Repeats a block of code as long as a specified condition remains true.
  • do-while loop: Similar to a while loop, but it guarantees that the code block will execute at least once before checking the condition.

3. Jump Statements

These transfer control to another part of the program abruptly.

  • break: Instantly terminates a loop or a switch statement and moves to the next line of code outside the block.
  • continue: Skips the current iteration of a loop and instantly jumps back to the top of the loop for the next iteration.
  • return: Exits from the current method and returns a value to where the method was called.

Questions and Answers

What is an enhanced for-loop in Java?+

Also known as the 'for-each' loop, it is a specialized loop introduced in Java 5 to iterate through arrays and collections much easier without needing an index variable.

More in Computer Science

Study Smarter with Shinyu.ai

Turn this guide into revision flashcards, a practice exam, or an AI-generated podcast โ€” free, no signup required.