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

Need help with some Java theory

 
Vlada Den
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Here is a piece of code:



I have two questions:

1. Are "intResult" and "doubleResult" local variables?
2. Why the return type of the getAddResult() method is String, if I operate with int and double variables?

Thank you,

Vlada
 
M Beck
Ranch Hand
Posts: 323
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. yes.
2. because the thing you're returning (everything after the "return" statement) is a String.
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

1. Are "intResult" and "doubleResult" local variables?


Yes, they're. However, the variables int1, int2, double1 & double2 are not. These should be instance variables, if not, you're going to get a compile-time error.


2. Why the return type of the getAddResult() method is String, if I operate with int and double variables?


Firstly, it was you to declared that the return type of this method to be of String type. And at the return statement, you concatenate String object with the integer & double results which in turn produced a new String object.
 
Jeff Jetton
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chengwei Lee:

Firstly, it was you to declared that the return type of this method to be of String type. And at the return statement, you concatenate String object with the integer & double results which in turn produced a new String object.


Yup. Another way to look at it is to rewrite your code like this:



Now ask yourself: What would you have to put in place of "???" to make this work? In other words, what type should the variable "foo" be?

A String, of course. That's really what you're returning, even though your example doesn't use a variable as an intermediate step like I'm doing.

- Jeff
 
Vlada Den
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much, guys!

Vlada
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic