File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Understanding how to use methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Understanding how to use methods" Watch "Understanding how to use methods" New topic

Understanding how to use methods

Jane Hall

Joined: Jul 31, 2012
Posts: 12

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.


fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

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).

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Jane Hall

Joined: Jul 31, 2012
Posts: 12
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

Joined: Jun 19, 2010
Posts: 825

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.

The quieter you are, the more you are able to hear.
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

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

Joined: Jul 31, 2012
Posts: 12
Thanks everyone! Exactly what I wanted to know.
I agree. Here's the link:
subject: Understanding how to use methods
It's not a secret anymore!