Java is ALWAYS Pass By Value. Here's Why

แชร์
ฝัง
  • เผยแพร่เมื่อ 26 ก.ค. 2024
  • 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
    amzn.to/36AfdUu
    📕 One of my favorite programming books, Clean Code by Robert Martin
    amzn.to/3GTPVhf
    🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
    www.audibletrial.com/johnclean...
    🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
    bit.ly/3QPNGko
    📹Phone I use for recording:
    amzn.to/3HepYJu
    🎙️Microphone I use (classy, I know):
    amzn.to/3AYGdbz
    Donate with PayPal (Thank you so much!)
    www.paypal.com/donate/?hosted...
    ☕Complete Java course:
    codingwithjohn.thinkific.com/...
    codingwithjohn.com

ความคิดเห็น • 341

  • @XanderKyle
    @XanderKyle 2 ปีที่แล้ว +235

    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.

    • @nelbr
      @nelbr 2 ปีที่แล้ว +22

      I absolutely agree with this comment. In most languages, pass by reference is when the address of the contents of a variable is passed to the function, which is exactly what was described here. Claiming that in Java this is pass by value just because seems a bit of a stretch to me.

    • @liviuursulescu2991
      @liviuursulescu2991 2 ปีที่แล้ว +17

      Pass by reference means that you have the same parameter in the called function and in the caller passed argument. In other words, if you change anything in the called function on that parameter, it will be also reflected in the caller. Here, if you try to change the passed cheese pointer (yes, even in Java, it's still a pointer), you only affect the local copy of the pointer, and not the myCheese variable defined in the main()... The misleading part here is that may times, when you sent a pointer to an object as a parameter, people think that you're sending the object itself, when instead you only send a copy of that pointer, hence cheese = new Cheese(); will affect only the copy, not the original pointer.

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว +14

      Pass by values is the only correct wording to describe this. I will show you immediately why. Let's say you have an array and you pass that array to a void method.
      The void method increases the number of elements of the array. What do you think happens outside of that method? The array length remains the same, because Java is pass by value.
      Here is the example.
      In the main method you have:
      int[] array = {0, 1, 2, 3};
      doSomething(array);
      Where the body and definition of the doSomething method are as following
      public static void doSomething(int[] array){
      array = new int[10];
      for(int i=0; i

    • @nelbr
      @nelbr 2 ปีที่แล้ว +10

      @@smrtfasizmu6161 I think it is just that Java programmers don't have the same understanding of pass by reference as C programmers do. Of course, even if you pass by reference, if you explicitly tells your function to create a new variable to work on, using the command new (as you did in your example above and also was done in the video), then the changes applied to the new variable will not be captured on the original variable. However, what would have happened if you did not use the new command inside the function?

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว

      @@nelbr The variable array will be affected outside of the function. However, if I don't use new I can't make the array bigger. Which means that I have to pass an array of the size which is at least as big as it is necessary to the function, because the function can't increase it. Why would I want to increase the length of the array in the method? The reason why this may be useful is if I want to have different outputs of a function, some of them I want to be arrays. In C I would pass a double pointer to the function (a pointer to the array), while in Java I could create a class which have an array as its field and then pass an instance of that class (I can do this in C with struct though). Of course, it is all just data, it is all just series of bytes, you can pack all the outputs of your function in one big array and read it sequentially, but this is less readable solution.
      The reason why I came to this video today is because I run into this "issue" today of wanting to have a method which has several outputs, some of them arrays.

  • @JanBebendorf
    @JanBebendorf 2 ปีที่แล้ว +197

    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.

    • @hrgwea
      @hrgwea 2 ปีที่แล้ว +14

      Correct. There's no pass-by-reference in C. Passing a pointer by value is the way to achieve the same effect as pass-by-reference, but it's a mechanism that you have to implement by yourself; the language doesn't handle it for you.

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว +5

      Of course it doesn't. I truly understood the difference of the two in C, in C you have to pass the double pointer if you want to change the address of the variable that you are passing to a function. For instance if you have a linkedList that you pass to a void function and you want to change the place where that linked lists starts in the memory (you want to add a new member, you want to change the head of the linked list), then you pass a double pointer to the void function. If you pass a pointer instead of a double pointer, your void function gets a copy of that pointer, in other words, it can't change where the pointer which was passed as an argument points to. That's why if you want to have a void function which adds a new head to the linked list, that void function needs to receive a double pointer as an argument. Of course, if your function doesn't return void and instead it returns whatever struct you used to create linked list, then you don't have to use double pointers.

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว +3

      It is not about the wording, you always pass by value, pass by value of a pointer if you are passing a pointer. The difference isn't just semantics, as you yourself have pointed out if a function takes a pointer as an argument, it takes a copy of that pointer. The function can't change the original pointer. Functions in C and Java always receive the copy. And this matters. I have already given you an example in C where it matters, now I will give you an example in Java (where matters even more because you can't use pointers like in C).
      Let's say you have an array like this
      int[] array = {};
      You can't pass this array to a function which arbitrarily increases the number of elements of that array. Why does this matter? It matters because this means that you can't pass this array to a function with intention of using this array as the output of a function. Let's say you want your function to have several different outputs, some of them being arrays. You can't pass an array to a function which you will use effectively as an output variable, unless you now the size of the array produced in the function in advance.

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว +1

      This Java problem that I have talking about is easily solved in C, either by passing a double pointer or by using realloc. Neither of the two exist in Java though. The problem is you want a function to have several outputs, some of them are arrays and you don't know the size of the arrays in advance. I guess in Java you can create a class which has all of these arrays as its fields and then you pass an instance of the class to the function.
      I mean yes, you can solve this problem in C in this same way as well, you can create a struct which has bunch of pointers as its fields.

    • @JanBebendorf
      @JanBebendorf 2 ปีที่แล้ว +5

      @@smrtfasizmu6161 It totally depends on how you define the word "reference" and the scope it is used in. Comparing it to C++ you are totally right but from a Java or C developer's perspective who doesn't have a concept that's similar to C++'s references you might aswell call the concept of passing by mutable objects (or pointers in case of C) "pass by reference". It's all a matter of the scope (:

  • @poulsander7899
    @poulsander7899 2 ปีที่แล้ว +74

    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.

    • @andreffrosa
      @andreffrosa 2 ปีที่แล้ว +1

      Exactly

    • @hoen3561
      @hoen3561 2 ปีที่แล้ว +1

      agreed

    • @sebastiangudino9377
      @sebastiangudino9377 2 ปีที่แล้ว +1

      Nice way to explain the idea!

    • @aleksey8530
      @aleksey8530 ปีที่แล้ว +1

      And also they don't show example about 'pass by value' in the C++!
      C++ can't change reference variable, and we can't redefine memory for it. We can't make such situation the JAVA speaks. It is just their imagination

  • @mohamedhegazy2182
    @mohamedhegazy2182 ปีที่แล้ว +22

    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.

    • @CodingWithJohn
      @CodingWithJohn  ปีที่แล้ว +3

      That's an even better way to explain it then I did!

    • @TheRiseLP
      @TheRiseLP ปีที่แล้ว +1

      @@CodingWithJohn "Primitive types are passed by value, everything else is passed by reference"
      There, that is the clearest way to explain it. I really don't understand why you feel the need to go through that kind of mental gymnastics only because you refuse to call it pass by reference.

    • @zdiscover1
      @zdiscover1 ปีที่แล้ว

      @@TheRiseLP I was stuck thinking why String even if passed as referencem do not change in the calling fn, and then I saw this view and it cleared out the confusion over how strings which are immutable must be handled internally. So basically the "mental gymnastics" worked!

    • @terrormapu
      @terrormapu 24 วันที่ผ่านมา

      This is the best explanation of the crux of the issue

  • @findlestick
    @findlestick 2 ปีที่แล้ว +18

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

  • @justinmeskan4410
    @justinmeskan4410 ปีที่แล้ว +20

    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!!

  • @nunya1120
    @nunya1120 2 ปีที่แล้ว +46

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

  • @pejko89
    @pejko89 2 ปีที่แล้ว +3

    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

  • @asherkhan2656
    @asherkhan2656 2 ปีที่แล้ว +1

    Nice short and sweet videos that help reinforce fundamental concepts 👍

  • @1over137
    @1over137 2 ปีที่แล้ว +5

    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();
    }

    • @thefab522
      @thefab522 2 ปีที่แล้ว

      Yes, it is pass by value behaviour. You're using the Integer wrapper class, not the int primitive type. myInt is not the value 12 itself, it's a reference to an object that contains the integer value 12.

    • @1over137
      @1over137 2 ปีที่แล้ว +2

      @@thefab522 Exactly. It's a reference to an object. So it's not the object itself... so.... it's pass by reference.

  • @jeanjacquesbarros
    @jeanjacquesbarros 2 ปีที่แล้ว +1

    Thanks! This concept was very confusing to me. Now it's clearer!

  • @zghxzwpc
    @zghxzwpc 2 ปีที่แล้ว +64

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

    • @WakkaFlocka
      @WakkaFlocka 2 ปีที่แล้ว +11

      "Pointers" may be a term that you understand as a C++ developer, but It's not a term used in Java development; this is why it's called a reference instead.

    • @zghxzwpc
      @zghxzwpc 2 ปีที่แล้ว +13

      @@WakkaFlocka : I understand this point. But I think it's a bit sad to use two different terms to express the same thing in two different languages. Or even worse, to use the same term to express two different things in two different languages !
      And that's the case here : Java reference == C++ pointer, and C++ reference doesn't exist in Java (as far as I know).
      Many developpers are using several languages to develop, this kind of ambiguity is confusing and I think it should be avoided as much as possible.

    • @vadimkholodilo2883
      @vadimkholodilo2883 2 ปีที่แล้ว +3

      I guess, we can't really say that it's passed by pointer, because there are no pointers in Java. Yes, variables hold nothing more than just a pointer, but since Java doesn't have pointers, this term can't be really used. Also, pointers in C/C++ let you work with addresses. For example, you can do something like myPointer++. However, in Java you can't really do it.

    • @zghxzwpc
      @zghxzwpc 2 ปีที่แล้ว +2

      @@vadimkholodilo2883 I agree that those "Java pointers" are not working exactly the same as C++ ones. You can't modify the address, you don't need to dereference the pointer to get the value, etc... But the concept is still much closer to "pointers" than to "references". So if we need to choose, "pointers" make much more sense.

    • @LSjame
      @LSjame 2 ปีที่แล้ว +2

      To answer your question: you would not say that because it is not true. Parameters are pass-by-value in Java.
      In C++, what you call "passing parameters by pointers" is actually a pass-by-value operation. The function parameter is a variable of type "pointer" (which points to the variable you wish to pass in) and a local copy of that pointer is created upon function call. Any changes to this new local pointer will not affect the original.
      Java References are like a combination of C++ pointers and C++ references, they have some properties of each, so there is no 1:1 comparison between the two languages. In this example, myCheese is just like a C++ pointer to a nameless object in memory. This pointer is passed by value, just like pointers in C++.

  • @karentechnologies3990
    @karentechnologies3990 หลายเดือนก่อน

    This video is the best explanation for the Java pass by value/reference topic on TH-cam. Subscribed

  • @deconline1320
    @deconline1320 2 ปีที่แล้ว +14

    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.

    • @jarlfenrir
      @jarlfenrir 2 ปีที่แล้ว +3

      I learned that java passes primitives by value and objects by reference... is this offical statement that java passes always by value?

    • @thierrydecorte1632
      @thierrydecorte1632 2 ปีที่แล้ว +1

      @@jarlfenrir The spec doesn't use wording such as pass by value/reference (as far as I know). It defines two types of variables: primitives and references and specify the following:
      "(8.4.1) When the method or constructor is invoked (§15.12), the values of the actual
      argument expressions initialize newly created parameter variables, each of the
      declared type, before execution of the body of the method or constructor."
      The word "value" here is used... But when the variable is a "reference type" the value passed is a reference to the object. Which makes it a pass by reference. Primitive types are not references which makes them pass by value.

    • @LSjame
      @LSjame 2 ปีที่แล้ว +1

      The term pass by value or reference refers to how function parameters are handled.
      myCheese is a pointer to a nameless object in memory. The variable myCheese (a pointer) is passed by value, and there is no way to pass in the nameless object, because Java does not allow variables with a true data type of Object (they are all references).
      Metaphorically, the nameless object gets passed by reference, but what actually happens is the reference object gets passed by value

    • @jarlfenrir
      @jarlfenrir 2 ปีที่แล้ว

      @@LSjame Then explain how does this differ from "pass by reference" in C++

    • @thierrydecorte1632
      @thierrydecorte1632 2 ปีที่แล้ว +4

      @@LSjame "Pass by reference" means you are passing a reference to an object. The fact that the reference (address) is copied into another memory location is not relevant since the term apply to the object being referenced and not the reference itself. It is the same in other languages where passing a pointer/reference means pass by reference even though the pointer itself copied. To pass the pointer itself by reference would require a pointer of pointer.
      As a programmer, if you tell me I'm getting an object by value, I would assume that I'm getting a "copy" of the object and not the same object that was passed by the method caller.

  • @JsinVibe
    @JsinVibe 2 ปีที่แล้ว

    This is such a great video!! Thank you!

  • @jagadeeshgurana4490
    @jagadeeshgurana4490 2 ปีที่แล้ว +1

    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❣

    • @ravireddyism
      @ravireddyism ปีที่แล้ว

      Bas abhi Daal kaakey soojaav bachhe

  • @stephenweber33
    @stephenweber33 2 ปีที่แล้ว

    I really love your racecar voice explaining. I remember distinctly the same issue alone years ago working mostly with python. And no one talks about cheese ,, REAL Cheese ,, not memory cheese as fast as you in real life successfully!

  • @benkimoon
    @benkimoon 2 ปีที่แล้ว +45

    you are THE Java professor everyone is looking for :)

  • @nitfitnit
    @nitfitnit 2 ปีที่แล้ว

    Very clear, great video!

  • @FukSN
    @FukSN 2 ปีที่แล้ว +5

    Superb!
    Haven't seen many videos explaining this and it's really useful to know.
    I have just discovered you recently John and have to say your content is high quality., well explained and useful.
    Thanks 👍

  • @b1tbanger
    @b1tbanger 2 ปีที่แล้ว +8

    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.

  • @renanaoki714
    @renanaoki714 10 หลายเดือนก่อน

    Thanks for the explanation!

  • @uchennannamani5795
    @uchennannamani5795 2 ปีที่แล้ว

    Your videos are great....... good job John

  • @mohamedtoba8361
    @mohamedtoba8361 2 ปีที่แล้ว +2

    Thank you very much for your efforts and I hope you make a video about dynamic binding in java

  • @boomsandapples2640
    @boomsandapples2640 2 ปีที่แล้ว

    This is a great explanation to a topic that can be a little confusing. Thanks!

  • @elvispontes4165
    @elvispontes4165 ปีที่แล้ว

    your tutorials are simply the best... thanks

  • @kauanmocelin
    @kauanmocelin 2 ปีที่แล้ว

    Nice explanation! A "simple" concept that I already confused sometimes.

  • @sacredfroakie1659
    @sacredfroakie1659 2 ปีที่แล้ว

    I swear you have literally incredible videos bro. I know Iv said it on multiples vids but ima say it again for that youtube algorithmn haha

  • @sxx2491
    @sxx2491 2 ปีที่แล้ว

    Nice contents, really helped me a lot.

  • @flexprods
    @flexprods 2 ปีที่แล้ว

    Nice video, now i understand a bit more about the new operator

  • @dinushachathuranga7657
    @dinushachathuranga7657 2 หลายเดือนก่อน

    Thanks a lot for the correct and clear explanation❤❤

  • @dimitrisgangas2897
    @dimitrisgangas2897 2 ปีที่แล้ว

    Excellent explanation!

  • @MrDavidjRay
    @MrDavidjRay ปีที่แล้ว

    John you are the absolute best thank you!

  • @dllm3tommy741
    @dllm3tommy741 9 หลายเดือนก่อน

    Thanks for the video

  • @_danl6327
    @_danl6327 2 ปีที่แล้ว

    Thanks for clear explanation

  • @Johnny-tz2dx
    @Johnny-tz2dx 2 ปีที่แล้ว

    love your videos!!!

  • @christopherfrog2371
    @christopherfrog2371 2 ปีที่แล้ว +3

    I really envy your abillity to share knowledge so it's all so simple to understand :)
    Great job, keep it up!

  • @sreeshakv5405
    @sreeshakv5405 ปีที่แล้ว

    Great information.. Thank you sir

  • @bwprogrammers874
    @bwprogrammers874 2 ปีที่แล้ว

    You are the best John.

  • @libertymedicalcommunicatio4908
    @libertymedicalcommunicatio4908 2 ปีที่แล้ว

    Liking sharing and commenting (and watching all the way through)

  • @kirumaqq
    @kirumaqq 11 หลายเดือนก่อน

    Great video thanks

  • @Bill-gc9bt
    @Bill-gc9bt 3 หลายเดือนก่อน

    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.

  • @vigneshparameshwaran4921
    @vigneshparameshwaran4921 ปีที่แล้ว

    thanks! great explanation

  • @temuryakhyoev5922
    @temuryakhyoev5922 2 ปีที่แล้ว

    For the moment the best channel for learning Java

  • @suryajit7
    @suryajit7 2 ปีที่แล้ว

    the clarity you get by watching Johns video (ta daaa)

  • @yusufmohdsuhair4472
    @yusufmohdsuhair4472 2 ปีที่แล้ว

    love your vid!

  • @spudhead169
    @spudhead169 2 ปีที่แล้ว +1

    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.

  • @IluSsIoNnN
    @IluSsIoNnN 2 ปีที่แล้ว

    Thank you !

  • @HaveAGreatDayStranger
    @HaveAGreatDayStranger 2 ปีที่แล้ว +11

    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?

    • @yahelbraun5471
      @yahelbraun5471 2 ปีที่แล้ว +1

      A "real" reference is an alias of the object.
      Meaning, assume:
      Cheese myCheese = new Cheese();
      Now myCheese in pointing to that object.
      If we pass myCheese to a function in C++ by a reference, it gives myCheese another name, an alias (not copying the memory address that will make another pointer to the object).

    • @HaveAGreatDayStranger
      @HaveAGreatDayStranger 2 ปีที่แล้ว

      @@yahelbraun5471 exactly, which is why i think its frivelous to try and export a C++ concept to other languages. Its meaningless to ask whether some language is pass by value or pass by reference.

    • @CodingWithJohn
      @CodingWithJohn  2 ปีที่แล้ว +3

      You're right that a lot of the argument for whether something is pass by reference or value is less meaningful than it was for older languages. That said, I know this can be a question asked in settings like entry level Java programming jobs, and it helps to be able to respond with a good understanding of what's going on underneath.

    • @LSjame
      @LSjame 2 ปีที่แล้ว +1

      You are missing that pass-by-reference and pass-by-value are descriptions of how a function/method handles incoming parameters, not a description of what data types you are passing.
      In pass-by-reference, a local parameter has the same memory address as the external variable that was passed in.
      In pass-by-value, a local parameter has a different memory address than the external variable that was passed in.
      When we pass the myCheese variable to the function in the video, the variable "cheese" is stored at a different location in memory than the original variable myCheese.

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว

      @@LSjame Yes.

  • @CalvinL.Stevens
    @CalvinL.Stevens ปีที่แล้ว

    If I had this kind of content available at the time, I wouldn't have had to repeat my Programming 2 exam at university 2 times.

  • @pejko89
    @pejko89 2 ปีที่แล้ว

    How lucky am I to learn this for free. Thank you so much!

  • @radiosparrow851
    @radiosparrow851 2 ปีที่แล้ว +2

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

    • @LSjame
      @LSjame 2 ปีที่แล้ว

      In a pass-by-reference language, the following two functions do the same thing. Var refers to the same spot in memory as x.
      int x = 10;
      void function(int var) { var += 1; }
      int x = 10;
      void function2() { x += 1;}

    • @radiosparrow851
      @radiosparrow851 2 ปีที่แล้ว

      @@LSjame right, so leaving aside primitive passing, even though in your reply, it's int x, I presume it's meant as an object by context.
      so for objects:
      "pass by value" is like you write down an address on a piece of paper for me and I copied the address by noting it down in my own notebook.
      "pass by reference" is like you write down an address on a piece of paper and give that piece of paper to me.
      so it actually has nothing to do with the value (the destination at the address), it's about how to handle the reference (the piece of paper where you wrote the address on).
      which also means, for objects, unless you use the keyword 'new', otherwise it doesn't matter practically. (which probably why you said in the video, it appears like a "pass by reference"), you either take that piece of paper or follow the information in your own notebook, you still end up at the same destination.

  • @avinashsakroji1811
    @avinashsakroji1811 2 ปีที่แล้ว +2

    Thanks for being so clear and precise. ❤️

  • @Rudxain
    @Rudxain 2 ปีที่แล้ว +1

    Pass by value is what happens when you download an image. Pass by reference is when you buy an NFT that points to the same image

  • @69k_gold
    @69k_gold ปีที่แล้ว

    It's actually pretty easy to understand and makes more sense than that of other languages.

  • @ensarthewicked
    @ensarthewicked 3 หลายเดือนก่อน

    I thought I forgot to change playback speed xd. you got me in the first half sir, not gonna lie

  • @brunomonteiro3646
    @brunomonteiro3646 ปีที่แล้ว

    John is right here. I know it sound pedantic, but this behaviour is ACTUALLY different than a "true" pass by reference, where no copies at all are made and the function cannot make the parameter point to something else without affecting the original one.

  • @leoniaklebanov2502
    @leoniaklebanov2502 2 ปีที่แล้ว

    Awesome!

  • @v01d_r34l1ty
    @v01d_r34l1ty 2 ปีที่แล้ว +4

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

    • @D0Samp
      @D0Samp 2 ปีที่แล้ว

      The main point is that Java does not have references *to* references (or references to primitive types without a boxing class). As an example, you can't pass a String *variable* (as the allocated space for storing the reference to a String object) to a method as an "out" parameter and have it filled with another String reference on return, which is what "passing by reference" accomplishes in other high-level programming languages that don't have "pointers" either. References (and primitive types) are always copied, which could be described as "passing by value with a layer of indirection", which doesn't help with the confusion at all. Especially since "reference" in the context of Java is the technical equivalent of a pointer to a specific position in the heap and the actual data can still be modified by everyone who knows where it is, as long as the language permits it.

    • @v01d_r34l1ty
      @v01d_r34l1ty 2 ปีที่แล้ว +1

      @@D0Samp yeah that’s confusing. It’s all name scheming, in essence it’s still just doing pass by reference from what I’m gathering.

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว

      @@v01d_r34l1ty No, it is not. It is pass by value. Here is an example which hopefully illustrates it.
      Let's say you have an array and you pass that array to a void method.
      The void method increases the number of elements of the array. What do you think happens outside of that method? The array length remains the same, because Java is pass by value.
      Here is the example.
      In the main method you have:
      int[] array = {0, 1, 2, 3};
      doSomething(array);
      Where the body and definition of the doSomething method are as following
      public static void doSomething(int[] array){
      array = new int[10];
      for(int i=0; i

    • @v01d_r34l1ty
      @v01d_r34l1ty 2 ปีที่แล้ว

      @@smrtfasizmu6161 sorry for the late response, but both C/C++ and Java treat arrays more as pointers. So “=“ will change the address and “[]” will dereference based on an index (product of x and the size of 1 element). Believe arrays are the most common reason to get a NullPtrException in Java, but tbf I haven’t touched either language in 2 months cuz I’ve been at BMT so I’m a little out of the loop right now. Essentially pass by reference is meant for normal variables, say a variable that is technically a pointer being passed by value but being treated as if it’s a pointer actively being dereferenced when utilized within the scope. But officially Java can call the operation whatever it wants technically speaking since they have jurisdiction over the terminology only in regards to their language.

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว

      @@v01d_r34l1ty I never claimed otherwise. I said that array variables hold the memory address both in C and java, then passing an array by memory address is pass by value, not pass by reference. If when we pass an array, we actually pass the memory address where the array variable is stored, then that would be pass by reference, because we are passing a reference to the array variable (and yes that array variable itself holds a memory address of the start of the array).

  • @bobbobthingymibob
    @bobbobthingymibob 2 ปีที่แล้ว +2

    I work with a java card, we always pass the object reference, this is decoded to an address 'when needed', as in the background we can perform defragmentation, ie. Object addresses can move. Primitives by value, objects by reference token.

    • @hoen3561
      @hoen3561 2 ปีที่แล้ว

      by reference actually means that it's passing a pointer by value

    • @aleksey8530
      @aleksey8530 ปีที่แล้ว

      @@hoen3561 and where isn't so? For C++ and C. show me example)

    • @bobbobthingymibob
      @bobbobthingymibob ปีที่แล้ว

      @@hoen3561 I think the answer from Jan Bebendorf makes it clear java passes a reference token not a pure pointer to allow for defragmentation.

  • @anujpotdar3529
    @anujpotdar3529 2 ปีที่แล้ว +2

    The value that Java passes each time in the context of call by value is the address of the said object. Have I understood this correctly?
    Edit: Btw, once again a great video as always 🙃

  • @sivaram3482
    @sivaram3482 2 ปีที่แล้ว +1

    I addicted to your videos John

    • @CodingWithJohn
      @CodingWithJohn  2 ปีที่แล้ว +5

      I better make more then! Don't want anyone going through withdrawals

  • @limx6065
    @limx6065 2 ปีที่แล้ว +1

    this video did not preface by defining what is pass by reference and by value. i could have said java passes reference of the [object] or passes value which is the [reference of the object] and meant the same thing. in other words, in the parameter position, what the argument was before in the caller is the same as the variable in the callee.

    • @luckyluckydog123
      @luckyluckydog123 2 ปีที่แล้ว

      I agree. IMO the explanation of the mechanism is clear, but the naming and general context don't make sense to me. Specifically:
      1. He doesn't define what he means by "pass by reference" and "pass by value", so the whole discussion is moot. To me, "pass by value" means that the caller makes a copy in memory of the data to be passed and gives to the called method the memory address of the copy. In this scenario one cannot modify the original data, only its copy. And to me, "pass by reference" means no copy is made and the memory address of the original data is passed.
      2. According to the definitions above (which may or may not be the relevant ones), Java is "pass by reference" for objects (as illustrated in the video), but it is "pass by value" for primitives (int, Integer, String, etc).
      So if you have something like
      public static void main(String[] args) {
      int i = 5;
      increment(i);
      System.out.println(" i = " + i);
      }
      static void increment(int k) {k++;}
      then output will be 5, not 6 (the "increment" method acted on its own copy of the data, so it has no effect outside its function scope).
      He didn't mentioned that primitives behave differently... so I can't see how saying 'it's always by value, because you always pass the value of the memory address' is a useful definition.

  • @mohamedhesham6008
    @mohamedhesham6008 2 ปีที่แล้ว

    you are a genius thank you

  • @Catalyst313
    @Catalyst313 2 ปีที่แล้ว

    Nice work B)

  • @Lucas-sw5js
    @Lucas-sw5js 2 ปีที่แล้ว

    I see you point and i agree John.
    Now the question is: is there any language that truly passes the object to the method?
    I mean, that you can change the original object address from inside? 🤔

  • @SanchitSnehashish
    @SanchitSnehashish 2 ปีที่แล้ว +1

    Great lesson, professor!
    I just have one question. Is this the same for data types and their wrapper classes? "int" stores an integer value in memory but an object of Integer class stores the address of memory where the integer value is stored?

    • @andreffrosa
      @andreffrosa 2 ปีที่แล้ว +2

      int stores an integer in the stack (i.e., the variable itself) and Integer stores an reference/address in the stack to a portion of memory in the heap that stores an integer. Its like an "indirect" int

  • @leonzer8257
    @leonzer8257 2 ปีที่แล้ว

    Perfect!

  • @natinaelfekadu2744
    @natinaelfekadu2744 2 ปีที่แล้ว

    I
    am loving java because of you

  • @omaral-dahrawy1134
    @omaral-dahrawy1134 9 หลายเดือนก่อน

    Amazing explanation as usual. I have one question though, if I pass a String to a method that adds a symbol '#' to the end of the String, the original String still isn't affected. Strings are non-primitives so according to this video the value of the original String should be changed, just like the levelOfStinkiness changes.

  • @smaug9833
    @smaug9833 2 ปีที่แล้ว

    You don't have to worry about pass by value or pass by reference doesn't matter at all as long as you make your function always return something and use that for further implementation. Which I do, I don't care if it's best practice or not.

  • @habtamusium8646
    @habtamusium8646 ปีที่แล้ว

    thanks !

  • @amirbabazadeh304
    @amirbabazadeh304 6 หลายเดือนก่อน

    hi John. i tries it with int type but i got two different values in main method and another method. would you please explain it? is it for being immutable?

  • @mehnaazmohiuddin
    @mehnaazmohiuddin 8 หลายเดือนก่อน

    Ya same pass by value is not a good term at all. After 10-12 years of knowing java . a pop up quiz just of pass by value / pass of reference tricked me into going delulu over my career . But your video bought back my peace

  • @ukaszr1560
    @ukaszr1560 2 ปีที่แล้ว +1

    What about something like:
    void main() {
    String zText = "";
    fillString(zText);
    printf(zText);
    }
    void fillString(String zText) {
    zText += "foo";
    }
    What is the result and why is that ?

    • @dicousdev2592
      @dicousdev2592 4 หลายเดือนก่อน

      Good question! String in Java is immutable, if we try to concatenate something with String, Java will create a new object as is the case in the code. So the result will always be an Empty String

  • @tusharchouhan1858
    @tusharchouhan1858 2 ปีที่แล้ว

    Thank you

  • @pedroalbertogomes3809
    @pedroalbertogomes3809 2 ปีที่แล้ว

    Nice video

  • @isotoxin
    @isotoxin 2 ปีที่แล้ว

    I'm thinking about this as a "passes the value of an whole object".

  • @dotanon
    @dotanon ปีที่แล้ว

    While I fully understand the underlying technical reasons that make people always stress that Java is ALWAYS pass by value, and this isn't aimed at you (your explanation was very good and easy to digest), but man, it is INCREDIBLY misleading for a beginner to try to look into this. Hearing that it's always pass by value to me intuitively makes me think I am manipulating a copy of an object and will need to return a value and store it in a variable in order for a method to actually affect objects in its argument. And to then add that references are passed by value feels like tiptoeing around what people are actually wanting to know, which is the practical considerations necessary to write code.
    I spent some time yesterday reading responses to similar questions on Stack Overflow and it just made me extra bloody confused, because in the middle of decent answers there are people who simply say "That's incorrect, Java is always pass by value" with no further explanation, which just makes any beginner reading it confused and begin to doubt themselves.
    To me it seems intuitive to call what is happening in Java "passing by reference". Because an address is in essence a reference to some object.
    Anyway, this video (and the lively debates in the comments) has given me a much better understanding at least, so thank you :)

  • @louiemunoz
    @louiemunoz 2 ปีที่แล้ว

    thanks

  • @VinyZikss
    @VinyZikss หลายเดือนก่อน

    There's so much Cheese that the word started looking funny and wrong by the end 😂

  • @codercoder7270
    @codercoder7270 2 ปีที่แล้ว

    can you explain differences between instance and object? with examples

  • @zekumoru
    @zekumoru 2 ปีที่แล้ว

    So basically Java objects are comparable to pointer variables in C, right?

  • @jarlfenrir
    @jarlfenrir 2 ปีที่แล้ว +2

    I was taught that java passes objects only by reference, so I find that explanation a bit confusing. Maybe you should do same stuff in C++ to show when java behaves similarly and when differently?
    In C++ when you pass by value, your whole object and variable pointing to it are copied. When you pass by reference I believe your variable is copied, but object is not (haven't written in C++ for ages), so... it's the same behaviour as in Java. So why inventing something like "passing by value but only reference, not object" instead of just saying "passing by reference"?

    • @himanish4541
      @himanish4541 2 ปีที่แล้ว +2

      @jarlfenrir that's my point exactly.
      As far as I understood before this video, objects in java are essentially passed by reference.
      If what is being said in this video means pass by value, what would pass by reference look like?

    • @Abstractor21
      @Abstractor21 2 ปีที่แล้ว +1

      ​@@himanish4541 this is what we've originally known as pass by reference. He says that its always pass by value because the adress of the object is always pass by value. for me, the name doesnt matter because you can still think this value as a reference to your object

  • @suvraneelsaha8973
    @suvraneelsaha8973 2 ปีที่แล้ว

    Im a beginner in java can anybody tell me what is cheese object Great video totally understood .
    you are creating a new variable in the function / method not accessing or modifying the actually passed var

  • @gustavobauer6543
    @gustavobauer6543 2 ปีที่แล้ว +2

    Totally agree with you, but the only thing that I could not figure out is why there is such distinction between pass by value and pass by reference since, even in languages like c there is only passing by value, since the data that you are actually passing is simply the memory address
    I believe its just a simplification to make the concept easier for the students to wrap their heads around it, what do you think?

    • @fredoverflow
      @fredoverflow 2 ปีที่แล้ว

      Other languages actually offer both path by value and pass by reference, e.g. C# and C++.
      Java does not, and that was a conscious design decision to keep things simple.

    • @jarlfenrir
      @jarlfenrir 2 ปีที่แล้ว +1

      In C you have no references, but in C++ passing by reference and value means a huge difference. Passing by reference basically works the way he described in the video how java works, but passing by value makes a copy of whole object.

    • @gustavobauer6543
      @gustavobauer6543 2 ปีที่แล้ว

      @@jarlfenrir Yes when I said that I meant in like, c, Java and more modern interpreted languages, I especially didnt mention c++ or rust because i knew they handled references in a different way.
      I said that because when I learnt C in college, my professor took like a day to explain what passage by reference is, when there is no such thing, you até always passing by value even If It is a pointer

    • @aleksey8530
      @aleksey8530 ปีที่แล้ว

      @@jarlfenrir But we don't have a strict rules for reference. I can make pointer wrapper and it will work like reference. And such C++ compiler will work as should using standard. Also we can't change refreneces in C++ because of they always const. So, the java case 'pass by reference' doesn't make any sense. We can't produce 'pass by reference' in C++) I mean value which java make for 'pass by reference'

  • @pabloaristimuno9447
    @pabloaristimuno9447 2 ปีที่แล้ว

    So clear and complete! Thanks a lot for your content

  • @AsifAliyev1988
    @AsifAliyev1988 ปีที่แล้ว

    Hey man, give us half a second between the sentences to process information. Other than that love your channel

  • @gauravkohirkar
    @gauravkohirkar 2 ปีที่แล้ว

    Thanks TH-cam for pointing my reference to this video..

  • @davidkeimer5474
    @davidkeimer5474 2 ปีที่แล้ว +1

    Good Video, but you should additionally have explained what pass by reference would mean. One could say, that the memory address of an object actually is nothing else than the reference to that object.

  • @StephenMoreira
    @StephenMoreira ปีที่แล้ว

    Weird. I considered what you just explained to be pass by reference, reference being the memory address being passed around...maybe conceptually confused it for a long time.

  • @gamerbynight1
    @gamerbynight1 2 หลายเดือนก่อน

    Great explanation! Whiteboards always help lol

  • @marcello4258
    @marcello4258 2 ปีที่แล้ว

    And don't forget.. strings are also objects hence Holding the address

  • @DzwiekiOtchlani
    @DzwiekiOtchlani ปีที่แล้ว

    So, after increaseStinkiness function scope, the cheese memory adress stays the same as it used to be before the function call, doesn’t it? 🧐

  • @jackofnotrades15
    @jackofnotrades15 2 ปีที่แล้ว

    Hi, please do a video on java nio

  • @motherfucc
    @motherfucc 2 ปีที่แล้ว

    Im kinda curious, how else would you be able to pass a reference, other than by its value? Is there any difference between reference itself and its hard copy, since they both resolve to same memory address and therefore are indistinguishable, and therefore hold the same value? (other than the fact that the reference in java cannot be overridden, but how does that relate to value? This is more of a question of mutability of that value) So, does it make any sense to call this "pass by value"? If so, then are all languages technically "pass by value"?

    • @smrtfasizmu6161
      @smrtfasizmu6161 2 ปีที่แล้ว

      C++ can be pass by reference. I can also imagine a language which has pass by reference. Such a language, when it is compiled, passes both the stack memory location (or heap memory location) of its arguments and the content of what's in the stack/heap.
      When you write in C and you pass a pointer (memory address) to a function, that pointer is also stored in the stack (or in the heap), you are not passing the memory location on the stack/heap where the variable that you pass to a function is.
      I can make machine code which will have functions that are truly pass by reference.

  • @ivanchl
    @ivanchl 6 หลายเดือนก่อน

    Why does the null have no effect on the referenced array in the memory since it is pointing to the same location in memory?
    public static void main(String[] args) {
    int[] array = {1,2,3};
    changeArray(array);
    System.out.println(Arrays.toString(array));
    clearArray(array);
    System.out.println(Arrays.toString(array));
    }
    private static void changeArray(int[]array){
    array[1] = 200;
    }
    private static void clearArray(int[]array){
    array=null;
    }
    }
    Console output: [1, 200, 3] [1, 200, 3]

  • @kaledbrahmi3442
    @kaledbrahmi3442 2 ปีที่แล้ว +1

    Oh this is cool

  • @Infinitesap
    @Infinitesap 2 ปีที่แล้ว

    What happens then when the value is not an object? Where is the reference then (pointing to)? I assume that it will point to the address, but how of not through a reference - which a primitive doesn't have.

  • @adelhatary7473
    @adelhatary7473 2 ปีที่แล้ว

    Please can you do Spring framework course