Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within OCPJP
Search Coderanch
Advance search
Google search
Register / Login
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
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Jeanne Boyarsky
Ron McLeod
Paul Clapham
Liutauras Vilda
Sheriffs:
paul wheaton
Rob Spoor
Devaka Cooray
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Carey Brown
Frits Walraven
Tim Moores
Bartenders:
Mikalai Zaikin
Forum:
Programmer Certification (OCPJP)
Pass by value for primitives
sandy chauhan
Ranch Hand
Posts: 31
posted 9 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
public class Pass { public static void main(String [] args) { int x = 5; Pass p = new Pass(); p.doStuff(x); System.out.print(" main x = " + x); } void doStuff(int z) { System.out.print(" doStuff z = " + z++); } }
The answer for the above code is 5 5
the value of x does not get updated because it has been passed by value
but is there any way to pass a primitive variable by reference???
Ulf Dittmer
Rancher
Posts: 43081
77
posted 9 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
You can wrap the value into a mutable class, or use an existing class that wraps a mutable integer, like java.util.concurrent.atomic.AtomicInteger. Or have the method return the new value as its result..
Nitin Mah
Greenhorn
Posts: 2
posted 9 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
public class Pass { public static void main(String [] args) { //int x = 5; Pass p = new Pass(); X x = p.new X(5); p.doStuff(x); System.out.print(" main x = " + x.value); } void doStuff(X z) { System.out.print(" doStuff z = " + z.value++); } public class X { int value; X(int i) { this.value=i; } } }
I like you because you always keep good, crunchy cereal in your pantry. This tiny ad agrees:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
string concatenation with integer
Boxing/Unboxing
Query on Wrapper
Wrappers
Wrapper throws NullPointerException, how to correct code
More...