Teachnique
      CourseRoadmaps
      Login

      OverviewHistoryFeaturesJava 8 - New Featuresvs C++Virtual Machine(JVM)JDK vs JRE vs JVMHello World ProgramEnvironment SetupBasic SyntaxVariable TypesData TypesType CastingUnicode SystemBasic OperatorsCommentsStreamsNew Date-Time API

      Loop ControlDecision Makingif-else Statementswitch statementfor loopfor each Loopwhile Loopdo...while Loopbreak Statementcontinue Statement

      OOPs (Object-Oriented Programming) ConceptsObject and ClassesClass AttributesClass MethodsMethodsVariable ScopesConstructorsAccess ModifiersInheritanceAggregationPolymorphismOverridingMethod OverloadingDynamic BindingStatic BindingInstance Initializer BlockAbstractionEncapsulationInterfacesPackagesInner classesStatic ClassesAnonymous ClassesSingleton ClassWrapper ClassesEnum Class

      Number ClassBoolean classCharacter ClassArraysMath Class

      File ClassCreating FilesWrite To FilesReading FileDelete FilesDirectory OperationsFiles and I/O

      ExceptionsTry Catch BlockTry with ResourcesMultiple Catch BlocksNested Try BlockFinally BlockThrows and Throw | Throw an ExceptionException PropagationBuilt-in ExceptionsCustom Exception

      MultithreadingThread Life CycleCreating a ThreadStarting a ThreadJoining ThreadsNaming a Thread with ExamplesScheduling Threads with ExamplesThread PoolsMain ThreadThread PriorityDaemon ThreadThreadGroup ClassJVM Shutdown Hook

      Thread SynchronizationBlock SynchronizationStatic SynchronizationInter Thread CommunicationThread DeadlockInterrupting ThreadThread ControlReentrant Monitor

      NetworkingSocket ProgrammingURL ProcessingURL ClassURLConnection ClassHttpURLConnection ClassSocket Class with ExamplesGenerics

      Collections FrameworkCollection Interface

      List InterfaceArrayList Class

      Queue InterfaceArrayDeque Class

      Map InterfaceSortedMap Interface

      Set InterfaceSortedSet Interface

      Data Structures Enumeration Interface BitSet Class

      How to Use Iterator?How to Use Comparator?How to Use Comparable?

      RecursionRegular ExpressionsSerializationString ClassJava Arrays - Class

      Feedback

      Submit request if you have any questions.

      Course
      for each Loop

      Java Tutorial

      This Java tutorial is tailored for newcomers, offering a journey from basic principles to complex Java programming techniques. Completing this tutorial equips you with a solid understanding of Java, preparing you for advanced learning. You'll emerge ready to tackle the challenges of becoming a top-tier software engineer, with the skills to innovate and excel in the vast world of software development.

      for each Loop

      Java for each Loop

      A for each loop is a special repetition control structure that allows you to efficiently write a loop that needs to be executed a specific number of times.
      A for each loop is useful even when you do not know how many times a task is to be repeated.

      Syntax

      Following is the syntax of enhanced for loop (or, for each loop)
      for(declaration : expression) {
      // Statements
      }

      Execution Process

      • 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.

      Examples

      Example 1: Iterating Over a List of Integers

      In this example, we're showing the use of a foreach loop to print contents of an List of Integers. Here we're creating an List of integers as numbers and initialized it some values. Then using foreach loop, each number is printed.
      import java.util.Arrays;
      import java.util.List;
      
      public class Test {
      
      public static void main(String args[]) {
      List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
      
      for(Integer x : numbers ) {
      System.out.print( x );
      System.out.print(",");
      }
      }
      }

      Output

      10, 20, 30, 40, 50,

      Example 2: Iterating Over a List of Strings

      In this example, we're showing the use of a foreach loop to print contents of an List of String. Here we're creating an array of Strings as names and initialized it some values. Then using foreach loop, each name is printed.
      import java.util.Arrays;
      import java.util.List;
      
      public class Test {
      
      public static void main(String args[]) {
      List<String> names = Arrays.asList("James", "Larry", "Tom", "Lacy");
      
      for( String name : names ) {
      System.out.print( name );
      System.out.print(",");
      }
      }
      }

      Output

      James, Larry, Tom, Lacy,

      Example 3: Iterating Over an Array of Objects

      In this example, we're showing the use of a foreach loop to print contents of an array of Student Object. Here we're creating an array of Students as Student object and initialized it some values. Then using foreach loop, each name is printed.
      public class Test {
      
      public static void main(String args[]) {
      Student[] students = { new Student(1, "Julie"), new Student(3, "Adam"), new Student(2, "Robert") };
      
      for( Students student : students ) {
      System.out.print( student );
      System.out.print(",");
      }
      }
      }
      class Student {
      int rollNo;
      String name;
      
      Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
      }
      
      @Override
      public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
      }
      }

      Output

      [ 1, Julie ],[ 3, Adam ],[ 2, Robert ],