• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

Java Loop Control

by admin

A loop statement allows us to execute a statement or group of statements multiple times

Loop & Description

  • while loop: Repeats a statement while a given condition is true.
  • for loop: Execute a sequence of statements multiple times and abbreviates the code that manages the loop variable.
  • do…while loop: it tests the condition at the end of the loop body.

Enhanced for loop in Java

Used to traverse collection of elements including arrays:

for(declaration : expression) {
   // Statements
}
  • Declaration: The newly declared block variable, is of a type compatible with the elements of the array you are accessing. The variable will be available within the for block and its value would be the same as the current array element.
  • Expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

Example:

public class Test {

   public static void main(String args[]) {
      int [] numbers = {5, 8, 7, 4, 9};

      for(int x : numbers ) {
         System.out.print( x );
         System.out.print(",");
      }
      System.out.print("\n");
      String [] names = {"Tiger", "Puss", "Smokey", "Misty"};

      for( String name : names ) {
         System.out.print( name );
         System.out.print(",");
      }
   }
}

Output:

5,8,7,4,9, Tiger,Puss,Smokey,Misty

Loop Control Statements

When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

Java supports the following control statements.

  • Break statement: Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.
  • continue statement: Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

Filed Under: Java

Some more articles you might also be interested in …

  1. Java Basics: Abstract and Nested Classes
  2. Java Initializers basics
  3. Java – Sending Email
  4. Java Applet Basics
  5. Scope of Variables in Java
  6. jarsigner: command not found
  7. Introduction to Exceptions in Java
  8. Using ‘final’ Keyword in Java
  9. Java Operators
  10. Java Methods

You May Also Like

Primary Sidebar

Recent Posts

  • nixos-rebuild Command Examples in Linux
  • nixos-option: Command Examples in Linux
  • nixos-container : Command Examples in Linux
  • nitrogen Command Examples in Linux

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright