Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Printing a value returned by a method.

 
John Paterson
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Guys,

I wrote the following code just to experiment handling a value returned by a called method. Following is the code:



My objective is to print from the main method, the value returned by the name method. How do I go about acheiving it? I get a 'cannot find symbol' error message with the above mentioned prinln statement. Hope someone can advise. Thanks.

regards
John
 
Gaurangkumar Khalasi
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
John Paterson wrote:I get a 'cannot find symbol' error message with the above mentioned prinln statement.


Because you have not defined an Instance variable named as "name" in the class Test, you have defined an Instance method "String name(String s){}".

So, try out to call a method...not a variable...like test.name("John");
 
Paul Clapham
Sheriff
Posts: 21142
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you do it? Well, first you assign the value returned by the method to a variable. And then, you print the value of that variable.
 
Greg Brannon
Bartender
Posts: 563
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In case you're having difficulty visualizing the fine answers you've been given thus far, to obtain the value returned by a method, assign it to a variable in the calling method:

That's to demonstrate how it's done using a variable, but you could also print the returned value directly:

 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would suggest you try something which doesn’t simply return its argument.There are some very dubious classifications of methods available, and this one is the most dubious of all. That duplicate method comes out as 1368 in that classification, so I marked it static. The private constructor means you must call that method the stylistically‑correct way:What you are doing in your method is creating a local variable referring to the same object as the parameter, and returning that reference without doing anything else with it. An optimising compiler may simply reduce that method to this!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic