File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes  string concatenation with integer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark " string concatenation with integer" Watch " string concatenation with integer" New topic

string concatenation with integer

puneet chaturvedi

Joined: Apr 22, 2013
Posts: 4
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

Joined: May 30, 2012
Posts: 679
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

Joined: Jul 09, 2001
Posts: 1183

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.


William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
ujjawal rohra
Ranch Hand

Joined: Mar 20, 2010
Posts: 105
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..


drac yang
Ranch Hand

Joined: Apr 19, 2013
Posts: 62
pass by value mechanism applies even if the parameter is of reference type, only means different variables respectively store the same referenced object.

science belief, great bioscience!
James X Peterson
Whizlabs Java Support
Ranch Hand

Joined: Feb 26, 2013
Posts: 158
Hi puneet chaturvedi,

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

I agree. Here's the link:
subject: string concatenation with integer
It's not a secret anymore!