Java is ALWAYS Pass By Value. Here's Why

preview_player
Показать описание
Is Java pass by reference or pass by value? Java is ALWAYS pass by value, not pass by reference. But it can look like it's pass by reference when it's not. We'll go over what that means and what that is in this video.

A common Java question is whether Java is pass by reference or pass by value. As a Java beginner it's easy to misunderstand how this works, so we'll break this down in this Java beginner tutorial video lesson.

Learn or improve your Java by watching it being coded live!

Hi, I'm John! I'm a Lead Java Software Engineer and I've been in the programming industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java learners.

Let me know what else you'd like to see!

Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.

📕 THE best book to learn Java, Effective Java by Joshua Bloch

📕 One of my favorite programming books, Clean Code by Robert Martin

🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial

🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)

📹Phone I use for recording:

🎙️Microphone I use (classy, I know):

Donate with PayPal (Thank you so much!)

☕Complete Java course:

Рекомендации по теме
Комментарии
Автор

A get what you're saying, but it seems a bit misleading to say that it's always passes by value. From what I've understood from most languages I've used, I've always assumed that passing a reference/pointer/memory address of an object is what Pass by Reference meant, and that Pass by Value is like passing a whole copy of an entire object itself. The process that you've just shown in this video is what I believe many people would describe as Pass by Reference.

XanderKyle
Автор

All the confusion comes from the Java marketing people demanding that name "pointer" is never used.
This made sense at the time since "pointer" at the time implied a raw C-style pointer which you could manipulate.
Thinking of Java as "passing by managed pointer" makes much more sense in today's context.

poulsander
Автор

By your definition pass by reference doesn't exist in C either. Having a pointer parameter in C will also allocate a copy of that pointer and changing the pointer's address in the function won't change the original pointer variable. A better name for it might be "pass by address" to make clear that we don't talk about variable references but as we don't have something called a reference (like C++ or PHP has) we might aswell call our object references or pointers "reference" and therefore call this pattern pass by reference. It's all about the wording of a particular language. Also the object references in Java internally aren't direct memory addresses but rather a reference token for that object to allow more efficient memory usage and defragmentation but that's up to the implementation of the JVM and the behavior is as if we were copying immutable pointer address around.

JanBebendorf
Автор

Thank you for reaffirming my understanding! I always thought of passing references to objects in Java as passing a key of a room : in Java we always make a copy of the key as we pass it. That way the recipient of the key will only make changes in the room if the room is mutable, but if they end up messing with their copy of the key, my original key will still successfully access the room with no changes in the room. I think in other languages that have the concept of pointers, we may be sharing the original key with the recipient, who can change it for us to allow us to access another room.

mohamedhegazy
Автор

John you have become my new Online Java mentor, I've been developing javascript for the last 10 years so I'm not totally new to programming so your fast detailed explanations are pure brain candy. please keep them coming.

On another note, if you could someday do some springboot videos OMG you'd hit rockstart status!!

justinmeskan
Автор

Commenting to assist with YouTube algorithm. Thanks for much-needed inspiration with Java.

findlestick
Автор

Consider this:

public void static main(String[] args) {
Integer myInt = new Integer( 12 );
aMethod( myInt );
System.out.println("myInt: "+myInt); // will print 13! This is NOT pass by value behaviour.
}

void aMethod( final Integer myInt ) {
myInt.increment();
}

over
Автор

You cover the same stuff as my professor, but in a different way. Hearing it two ways is sooo helpful.

nunya
Автор

you are THE Java professor everyone is looking for :)

benkimoon
Автор

That's clear, thks !

But I think the term "reference" is a bit misleading for C++ developpers like me. Actually, from your description "Cheese" is actually a "pointer", not a "reference".
So pointers are passed by value, which totally makes sense. But in C++ that's what we call "passing parameters by pointers", not "by value".

In C++, when a parameter is passed "by reference", actually it's totally different. In this case, no copy at all is happening, neither the object itself, neither its adress. If you look at the stack when the function is called, no value is stacked at all for reference parameters when the function is called. So it's really different from Java "references".

So my question is : Why not just saying "In Java, parameters are passed by pointers" ? This would be much less confusing...

zghxzwpc
Автор

I would always make a method like this return an object and store it as a new variable. This is important to understand. You explain in such a way that it's easy to understand

pejko
Автор

So...

The cheese variable holds a reference to the object in memory.

We pass the cheese variable (reference) to the function.

Therefore, it's pass by value?

It's literally a reference...that we are... passing.

What am I missing?

HaveAGreatDayStranger
Автор

Your explanation describes precisely pass by reference (or address)... Yes you pass the address of the object by value, but this value is a reference to your object. The term pass by value or reference refers to the object itself and not to it's pointer. I have no idea why Java decided to confuse people with this terminology... It doesn't make any sense.

deconline
Автор

This is misleading... pass by value means you push a copy on the stack before the call. Pass by reference means the code passes the address of the object (of course the address is a 'pass by value') -- I think that is the point you wish to make, but for new devs, they may be confused . There are languages where object types can be defined to be 'value type' and the entire memory foot print of the object is (copied) and pushed on the stack - meaning the function only has a stack copy of the object and not the address (reference) to a mutable object that could have side affects. I think it is simple enough to point out that, in the end, everything is passed by copying value(s) pushed on the stack, but the implications of pass by value vs pass by reference are important -- and this makes it seem like all methods in java ar PBV, and hence get a copy of the object..not a reference to an existing one in the caller's stack.

Looks like several others made a similar comment - perhaps an edit is in order? Otherwise, nice work on all the other videos.

rainmanrick
Автор

Primitives e.g. int, short, double, char, long, and boolean are passed by value. Reference types e.g. strings and objects are passed by reference. That's how I understand it.

clint_
Автор

if "pass by the value of the reference" is "pass by value" then what's actually "pass by reference"?

radiosparrow
Автор

I tried understanding this thru articles for about 2hrs and got nothing, this 5 min video just clarified all my doubts. Thanks a lot, John❣

jagadeeshgurana
Автор

John speaks about the "values" of memory addresses of objects that Java passes to functions. For any C / C++ developers out there, these "values" are called pointers.

Bill-gcbt
Автор

A pointer to an object is a reference to that object. Saying that you're passing the value of that pointer and thus are passing by value is technically correct but a little too specific. Methods are passing object POINTERS by value, but they are also, less specifically passing objects by reference.

spudhead
Автор

So let me get this straight: passing an object reference is not "passing by reference"?
I understand the pass by value argument, but everything is pass by value regardless since you're can't just magically make something appear out of thin air. There's only 3 ways of passing an argument: by explicit copying of the entire object, by copying it's address (pass by pointer), or by copying it's address and using it like it's in the same context (pass by reference).

vd_rlty