• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can't seem to follow program logic here  RSS feed

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am making good progress using Enthuware's test simulation software (first test was a 52%, second 81%, third 72%). However, I don't seem to get any of the answers they have here in this code segment. Fortunately I guessed the right one, but I have no idea why the answer is what it is.


I went through it as follows: the first print statement will access Baap's h variable, and thus print "4", then b.getH(); will read Beta's getH method and give "Beta 44".

Then, similarly, bb will give b = "44" and getH will again be Beta's getH method and print "Beta 44". There was no constructor given, nor any static statements to worry about, so I figured this was the end of what should appear. I don't think the return statement in either getH method affects anything either. Thus my expected answer was:

4 Beta 44
44 Beta 44

However, the answer is apparently:

Beta 44
4 44
Beta 44
44 44

So... what am I missing here??
 
Ranch Hand
Posts: 136
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are wrong in very first assumption that there would be 2 output results....clearly SOP
is executed 4 times, hence 4 time output.

And to see why are output values this way, just debug the code which would tell you what code is actually executed.

Manish
 
Robert Lippens
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So let me see if I got this one straight.

At: System.out.println(b.h + " " + b.getH());

The inner method statement is evaluated first, and it will first activate Beta's println statement inside of the getH method. So the first thing printed will be "Beta 44".

Then, the rest of the values inside of the main method print statement will be evaluated: b.h = 4, b.getH() returns 44 so the next line will be 4 44.

The same will occur for the bottom method, yielding

Beta 44
44 44
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!