This site requires JavaScript, please enable it in your browser!
Greenfoot back
aromero2
aromero2 wrote ...

2015/8/30

Could anyone help me understand this, please?

aromero2 aromero2

2015/8/30

#
This is terrible, but I missed this question 3 times in a test and I just can't seem to grasp how to solve it. Any assistance, please?
public class Test {
     public static void main(String[] args) {
         int j = 0;
         int i = ++j + j * 5;

         System.out.println("What is i? " + i);
     }
}
danpost danpost

2015/8/30

#
What was the actual question? Would it be 'What does the following code output to the terminal?' ? The answer is to this question is: "What is i? 6" Line 3 sets 'j' to zero; Line 4 set 'i' to the sum of (a) the incremented value of 'j', or one; and (b) that incremented value of 'j' times five, or one time five, or five; The sum of one and five is six.
aromero2 aromero2

2015/8/30

#
Yes, sorry the question was asking what the output of I to the terminal would be. So, as I understand it now - the preincrement affects all the variables of 'j" not just the 'j' with the '++' before it. So it actually looks like i = 1 + 1 * 5. Thanks danpost! I appreciate your help as always.
danpost danpost

2015/8/30

#
I think that if the parts of the sum were reversed, it would be different. If:
int i = j * 5 + (++j);
you would get: i = 0 + 1
You need to login to post a reply.