Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Java pass by value only? [closed]

So here is another worthy downvote question.

I understand that Java IS pass by value and what this means and how it works. So this is not another can you explain what pass by value is. I am more curious as to WHY Java does not include pass by reference? I would imagine this would be useful? It would also be helpful to know to cement the reasoning in my head....

I hate 'it is because it is' scenarios surely the equivalent of 'because I said so'. So does anyone have an answer as to why Java only includes pass by value?

like image 471
Danrex Avatar asked Jun 08 '14 00:06

Danrex


People also ask

Why Java is strictly pass by value?

Object references are passed by value The reason is that Java object variables are simply references that point to real objects in the memory heap. Therefore, even though Java passes parameters to methods by value, if the variable points to an object reference, the real object will also be changed.

Is Java only pass by value?

Java is always Pass by Value and not pass by reference, we can prove it with a simple example. Let's say we have a class Balloon like below. And we have a simple program with a generic method to swap two objects, the class looks like below. When we execute above program, we get following output.

Why Java is pass by value and not pass by reference?

Java is officially always pass-by-value. The question is, then, “what is passed by value?” As we have said in class, the actual “value” of any variable on the stack is the actual value for primitive types (int, float, double, etc) or the reference for reference types.

What are the disadvantages of pass by value?

A disadvantage of pass-by-value is that, if a large data item is being passed, copying that data can take a considerable amount of execution time and memory space. Pass-by-reference improves performance by eliminating the pass-by-value overhead of copying large objects.


1 Answers

O'Reilly's Java in a Nutshell by David Flanagan puts it best: "Java manipulates objects 'by reference,' but it passes object references to methods 'by value.'" This was a design decision by Java. When you pass objects around, you are still manipulating the same underlying object as they all reference the same memory location. So I'm not sure what specific scenario you are thinking about that you can't do with the existing Java mechanisms.

like image 128
rvijay007 Avatar answered Oct 10 '22 01:10

rvijay007