Consider the classes below:
public class TestA
{
public static void main(String args[])
{
int x = 2;
int y = 20
int counter = 0;
for (int j = y % x; j < 100; j += (y / x))
counter++;
}
}
public class TestB
{ public static void main(String args[]) { int counter = 0; for (int j = 10; j > 0; --j) ++counter; }}
Which of the following statements is true?a. The value of counter will be different at the end of each for loop for each class.b. The value of j will be the same for each loop for all iterationsc. Both (a) and (b) are true.d. Neither (a) nor (b) is true

Respuesta :

Answer:

Hi!

The correct answer is d. Neither (a) nor (b) is true.

Explanation:

First, you have to know what the scripts intend to do, and they are counting from 1 to 10 in both cases.

Table of results of class TestA at end of each iteration:

[j = 0,  counter =  1]

[j = 10,  counter =  2]

[j = 20,  counter =  3]

[j = 30,  counter =  4]

[j = 40,  counter =  5]

[j = 50,  counter =  6]

[j = 60,  counter =  7]

[j = 70,  counter =  8]

[j = 80,  counter =  9]

[j = 90,  counter =  10]

Table of results of class TestB at end of each iteration:

[j = 10,  counter =  1]

[j = 9,  counter =  2]

[j = 8,  counter =  3]

[j = 7,  counter =  4]

[j = 6,  counter =  5]

[j = 5,  counter =  6]

[j = 4,  counter =  7]

[j = 3,  counter =  8]

[j = 2,  counter =  9]

[j = 1,  counter =  10]

That's why a) and b) are false.

Maybe you want to know why using pre increments on class TestB doesn't affect the loop. The reason is that when enters in a loop, first checks the test condition and takes the decision if true or false, and last executes the incrementation step.

ACCESS MORE