Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain to me what the reasoning behind passing by "value" and not by "reference" in Java is?

I'm fairly new to Java (been writing other stuff for many years) and unless I'm missing something (and I'm happy to be wrong here) the following is a fatal flaw...

String foo = new String();
thisDoesntWork(foo);
System.out.println(foo);//this prints nothing

public static void thisDoesntWork(String foo){
   foo = "howdy";
}

Now, I'm well aware of the (fairly poorly worded) concept that in java everything is passed by "value" and not "reference", but String is an object and has all sorts of bells and whistles, so, one would expect that unlike an int a user would be able to operate on the thing that's passed into the method (and not be stuck with the value set by the overloaded =).

Can someone explain to me what the reasoning behind this design choice was? As I said, I'm not looking to be right here, and perhaps I'm missing something obvious?

like image 789
Yevgeny Simkin Avatar asked Feb 05 '09 03:02

Yevgeny Simkin


2 Answers

This rant explains it better than I could ever even try to:

In Java, primitives are passed by value. However, Objects are not passed by reference. A correct statement would be Object references are passed by value.

like image 125
Ric Tokyo Avatar answered Sep 21 '22 15:09

Ric Tokyo


When you pass "foo", you're passing the reference to "foo" as a value to ThisDoesntWork(). That means that when you do the assignment to "foo" inside of your method, you are merely setting a local variable (foo)'s reference to be a reference to your new string.

Another thing to keep in mind when thinking about how strings behave in Java is that strings are immutable. It works the same way in C#, and for some good reasons:

  • Security: Nobody can jam data into your string and cause a buffer overflow error if nobody can modify it!
  • Speed : If you can be sure that your strings are immutable, you know its size is always the same and you don't ever have to do a move of the data structure in memory when you manipulate it. You (the language designer) also don't have to worry about implementing the String as a slow linked-list, either. This cuts both ways, though. Appending strings just using the + operator can be expensive memory-wise, and you will have to use a StringBuilder object to do this in a high-performance, memory-efficient way.

Now onto your bigger question. Why are objects passed this way? Well, if Java passed your string as what you'd traditionally call "by value", it would have to actually copy the entire string before passing it to your function. That's quite slow. If it passed the string by reference and let you change it (like C does), you'd have the problems I just listed.

like image 40
Dave Markle Avatar answered Sep 20 '22 15:09

Dave Markle