Phân biệt tham chiếu và tham trị trong java

Written by IT Phú Trần on 16/03/2017 in Câu hỏi phỏng vấn and LẬP TRÌNH JAVA with 80 comments.

Tham chiếu và tham trị trong java rất dễ gây nhầm lẫn cho các bạn mới học,kể cả các lập trình viên code lâu năm cũng đôi lúc có sự nhầm lẫn về sự phân biệt  khái niệm tham chiếu và tham trị trong java.Trong bài này,tôi sẽ chia sẻ theo kinh nghiệm cũng như hiểu biết của mình để các bạn tham khảo cùng thảo luận về vấn đề trên.

Trong JAVA có 2 loại kiểu dữ liệu: cơ bản và tham chiếu :
– Kiểu cơ bản : Số nguyên, số thực, kí tự , logic
– Kiểu tham chiếu : Kiểu mảng, kiểu lớp đối tượng Class, kiểu Interface

Truyền tham trị là gì?

Khi các bạn truyền tham trị thì trình biên dịch sẽ tạo 1 bản sao và sau đó truyền bản sao đó vào nơi muốn truyền, vì vậy mà mọi thay đổi sẽ sảy ra trên bản sao này và ko ảnh hưởng đến biến gốc.

Truyền tham chiếu là gì?

Truyền tham chiếu thì các bạn sẽ truyền ngay địa chỉ hay gọi là chính cái biến đó vào nơi cần truyền, nên ở trong hàm mà mình truyền vào có thay đổi gì thì biến ngoài cũng thay đổi theo.


Để làm rõ hơn về vấn đề này,tôi sẽ vào một ví dụ để các bạn dễ hình dùng như sau :

1.Ví dụ về truyền kiểu dữ liệu nguyên thủy :

Class  TestDemo1.java :

Khi bạn truyền tham số cho hàm trong Java, Java sẽ tạo ra một bản sao của biến và truyền vào phương thức đó. Vậy nên khi thực thi hàm chỉ có bản sao bị ảnh hưởng mà biến không hề bị ảnh hưởng.Vì lý do vậy nên khi chạy trường trình thì giá trị của biến number vẫn bằng 10.

2. Java không có kiểu truyền tham chiếu (reference)

Thường thì chúng ta sẽ nghĩ rằng Kiểu dữ liệu cơ sở được truyền theo tham trị, kiểu object được truyền theo tham chiếu. Ok.Nhưng đó là một sự nhầm lẫn.

Khi các bạn truyền một biến có kiểu object vào một hàm thì lúc đó có nghĩa ta đã truyền giá trị của biến đó để sử dụng trong hàm, chứ không phải truyền đối tượng được biến đó tham chiếu tới. Vậy nên việc thay đổi giá trị của biến có kiểu object này bằng cách gán cho một biến kiểu object khác thì object được tham chiếu đến lúc đầu không bị ảnh hưởng, chỉ khi sử dụng các method của chính các object được tham chiếu này thì dữ liệu của object mới được thay đổi sau khi ra khỏi hàm.

Các bạn hãy xem ví dụ dưới đây : 

Qua ví dụ này,các bạn thấy được rằng với Java không có tryền tham chiếu như thấy ở trường hợp 1 sử dụng phương thức change1,chúng ta vẫn lấy được name là “Lan Anh” .Giá trị của biến kiểu object là địa chỉ của object mà biến đó tham chiếu đến đến. Cho nên lúc này việc thay đổi giá trị của biến kiểu object này bằng cách gán cho một biến kiểu object khác thì object được tham chiếu đến lúc đầu không bị ảnh hưởng.

Khi dùng change2 thì lúc này,khi biến tham chiếu đến chúng ta đã thay đổi giá trị ở trong phương thức bằng cách setName lại mà không thông qua một đối tượng tham chiếu tạo ra mới nào,nên lúc này chỉ khi sử dụng các method của chính các object được tham chiếu này thì dữ liệu của object mới được thay đổi sau khi ra khỏi hàm.Vậy kết quả lần lượt sẽ là : “Lan Anh” , “Phú Trần IT”.

80 Responses to “Phân biệt tham chiếu và tham trị trong java

  1. My coder is trying to persuade me to move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress on several websites for
    about a year and am anxious about switching to another platform.
    I have heard great things about blogengine.net. Is there a
    way I can transfer all my wordpress content into it? Any help would be greatly appreciated!

  2. I truly love your site.. Excellent colors & theme. Did you create this site yourself?
    Please reply back as I’m planning to create my very
    own website and want to find out where you got this
    from or what the theme is called. Kudos!

  3. Thanks for every other fantastic article. Where else may
    just anybody get that type of information in such an ideal
    approach of writing? I’ve a presentation next week, and I am on the search for such info.

  4. Hey, I think your blog might be having browser compatibility issues.

    When I look at your blog site in Chrome, it looks fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other then that, terrific
    blog!

  5. Have you ever thought about publishing an e-book
    or guest authoring on other blogs? I have a blog based on the same information you discuss and would love to
    have you share some stories/information. I know my visitors would appreciate your work.
    If you are even remotely interested, feel free to shoot me an e mail.

  6. Woah! I’m really loving the template/theme of this blog.

    It’s simple, yet effective. A lot of times it’s
    tough to get that “perfect balance” between user friendliness
    and visual appearance. I must say you have done a amazing job with this.
    In addition, the blog loads very fast for me on Safari.
    Superb Blog!

  7. Oh my goodness! Amazing article dude! Thank you so much, However
    I am going through problems with your RSS. I don’t know the reason why
    I can’t join it. Is there anybody having similar RSS problems?
    Anyone that knows the answer can you kindly respond? Thanx!!

  8. Do you have a spam problem on this site; I also am a blogger, and I was wondering your situation; many of us have
    developed some nice methods and we are looking to exchange solutions with others, why not shoot me an email if interested.

  9. Hello, i read your blog from time to time and i own a similar one and i was
    just curious if you get a lot of spam feedback? If
    so how do you reduce it, any plugin or anything you can suggest?
    I get so much lately it’s driving me insane so any assistance is very much
    appreciated.

  10. Great site you’ve got here.. It’s difficult to get high quality writing like yours nowadays. I seriously appreciate individuals as if you! Be careful!!

  11. Greetings from Ohio! I’m bored to death at the office and so i chose to check out your blog in my iphone during lunch break. I enjoy the knowledge you provide here and can’t wait to have a look when I return home. I’m shocked at how quick your website loaded on my small mobile .. I’m not using WIFI, just 3G .. Anyhow, superb site!

  12. I just want to mention I’m all new to blogs and definitely loved you’re blog site. Likely I’m planning to bookmark your site . You certainly come with awesome articles. Regards for sharing with us your web page.

  13. I know this web page presents quality depending content and additional data, will there be some other website which provides these data in quality?

  14. Thank you for sharing your thoughts. I really appreciate your efforts and I am waiting for your next
    post thanks once again.

  15. I have mastered some considerations through your website post. One other stuff I would like to convey is that there are plenty of games in the marketplace designed in particular for preschool age little ones. They consist of pattern identification, colors, creatures, and shapes. These normally focus on familiarization as opposed to memorization. This helps to keep children and kids engaged without experiencing like they are studying. Thanks

  16. Pretty nice post. I just stumbled upon your blog and wanted to note that
    We have truly loved surfing around your blog posts. Regardless I’ll be
    subscribing in your feed and I’m hoping you write again soon!

    Also visit my site GilTStrutton

  17. This site certainly has all the information and facts I wanted concerning this subject and didn’t know who to ask.

  18. A further issue is really that video gaming has become one of the all-time biggest forms of fun for people of any age. Kids participate in video games, and also adults do, too. The particular XBox 360 is one of the favorite gaming systems for many who love to have a lot of activities available to them, in addition to who like to experiment with live with other folks all over the world. Thanks for sharing your notions.

  19. Hi! I could have sworn I’ve been to this site before but after going through a few of the articles I realized it’s new to me. Anyways, I’m certainly happy I stumbled upon it and I’ll be book-marking it and checking back regularly!

  20. Hi there mates, pleasant paragraph and nice arguments commented at
    this place, I am in fact enjoying by these.

  21. MetroClick specializes in building completely interactive products like Photo Booth for rental or sale, Touch Screen Kiosks, Large Touch Screen Displays , Monitors, Digital Signages and experiences. With our own hardware production facility and in-house software development teams, we are able to achieve the highest level of customization and versatility for Photo Booths, Touch Screen Kiosks, Touch Screen Monitors and Digital Signage. Visit MetroClick in NYC at http://www.metroclick.com/ or , 121 Varick St, New York, NY 10013, +1 646-843-0888.

  22. I like the helpful information you provide in your articles.
    I will bookmark your weblog and check again here regularly. I’m quite certain I will learn many new stuff right here! Best of luck for the next!

  23. Everything is very open with a very clear explanation of the issues. It was truly informative. Your website is extremely helpful. Many thanks for sharing!

  24. Ahaa, its fastidious discussion concerning this
    article here at this web site, I have read all that, so at
    this time me also commenting at this place.

  25. May I just say what a relief to find a person that actually understands what they’re discussing on the net. You certainly understand how to bring a problem to light and make it important. A lot more people have to look at this and understand this side of the story. I was surprised that you’re not more popular given that you definitely possess the gift.

  26. Hi would you mind stating which blog platform you’re working with?

    I’m planning to start my own blog soon but I’m having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
    The reason I ask is because your layout seems different then most blogs and I’m looking for something
    completely unique. P.S Sorry for getting off-topic but I had to ask!

  27. MetroClick specializes in building completely interactive products like Photo Booth for rental or sale, Touch Screen Kiosks, Large Touch Screen Displays , Monitors, Digital Signages and experiences. With our own hardware production facility and in-house software development teams, we are able to achieve the highest level of customization and versatility for Photo Booths, Touch Screen Kiosks, Touch Screen Monitors and Digital Signage. Visit MetroClick in NYC at http://www.metroclick.com/ or , 121 Varick St, New York, NY 10013, +1 646-843-0888.

  28. After I initially commented I appear to have clicked the -Notify me when new comments are added- checkbox and now every time a comment is added I get 4 emails with the same comment. Is there a means you are able to remove me from that service? Kudos.

  29. I’d like to thank you for the efforts you’ve put in penning this website. I am hoping to check out the same high-grade content from you later on as well. In truth, your creative writing abilities has inspired me to get my very own blog now 😉

  30. Write more, thats all I have to say. Literally,
    it seems as though you relied on the video to make your point.
    You clearly know what youre talking about, why throw away your intelligence on just posting videos to your
    weblog when you could be giving us something enlightening to read?

  31. I really love your site.. Very nice colors & theme. Did you build this website yourself? Please reply back as I’m planning to create my own personal website and would like to learn where you got this from or just what the theme is called. Thanks!

  32. I used to be suggested this website by my cousin. I am not sure whether
    this post is published by him as no person else know
    such detailed about my difficulty. You’re wonderful! Thanks!

    Feel free to surf to my page; DarnellRRill

  33. I simply want to notify you that I am new to putting up a blog and clearly liked your information. Very possible I am going to bookmark your blog post . You seriously have outstanding article information. Admire it for expressing with us your very own internet webpage

  34. Oh my goodness! Awesome article dude! Thanks, However I am having issues with your RSS. I don’t know why I can’t subscribe to it. Is there anybody having similar RSS issues? Anyone who knows the answer can you kindly respond? Thanks!!

  35. Your style is unique compared to other folks I have read stuff from. Many thanks for posting when you’ve got the opportunity, Guess I’ll just book mark this site.

  36. Attractive section of content. I just stumbled upon your weblog and in accession capital
    to assert that I get actually enjoyed account your blog posts.
    Any way I will be subscribing to your augment and even I achievement you access consistently rapidly.

  37. Your method of explaining the whole thing in this post is in fact pleasant, everyone be capable of effortlessly be aware of it, Thanks a lot.

  38. Everything is very open with a very clear explanation of the issues. It was really informative. Your site is very useful. Thanks for sharing!

  39. I seriously love your site.. Great colors & theme. Did you create this web site yourself? Please reply back as I’m trying to create my own site and would love to learn where you got this from or just what the theme is called. Thanks.

  40. I’ve been absent for a while, but now I remember why I used to love this site. Thank you, I’ll try and check back more often. How frequently you update your web site?

  41. Howdy! I could have sworn I’ve visited this web site before but after looking at many of the articles I realized it’s new to me. Anyhow, I’m definitely delighted I came across it and I’ll be book-marking it and checking back frequently.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *