English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

When will the output of the two code segments be different considering y is an initialized int variable?

SEGMENT 1

int x=0
while (y>0)
{
y--;
x++;
}
S.O.P.ln("x =" + x);


SEGMENT 2

for (int x=0; y>0; y--)
{
x++;
}
S.O.P.ln("x= " + x);

2007-08-14 01:50:18 · 2 answers · asked by dingdong 1 in Computers & Internet Programming & Design

2 answers

They appear to be functionally identical.

However, in the segment #2, x is declared in the for loop and is therefore scoped to the for() loop. It does not have a value outside of the loop and its block of code:

// x does not exist above the loop
for (int x=0; x<99; ++x) {
// x exists inside the loop
}
// x does not exist below the loop

Without additional code, segment #2 won't even compile, because the println at the end references x outside of its scope. (In segment #1, x is scoped to the block surrounding the while loop, which includes the println() at the bottom of segment #1.)

If segment #2 does compile, it is because the method in question has access to an instance variable or static variable named "x" and that other x does not need to have the same value. The static or instance x won't be touched by the for() loop, but will be printed at the end.

Summarized: "The output will be different when the segments are used in a class that has an instance or static variable named "x," because in segment #2, that's the value that gets printed, instead of the local temporary variable x. (And if that other x variable is not present, segment #2 won't even compile.)

Example:
=======================
public class Test {
static int x = 337; // Note static with same name

static void test1() {
int y = 10;
int x = 0;
while (y > 0) { y--; x++; }
System.out.println("TEST1: x = " + x);
}

static void test2() {
int y = 10;
for (int x=0; y>0; y--) { x++; }
System.out.println("TEST2: x = " + x);
}

public static void main(String[] args) {
test1();
test2();
} }

=======================
Sample output:

TEST1: x = 10
TEST2: x = 337

2007-08-14 04:10:53 · answer #1 · answered by McFate 7 · 1 0

i don't think that the two code segments can ever be different.
both are just another form of the other.

2007-08-14 09:07:34 · answer #2 · answered by momoy 2 · 0 0

fedest.com, questions and answers