• Post Reply Bookmark Topic Watch Topic
  • New Topic

Can anyone please explain below behavior of the code  RSS feed

 
gowthami vatsavayi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



output: A


But when we assign a value its showing below result





output: C



Can anyone explain why this?
 
Tim Cooke
Marshal
Posts: 4041
239
Clojure IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, and welcome to the Ranch!

It's best to UseCodeTags when posting code as it makes it much easier to read. I added them for you this time, see how much better it looks?
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please go through the code with a pencil and write down what you think the state of each variable is after each line. Particularly the variable which prints out as A. Did you expect it to print null? Or throw an Exception?
 
Omkar Shetkar
Ranch Hand
Posts: 100
2
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java is pass-by-value. That means, when a method is called, caller passes a copy of the value of the variable.
In this case, 'm' is a char array reference. When you call doA() method, a copy of array reference is passed and not copy of array.

Now, in the first case, we are setting copy of array reference to null. Hence, there won't be any changes in original copy of array.
In the second case, we are setting first element of array to 'C' using copy of array reference. Hence, this change will reflect in the output.

I hope attached image clears pass-by-value concept.

example.png
[Thumbnail for example.png]
Pictorial representation
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!