• Post Reply Bookmark Topic Watch Topic
  • New Topic

Passing String into method  RSS feed

 
Eric Longhorn
Ranch Hand
Posts: 40
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I already understand that when you pass an object into a method a copy of the reference is made, and if you pass primitives into methods the copy of the value is made.
However, I am not sure about what happens when you pass a String into a method.
I believe that a copy of the String's value is made and passed into the method.

Please correct me if I am wrong.
Thanks in advance.
 
Ivan Pronin
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String is passed by “reference” in Java: here's a good explanation with example code
E.g. this code:

will print "ab";
 
Eric Longhorn
Ranch Hand
Posts: 40
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I figured it out. I ran a little code snippet, and based on the results I believe that whenever you pass a String into a method, a copy of the String is made and passed into the method.

Thanks.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66304
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What lead you to that belief?
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when you pass an object into a method a copy of the reference is made,

Strings are objects that are accessed via references.
 
Eric Longhorn
Ranch Hand
Posts: 40
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Bear Bibeault wrote:What lead you to that belief?

I ran this code:

and it printed out hello, which meant that the original String was not changed.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66304
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does that conclude that the string is copied, or its reference?
 
Eric Longhorn
Ranch Hand
Posts: 40
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OH!

The reference is being copied 
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66304
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Think of an object parameter¹ as a local variable that is initialized with a copy of the passed reference. In this case, a is assigned a copy of the reference in hi.


¹ A String is an object.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!