• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Junilu Lacar
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Ganesh Patekar

String - Pass by value/reference

 
Ranch Hand
Posts: 403
2
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose we have the following code:



If I run this code, it still prints "Main". Shouldn't it print Method instead since we are passing the object reference and updating the value at the reference. So, why it is not getting updated?
 
Ranch Hand
Posts: 127
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you call method(String str) your jvm creates a pointer to the actual arguments.

At the line 13:

str = "Method";

You create a new object and the pointer now points to the -new- string "Method". Anyway you can not change the contents of any string instance because strings are inmutable.
 
Bartender
Posts: 708
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
However, if you changed your code to the following, it would print out the line "Entering Method, str is : Main" from the print in method, followed by the line "String is : Method" from the print in main:
public class Test {

 
Ranch Hand
Posts: 392
4
Android Tomcat Server Java
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For your info, Java is pass by value and not pass by reference
 
Marshal
Posts: 65814
250
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...but websites like this one (see No 6) cause confusion because their authros don't know what pass by reference means. As RT says, Java┬« only implements pass by value. Please search this forum and this one for “pass by value” and you should find some more useful information.
 
rubbery bacon. rubbery tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!