简体   繁体   中英

How does this formula work in java?

I'm trying to figure this out, but how does the double print 22? Also, what exactly does the semicolon do after the for loop? I'm going to assume that the final result is due to this.

public class termdeposit
{
    int sum;

public termdeposit()
{
    sum = 1;
}

public void test() 
{
int sum = 1;
for (int i = 0; i <= 4; i++); {
    sum = sum + 1;
}
System.out.println ("The result is: " + sum);
System.out.println("Double result: "+ sum+sum);
}
}

The semicolon ends the (useless) loop statement, and the curly braces start an unrelated block of code. Your code is equivalent to this:

for (int i = 0; i <= 4; i++) {
    // do nothing
}
// run once:
sum = sum + 1;

Your print statement prints 22 because sum+sum is interpreted as string concatenation in the context of the previous + , and since sum now is 2 , it prints "2" and "2" .

I'm assuming that you were challenged to explain the program behavior. It's a trick question. As you seem to be aware, the semicolon is very important. This code:

for (int i = 0; i <= 4; i++); {
    sum = sum + 1;
}

is deceptive. Properly indented, it would be something like:

for (int i = 0; i <= 4; i++)
    ; // do nothing
{
    sum = sum + 1;
}

The braces create a code block (which could have declared variables local to that block). In this case, it has exactly the same effect as if sum = sum + 1; were written outside any braces.

You should be able to figure out the rest of the behavior from that plus the fact that, in the last print statement, the + operator associates left-to-right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM