Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Understanding how to use methods

 
Jane Hall
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Could anyone help me with the code below? I understand that it's because Java doesn't update the values of the latitude and longitude from the function, but I don't know how to fix this (without just removing the function).

I'm a beginner at programming, and the below example is taken from a book on C (Head First C) where it explains how to fix this with pointers. But I'd really like to understand how this works in Java where you don't have pointers.

Thanks!

 
fred rosenberger
lowercase baba
Bartender
Posts: 12125
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could encapsulate the values in an object...something like


You would then pass the object into the method, and you can update its member variables (assuming you have written the proper setter methods).
 
Jane Hall
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does that mean there's no way to do it keeping a similar structure? Is it not possible to call a method and use the values of the variables you've set inside them?
 
Kemal Sokolovic
Bartender
Posts: 825
5
Java Python Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not possible with primitive types.

You can read this tutorial section, scroll down to Passing Primitive Data Type Arguments and Passing Reference Data Type Arguments for more details.
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jane Hall wrote:Does that mean there's no way to do it keeping a similar structure?


You say that like it's a bad thing. But it's really a good thing, because it makes it much easier to look at a program and understand what it does. In the Java version of the code, you can look at line 7 of the posted code and know that after it runs, the values of the two local variables will remain unchanged. In a similar C version you wouldn't know that. Somewhere there's a rule of thumb which says "Functions with side effects are evil" (don't ask me to point it out), so not allowing code to change reference parameters is a good thing according to that rule of thumb.
 
Jane Hall
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone! Exactly what I wanted to know.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic