• 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
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

String - Pass by value/reference

 
Ranch Hand
Posts: 401
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: 122
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 Foreman
Posts: 307
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: 64642
225
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!