• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string concatenation with integer

 
puneet chaturvedi
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code :
the output of above program is :
dostuff x5
dostuff x 2nd6
main x=5
i am not clear that even the value of x is incremented to 6 , but it print 5 at the end why ?
 
Stuart A. Burkett
Ranch Hand
Posts: 679
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because java is pass by value. There is no code there that changes the value of the x variable declared on line 4.
 
Dan Drillich
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Puneet,

Does Java pass by reference or by value? says -

The key with pass by value is that the method will not receive the actual variable that is being passed - but just a copy of the value being stored inside the variable.


Regards,
Dan
 
ujjawal rohra
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you pass a value of a primitive to a method and manipulate it inside the called method, the change is not reflected inside the calling method. This is because Java uses pass by value method.
If you want the incremented value in the calling mehod then you shound return the incremented value from the method called and store it in a variable inside the calling method(main, in your case) as below:

y will have a value 6.

and your method definition becomes:



Hope this helps..

Cheers!!!
 
drac yang
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
pass by value mechanism applies even if the parameter is of reference type, only means different variables respectively store the same referenced object.
 
James X Peterson
Whizlabs Java Support
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi puneet chaturvedi,

you have used pass by value so the change to variable x will not effect to variable x in main method.

Regards,
James
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic