Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dont�t understand the result

 
Stephan Deve
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
i have a problem with the following question (from javacertivicate.com):

Meanwhile i know that the answer is 31. So i can choose the right answer everytime i see the question, but i still don�t understand what is happening.
After x += x << 3; x is 54
After y += z << 2; y should be 25
If i add 54 and 25 i think this should be 79. So why is 31 correct ??



greetings
Stephan
 
Rajasekar Elango
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Carefully look at test method.
 
Netty poestel
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
a bit tricky

do so :-- public void test(int d(or anyother identifier except x), int z)
and you'll get your answer 79.

do:-- public void test(int x, int z)
you get x= 6, z = 25
 
Rajasekar Elango
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Sorry for incomplete previous post.

Look at


Within the test method parameter variable x is redeclared, So only the local variable x is modified and not static variable x defined in class Pass.

But variable y is not declared within test and y += z << 2, modified y to 25.

So in the System.out.println(x+y) is 6 + 25 = 31 (x has the value assigned to 6 in main() before calling test())

The variable x in test is said to shadowed the same variable declared in class.

- Rajasekar
 
Celso Serrano Araujo
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note que x += x << 3; is assingment 54 in the automatic variable x and not variable member static x
 
Stephan Deve
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it now.
Thanks a lot.

Changing

to

helped a lot to make clear how this code works.


greetings
Stephan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic