About Question com.enthuware.jfcja.v8.2.333 :

Oracle Certified Foundations Associate Java Certification Questions and Discussion
1Z0-811

Moderator: admin

Post Reply
Maria Teresa Lorenzo
Posts: 5
Joined: Fri Nov 18, 2022 2:45 pm
Contact:

About Question com.enthuware.jfcja.v8.2.333 :

Post by Maria Teresa Lorenzo »

Can anybody explain the logic behind this loop?

Thanks

Maria Teresa Lorenzo
Posts: 5
Joined: Fri Nov 18, 2022 2:45 pm
Contact:

Re: About Question com.enthuware.jfcja.v8.2.333 :

Post by Maria Teresa Lorenzo »

Given the following code, which of these statements are true?

Code: Select all

public class TestClass
{
   public static void main(String args[])
   {
      int k = 0;
      int m = 0;
      for ( int i = 0; i <= 3; i++)
      {
         k++;
         if ( i == 2)
         {
            // line 1
         }
         m++;
      }
      System.out.println( k + ", " + m );
   }
}
These were the 3 possible correct answers:
It will print 3, 2 when line 1 is replaced by break;
It will print 4, 3 when line 1 is replaced by continue.
It will print 3, 3 when line 1 is replaced by i = 4;
Last edited by admin on Thu Mar 30, 2023 10:30 pm, edited 1 time in total.
Reason: Please put code inside [code] [/code]

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: About Question com.enthuware.jfcja.v8.2.333 :

Post by admin »

Can you please tell which part do you have trouble understanding? Do you know how break and continue statements work?

In questions like these, you need to keep track of all the variables after each statement. For example, let's see what happens when you put break; in place of //line 1:
In in the first iteration of the for loop, i is 0. Inside the loop, k is incremented to 1, since i is not equal to 2 break is not executed, and then m++ increments m to 1.
In in the second iteration of the for loop, i is 1. Inside the loop, k is incremented to 2, since i is not equal to 2 break is not executed, and then m++ increments m to 2.
In in the third iteration of the for loop, i is 2. Inside the loop, k is incremented to 3, since i is equal to 2 break is executed. Therefore, the loop break (m++ is not executed).

After the for loop, k, which is 3, and m, which is 2, are printed.

You can try doing the same for other two options.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 15 guests