Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 32

Thread: Can't pass by reference?

  1. #1
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Can't pass by reference?

    Hello, I'm fairly new to Java, I'm very experienced with C++ and C# in which you can pass by reference - extremely useful. Take for example this bit of code in C#:

        class MyClass
        {
            public MyClass(int i)
            {
                m_i = i;
            }
     
            public int m_i;
        }
     
        class Program
        {
            static void DoSomething(ref int i)
            {
                i = i * 2;
            }
     
            static void Main(string[] args)
            {
                MyClass x = new MyClass(1);
                DoSomething(ref x.m_i);
                DoSomething(ref x.m_i);
                DoSomething(ref x.m_i);
            }
        }

    Just at the end of this program x.m_i will be equal to 8. As far as I can see this is not possible in Java: you can't pass a double by reference, using a Double will kick in the autoboxing so that won't work either. The only "solution" in Java would be to pass in a double[] (of length 1) or to make a wrapper class, both nasty solutions because a user may want to just hold a double as a member of their class just as I have, for reasons such as not allocating more memory for a class and generally not being bloated. Does anybody have any ideas of a solution to this if there is one? if there isn't will there be one in Java?

    Peter
    Last edited by JavaDeveloperPeter; August 25th, 2014 at 09:46 AM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Can't pass by reference?

    Java does not pass parms by reference.

    Please edit your post and wrap your code with code tags:
    [code=java]
    YOUR CODE GOES HERE
    [/code]
    to get highlighting and preserve formatting.

    For your simple example, have doSomething() return the new value and have the caller assign it to i.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Can't pass by reference?

    Java is pass-by-value. It is *not* pass-by-reference.

    If that is confusing, please read this: JavaRanch Campfire - Cup Size: a Story About Variables
    And then this: JavaRanch Campfire - Pass By Value, Please

    The only way to accomplish what you want is by passing in a wrapper Object that contains a double.

    I'm not sure how much overhead you think this is going to entail, but worrying about it seems like premature optimization to me.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. #4
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    Thanks, but it is quite a nasty flaw, suppose that you implement a brent solver or a newton solver. Suppose that there is a double that you want the brent solver to solve for, or many doubles that the newton solver should solve for. In C# or C++, you can just pass by reference or use their addresses. In Java the implementation of where the doubles live has to change to a bunch of wrapper classes... you can't seriously be saying that that is ok?

  5. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Can't pass by reference?

    Quote Originally Posted by JavaDeveloperPeter View Post
    Thanks, but it is quite a nasty flaw
    This is not a flaw. This is a purposeful design choice.

    Quote Originally Posted by JavaDeveloperPeter View Post
    Thanks, but it is quite a nasty flaw you can't seriously be saying that that is ok?
    ...I'm pretty fine with it.

    If you want to program in C or C++, then program in C or C++. Not every language works the same.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. #6
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    Obviously not all languages work the same, and obviously Java is not for doing maths! No wonder Java is going down the toilet.

  7. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Can't pass by reference?

    If you say so. It's worked pretty fine for me up to this point.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  8. #8
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    Seriously, try C# or C++ you don't know what you are missing!

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Can't pass by reference?

    What is your purpose for posting here? It sounds more like trolling than an attempt to learn java.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    Fair enough, but being told "not all languages are the same" maybe that isn't trolling but pretty daft, when I've raised a good question.

  11. #11
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Can't pass by reference?

    Quote Originally Posted by JavaDeveloperPeter View Post
    Fair enough, but being told "not all languages are the same" maybe that isn't trolling but pretty daft, when I've raised a good question.
    You claimed that a pretty basic design choice was a "serious flaw", hence the explanation that not all languages are the same, so just because something is *different* doesn't mean it's *wrong*.

    I also don't really understand the motivations behind your posts. This is a technical forum, not a place to have pointless "language debates". Languages are tools. Different tools are better fit for different jobs. I've used C, C++, and C# in the past. Java is a better fit for most of the things I currently do. I'm not sure what you hope to achieve by telling me that "I don't know what I'm missing".
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  12. The Following User Says Thank You to KevinWorkman For This Useful Post:

    ChristopherLowe (August 25th, 2014)

  13. #12
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    I said that because I was irritated at the revelation that you gave me about languages being different - that maybe not trolling but quite an irritating comment. And I was looking for a solution or if someone knows if there will be a solution to this. And I'm sure that anyone who is objective would agree with me __because__ a Double is a class __but__ the autoboxing ruins that fact in this context. My apologies for getting heated, but I was looking for some clarification on this forum about a solution to what seems a contradiction even in the way the language is set up.

  14. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Can't pass by reference?

    Given that java is pass by value, what is your question?
    If you don't understand my answer, don't ignore it, ask a question.

  15. #14
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    Thank you for your answers everyone. My two questions have been answered. You can't pass by reference and this will never change and one should never question java developers about this.

  16. #15
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Can't pass by reference?

    Quote Originally Posted by JavaDeveloperPeter View Post
    I said that because I was irritated at the revelation that you gave me about languages being different
    And I said that languages are different because you seemed confused that a *purposeful design choice* was somehow a *flaw* because it wasn't the same in some other language.

    Quote Originally Posted by JavaDeveloperPeter View Post
    And I was looking for a solution or if someone knows if there will be a solution to this.
    You were given two separate approaches to this problem. What happened when you tried each?

    Quote Originally Posted by JavaDeveloperPeter View Post
    And I'm sure that anyone who is objective would agree with me __because__ a Double is a class __but__ the autoboxing ruins that fact in this context.
    I'm not even sure what this sentence is supposed to mean. What exactly is "ruined"?

    Quote Originally Posted by JavaDeveloperPeter View Post
    I was looking for some clarification on this forum about a solution to what seems a contradiction even in the way the language is set up.
    Like I said, you were given two solutions that you seem to be ignoring. And there is no contradiction: Java is *always* pass-by-value. No contradictions.

    Note that your question has nothing to do with autoboxing, as the Double class is immutable anyway.

    --- Update ---

    Quote Originally Posted by JavaDeveloperPeter View Post
    one should never question java developers about this.
    You are more than welcome to ask specific technical questions here, as this is a technical forum and we're here answering questions, for fun, in our spare time. We just don't have time to feed the "Java sux, C++ is better" trolls who don't understand that languages are tools, not religions. We have plenty of other spam to get rid of, haha.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  17. #16
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    Absolutely they aren't religious, best tool for the job. For making a GUI I'd much prefer C# or Java. For the record, my point about Double is what is the point of passing the class version of double if you can't set the value inside it. You are right, I became heated and perhaps some posts are a little uncalled for. I'm sure that there must be people that sympathize with my frustration though. I won't post again here.

  18. #17
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Can't pass by reference?

    Quote Originally Posted by JavaDeveloperPeter View Post
    For the record, my point about Double is what is the point of passing the class version of double if you can't set the value inside it.
    This doesn't really have anything to do with autoboxing or pass-by-value or pass-by-reference. The primitive wrapper classes are simply **immutable**, just like many other classes. The String class is also immutable. So is the File class, the Color class, etc.

    More info here: Immutable Objects (The Java™ Tutorials > Essential Classes > Concurrency)

    Quote Originally Posted by JavaDeveloperPeter View Post
    I won't post again here.
    That's a bit extreme, but it's really up to you. Happy coding.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  19. #18
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    I meant I won't spam any more on this post
    Thanks for your reply.
    Peter

  20. #19
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Can't pass by reference?

    Give the problem you originally asked, I would have to ask what logical sense doing it the way you suggested in C# makes.
    You passed the value 1 to an instance of the MyClass class, where you set the nonstatic variable m_i with the value 1. You then attempt to statically modify the value of m_i from outside of the MyClass instance? That just looks like a poor design.
    Java encourages you to modify simply type fields of an instance of an object from within that object (you can do it externally by getting and setting, but that is generally poor design).
    To do what you suggested in java:
    class MyClass {
    	public int m_i;
     
    	public MyClass(int i) {
                m_i = i;
            } 
    	public void doSomething() {
                m_i = m_i * 2;
            }
    }
    class Program {
            public static void Main(String[] args){
                MyClass x = new MyClass(1);
                x.doSomething();
                x.doSomething()
                x.doSomething()
    	}
    }
    Given how basic that solution is (and how similar it is to your C# code), I'm not sure why you are so heated.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  21. #20
    Member jdv's Avatar
    Join Date
    Jul 2014
    Location
    This Land
    Posts
    73
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: Can't pass by reference?

    The important consideration here is that object references are passed-by-value. That is, a pointer (and this word is used in the language specification) is passed, not the object itself.

    If you think about this a little then we really aren't "missing" anything vis-a-vis other languages. The only thing that changes are the idioms and the syntax.

    In short,
    Dog d;
    in Java is semantically the same as
    Dog *d;
    in C++. Similarly,
    identifyBark(d);
    in Java is passing a pointer/reference to the object, not the object itself.

    As suggested upthread, this is a specific design choice, especially when it comes to primitives, as the whole raison-d'etre of Java was to not allow potentially unsafe pointer maths in this regard.

  22. #21
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    Hi aussiemcgr, just to clear it up, that is just an example, it would as you say be pointless. the problem is for example say you have an object containing many doubles and you want to solve or change them to solve some condition. typically you would use something like a newton raphson solver and in c++ pass in the variable addresses.

    Hi jdv, please see my post to aussiemcgr. I think this is what gets people like me heated... "if you thiink a little". I admit to Norm and others that I was immature and too "religious". but comments like this are a little daft... clearly I am someone who thinks a lot, and clearly Java is great for some things, but to put it in your words and think a little you will see that there is something here that Java does miss over other languages, and to be correct I will say that of course Java has some great things that other languages don't have, for example it's GC is better than C#s and C++ doesn't even have one, unless you use the managed c++. I trolled a bit, but come on people, let's not be patronizing. And note that passing by reference for example how I showed in my example cannot result in any problems because pointers don't come in to it.
    Last edited by JavaDeveloperPeter; August 25th, 2014 at 11:50 AM.

  23. #22
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Can't pass by reference?

    Quote Originally Posted by JavaDeveloperPeter View Post
    let's not be patronizing.
    You might want to adjust how easily you take offense to things. Jdv was not implying that you don't think enough, he was simply transitioning into a new paragraph. It almost seems like you *want* to get into an argument, with how easily offended you seem to be. The internet is a big scary place, and part of being a good programmer is knowing how to take criticism. If you can't read a single answer (which are being posted, for free, by volunteers doing this in their spare time) without taking offense to every other sentence, you might be better off paying for a tutor or a consultant instead.

    Quote Originally Posted by JavaDeveloperPeter View Post
    And note that passing by reference for example how I showed in my example cannot result in any problems.
    Are you saying that passing by reference causes absolutely no problems? This is simply untrue, which is why Java chose to only use pass-by-value.

    Passing by reference has its uses, but saying that it comes with absolutely no downsides is not true.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  24. #23
    Member jdv's Avatar
    Join Date
    Jul 2014
    Location
    This Land
    Posts
    73
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: Can't pass by reference?

    It looks like returning to a rather interesting /technical/ discussion in this context is not going to be possible, so I will provide a reference for future spelunkers regarding "how to simulate C++ references in Java": How can I simulate pass by reference in Java? - Stack Overflow

    Every language has its own idioms, and there is a very good rationale for the Java spec to constrain how primitives (since they decided to have them) and objects are passed. This is discussed up-thread. But this does not mean, in this instance, that Java is missing the functionality that pass-by-ref can provide as it is often used in C++ (for example).

    I'll restate the salient point here: Java passes object references (referred to as "pointers" in the spec), so anything you can do with a primitive reference in C++ you can do in Java.

    It all depends on where you are coming from. Note that because of how objects are passed, Java coders don't have to worry about things like new() abuse, as is common in C++ (especially those of us who came to C++ from Java!)

    tl;dr:

    1. Java treats primitives and object parameters differently. The rationale for this includes (but is not limited to) increased type-safety, removing pointer math, and simplified class definition and method invocations.

    2. There is nothing magical about C++ style pass-by-reference that cannot be achieved in Java with well-known idioms. (Other than those things that are explicitly disallowed, of course.)
    Last edited by jdv; August 25th, 2014 at 12:05 PM. Reason: MOAR Clarification.

  25. #24
    Junior Member
    Join Date
    Aug 2014
    Posts
    14
    My Mood
    Bored
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't pass by reference?

    I'm not offended, I'm just surprised at how high handed people are, talking like that, and there you go suggesting that I need a tutor :-) do you even appreciate why passing by reference is useful, do you know why people use newton solvers, do you even know what one is? I can suggest using a tutor if you would like to find out :-) And come on, the criticism was made that you can have __pointer__ problems, and I corrected the person saying that passing by ref like that has nothing to do with pointers, I mean that in the context of pointers there is no problem.

  26. #25
    Member jdv's Avatar
    Join Date
    Jul 2014
    Location
    This Land
    Posts
    73
    Thanks
    0
    Thanked 5 Times in 5 Posts

    Default Re: Can't pass by reference?

    Quote Originally Posted by JavaDeveloperPeter View Post
    "if you thiink a little" ...
    My intention was the third-person "you", without resorting to using the rather snobby sounding "one".

    I did not intend for my neutral statement to be considered a dig. (This is why I did not quote you, but addressed my comment to the entire audience of the thread.)

    On the contrary, I was calling out a subtlety in the language that is often missed by newcomers and experts alike.
    Last edited by jdv; August 25th, 2014 at 12:14 PM. Reason: Clarify

Page 1 of 2 12 LastLast

Similar Threads

  1. not sure how to pass this value
    By iamgonge in forum What's Wrong With My Code?
    Replies: 3
    Last Post: May 16th, 2013, 01:08 AM
  2. Get Reference of js files
    By Priyankati in forum Other Programming Languages
    Replies: 1
    Last Post: February 11th, 2013, 12:04 PM
  3. Value vs Reference Types
    By anis.laghaei in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 23rd, 2012, 01:21 PM
  4. [SOLVED] Pass-by-Value scheme, puzzled with passing/assigning a reference to another object
    By chronoz13 in forum Java Theory & Questions
    Replies: 10
    Last Post: June 2nd, 2012, 10:43 AM
  5. 'pass by value' and 'pass by reference'
    By pokuri in forum Object Oriented Programming
    Replies: 5
    Last Post: January 26th, 2011, 11:30 AM