Exercise 02: Simple for loop

Very Easy Exercises For Beginners
Very Easy Exercises   For Beginners  E = Exercise
 E01   E02   E03   By title 

The following code demonstrates a simple Java for loop. The level of this serie exercises is very easy. They are all designed for beginners.

Java exercise 02: A simple for loop

Level: Very easy

What happens if the following code is compiled and run?

public class MyClass
{
  public static void main(String[] args)
  {
    for(int i = 0; i < 3; i++)
    {
      System.out.print(i);
    }
  }
}
Author: Sar Maroof

Select the correct answer.


Answer explanation

  1. The statement for(int i = 0; i < 3; i++) means that execute the body of the loop as long as the value of the variable i is smaller than 3 and by each execution icrement the value of i by one. The initial value of i is 0, therefore the statement System.out.print(i); writes 0 to the standard ouput.
  2. By the second time execution of the body of the loop, the value of i becomes 1.
  3. By the third time execution of the body of the loop, the value of i becomes 2.
    The statmenent System.out.print(i); writes all the three value of i to the standard ouput.

The correct answer is: a.

If you found this difficult, you might consider reading my book Java quizmaster for beginners. It is easy to understand, organized to learn Java in 17 days and it guides you to master Java code by solving 105 quizzes and 117 assignments. This book explains each chapter properly before starting with exercises and assignments. It is available on Amazon. See inside the book here!

Please, leave your questions, feedback and suggestions in the comments below!
SarMaroof.com offers a practical method to learn and improve your Java skills. It avoids unnecessary long boring theoretical explanations, but it uses many exercises and quizzes.




Sar Maroof is graduated from HBO Amsterdam "higher professional education". He is a professional computer programming teacher, gives master classes and publishes technical articles. His experience with developing software started from 2001 and he has worked as a software developer for several big as well as small companies and later as a freelancer. He is the author of Java quizmaster and Build a Java application in 7 days.

Books by Sar Maroof

           

 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *

Sarmaroof © 2017