Java is ALWAYS Pass By Value. Here's Why

Поделиться
HTML-код
  • Опубликовано: 27 июл 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 25 дней назад

      This is the best explanation of the crux of the issue

  • @findlestick
    @findlestick 2 года назад +18

    Commenting to assist with RUclips 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!!

  • @asherkhan2656
    @asherkhan2656 2 года назад +1

    Nice short and sweet videos that help reinforce fundamental concepts 👍

  • @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

  • @jeanjacquesbarros
    @jeanjacquesbarros 2 года назад +1

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

  • @nunya1120
    @nunya1120 2 года назад +46

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

  • @mohamedtoba8361
    @mohamedtoba8361 2 года назад +2

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

  • @JsinVibe
    @JsinVibe 2 года назад

    This is such a great video!! Thank you!

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

  • @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++.

  • @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 👍

  • @nitfitnit
    @nitfitnit 2 года назад

    Very clear, great video!

  • @boomsandapples2640
    @boomsandapples2640 2 года назад

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

  • @renanaoki714
    @renanaoki714 10 месяцев назад

    Thanks for the explanation!

  • @elvispontes4165
    @elvispontes4165 Год назад

    your tutorials are simply the best... thanks

  • @uchennannamani5795
    @uchennannamani5795 2 года назад

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

  • @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

  • @kauanmocelin
    @kauanmocelin 2 года назад

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

  • @dinushachathuranga7657
    @dinushachathuranga7657 2 месяца назад

    Thanks a lot for the correct and clear explanation❤❤

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

  • @karentechnologies3990
    @karentechnologies3990 Месяц назад

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

  • @MrDavidjRay
    @MrDavidjRay Год назад

    John you are the absolute best thank you!

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

  • @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

  • @_danl6327
    @_danl6327 2 года назад

    Thanks for clear explanation

  • @dimitrisgangas2897
    @dimitrisgangas2897 2 года назад

    Excellent explanation!

  • @dllm3tommy741
    @dllm3tommy741 9 месяцев назад

    Thanks for the video

  • @sreeshakv5405
    @sreeshakv5405 Год назад

    Great information.. Thank you sir

  • @vigneshparameshwaran4921
    @vigneshparameshwaran4921 Год назад

    thanks! great explanation

  • @Johnny-tz2dx
    @Johnny-tz2dx 2 года назад

    love your videos!!!

  • @bwprogrammers874
    @bwprogrammers874 2 года назад

    You are the best John.

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

  • @kirumaqq
    @kirumaqq 11 месяцев назад

    Great video thanks

  • @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

  • @benkimoon
    @benkimoon 2 года назад +45

    you are THE Java professor everyone is looking for :)

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

  • @temuryakhyoev5922
    @temuryakhyoev5922 2 года назад

    For the moment the best channel for learning Java

  • @IluSsIoNnN
    @IluSsIoNnN 2 года назад

    Thank you !

  • @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

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

  • @libertymedicalcommunicatio4908
    @libertymedicalcommunicatio4908 2 года назад

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

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

  • @codercoder7270
    @codercoder7270 2 года назад

    can you explain differences between instance and object? with examples

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

  • @pejko89
    @pejko89 2 года назад

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

  • @avinashsakroji1811
    @avinashsakroji1811 2 года назад +2

    Thanks for being so clear and precise. ❤️

  • @yusufmohdsuhair4472
    @yusufmohdsuhair4472 2 года назад

    love your vid!

  • @suryajit7
    @suryajit7 2 года назад

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

  • @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?

  • @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? 🤔

  • @69k_gold
    @69k_gold Год назад

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

  • @leoniaklebanov2502
    @leoniaklebanov2502 2 года назад

    Awesome!

  • @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 🙃

  • @mohamedhesham6008
    @mohamedhesham6008 2 года назад

    you are a genius thank you

  • @habtamusium8646
    @habtamusium8646 Год назад

    thanks !

  • @zekumoru
    @zekumoru 2 года назад

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

  • @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

  • @stevenshrii
    @stevenshrii Год назад

    What is the difference between a object, an instance and a pointer?

  • @wassimtahraoui9888
    @wassimtahraoui9888 2 года назад

    does java do the same process for primitive data types?

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

  • @louiemunoz
    @louiemunoz 2 года назад

    thanks

  • @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? 🧐

  • @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

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

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

  • @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

  • @leonzer8257
    @leonzer8257 2 года назад

    Perfect!

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

  • @user-qi4cm6gg9n
    @user-qi4cm6gg9n 10 месяцев назад

    this may be an old video, but does anyone have useful resources regarding how coding interacts with the memory and memory allocation as John showed us on his whiteboard? this is one thing I have always had trouble understanding, and any resources that are concise like this that explain the basics with regards to memory allocation and how coding actually interacts with memory would be greatly appreciated

    • @shanewalsch
      @shanewalsch 4 месяца назад

      You probably should just learn c++😂

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

  • @natinaelfekadu2744
    @natinaelfekadu2744 2 года назад

    I
    am loving java because of you

  • @Aaron31909
    @Aaron31909 2 года назад

    How is this different from pass by reference?

  • @ensarthewicked
    @ensarthewicked 3 месяца назад

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

  • @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'

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

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

  • @adelhatary7473
    @adelhatary7473 2 года назад

    Please can you do Spring framework course

  • @Shakyws143
    @Shakyws143 2 года назад

    How to access and print cheese with 756 then?

  • @tusharchouhan1858
    @tusharchouhan1858 2 года назад

    Thank you

  • @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]

  • @Catalyst313
    @Catalyst313 2 года назад

    Nice work B)

  • @vishalsundararajan1228
    @vishalsundararajan1228 2 года назад

    Use hibernate and the problem becomes double with the level 1 session. setting the chest stinkiness to 756 will fire an update query if the cheese reference is passed

  • @sebastianlenzlinger9291
    @sebastianlenzlinger9291 2 года назад

    I‘m a bit confused. I get how you say what java calls pass by reference is actually also passing a value. But I don‘t get what else pass by reference would be? Can someone help me out? I feel there‘s a good subtle lesson to be learned.

    • @aleksey8530
      @aleksey8530 Год назад

      @@williams322 So, we have that behavior in all languages. But only JAVA call it 'pass by value'. More correct is 'pass by sharing'. Also the example of 'pass by reference' from JAVA doesn't exist in the nature)

  • @pabloaristimuno9447
    @pabloaristimuno9447 2 года назад

    So clear and complete! Thanks a lot for your content

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

  • @jackofnotrades15
    @jackofnotrades15 2 года назад

    Hi, please do a video on java nio

  • @AhmadAhmadi-wb9ny
    @AhmadAhmadi-wb9ny 11 месяцев назад

    why do we use by pass value?

  • @isotoxin
    @isotoxin 2 года назад

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

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

  • @pedroalbertogomes3809
    @pedroalbertogomes3809 2 года назад

    Nice video

  • @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

  • @monisha2144
    @monisha2144 2 года назад

    I think the class Cheese is a java bean. am i correct?

  • @natinaelfekadu2744
    @natinaelfekadu2744 2 года назад

    when i pass reference type like array or object of o a class it works as if it is passed by reference but when try to pass String object it doesn't not work it works as if it is primitivize type
    ,so why is this happening?

    • @fredoverflow
      @fredoverflow 2 года назад

      Assignments to parameters (param = value) never affect the caller, no matter the type. Calling methods on parameters (param.method()) can potentially mutate the object, but String has no mutating methods, i.e. Strings are immutable.

    • @selcuksezer6
      @selcuksezer6 2 года назад

      If you are familiar with C++ you can think it like this. When you are passing a variable, Java passes a copy of its "pointer", i.e. an object referring to the address of the actual variable object. So when you reassign a passed parameter (formal parameter), since the value at the memory address changes, your original parameter (actual parameter) changes as well. However, strings in Java are "immutable", meaning once they are created in the memory, their value cannot be changed. When you reassign your passed parameter to a string, Java creates a new string and your passed parameter holds a pointer to the address of the new string, hence original and passed variables are different.

  • @aaksadeeq
    @aaksadeeq 2 года назад

    You are the best

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