• Post Reply Bookmark Topic Watch Topic
  • New Topic

Head First Java Chapt 4 "Be the compiler" question.  RSS feed

 
Ranch Hand
Posts: 178
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I appreciate the help I'm getting here. May I please verify that in the below code the line "int y = x.go(orig);" is the value of the argument "orig" being used in the parameter for method " int go (int arg)" ? Output is " 42 84"

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yea, you are doing it right.

Your caring the name orig of a value, 42.

into your object of XCopy x = new Xcopy();

with a method object called go and you are returning it along with its mutation in int y.

Yea it is working correctly.
 
Sheriff
Posts: 4935
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Lisa Austin wrote:May I please verify that in the below code the line "int y = x.go(orig);" is the value of the argument "orig" being used in the parameter for method " int go (int arg)" ? Output is " 42 84"

Hi Lisa. Yes, the output is correct, based on the code you posted. How it happens:

Line 4: you declare variable "orig" and initialise with value 42.
Line 5: creating a new instance of "XCopy" class. "x" is a reference variable, which refers to that created object.
Line 6: declare variable "y" and in order to initialise, rather than providing pure literal value, you invoke a method "go" on previously created instance "x" and pass the argument, which is a copy of variable "orig".

Method "go(int arg)" takes this passed variable copy as parameter, does some calculations (multiplies 42 times 2), and returns new value "84" (so, it is a value of variable "y" in line 6).

Line 7: This part probably confused you as likely you expected sum of them. But what actually is being printed, it prints "42" first, which is initial value of variable "x" and concatenates it with "space symbol" (which is string) as well as with variable "y" value.

So you get 42space84
 
Lisa Austin
Ranch Hand
Posts: 178
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all. I really appreciate the patience answering my questions. I often think I understand what I'm reading but need / want confirmation.
 
Liutauras Vilda
Sheriff
Posts: 4935
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome. Well, I think it is a correct way to ask such a questions over here, so someone can help you get firm understanding about the topic.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!