Results 1 to 4 of 4
- 07-16-2011, 05:40 PM #1
Member
- Join Date
- Apr 2011
- Posts
- 7
- Rep Power
- 0
. confuse that how actually reference is passed to a method ?
i know this code is example of pass by value , so
how to make the same code as pass by reference ?
also explain how and what happens when you alter the same code as i new bie to java and confuse that how actually reference is passed to a method ?
Java Code:class sample { int value = 60; void changeVal(int val) { val=19; System.out.println("inside method" +val); } public static void main(String[] args) { int val = 10; sample s ; s = new sample(50); //System.out.println(" in main method " + s.value); //System.out.println(" in main method " + s1.value); s.changeVal(val); System.out.println(" in main method " + val); } }
- 07-16-2011, 06:18 PM #2
Senior Member
- Join Date
- Nov 2010
- Posts
- 210
- Rep Power
- 3
You can't pass primitive values by reference in Java. You'll have to use objects instead.
Note that this won't work with the built-in Integer class because of auto-unboxing. If you were to use Integer instead of IntWrapper here, the expression i += 5 would create a new Integer with value equal to i+5, and then assign a reference to the new Integer to the local variable i. The original Integer still exists at its original location with an unchanged value.Java Code:public class A { public static void main(String[] args) { IntWrapper i = new IntWrapper(); i.val = 1; addFive(i); System.out.println(i.val); } public static void addFive(IntWrapper i) { i.val += 5; } } class IntWrapper { int val; }Last edited by Iron Lion; 07-16-2011 at 06:28 PM.
- 07-16-2011, 09:00 PM #3
You can't pass any values by reference in Java. All passing is by value. Primitives are passed by value. References are passed by value.You can't pass primitive values by reference in Java.
There's a very good anecdotal explanation here:
JavaRanch Campfire - Cup Size: a Story About Variables
JavaRanch Campfire - Pass By Value, Please
Make sure to read both articles, in the correct order.
db
- 07-17-2011, 04:16 PM #4
Senior Member
- Join Date
- Nov 2010
- Posts
- 210
- Rep Power
- 3
Similar Threads
-
hiding passed parameters using window.location.href = 'params' method
By kulangotski in forum JavaServer Pages (JSP) and JSTLReplies: 0Last Post: 07-01-2011, 12:49 PM -
hi guys , please help me in telling about how Objects are passed by reference. :(
By funkygarzon in forum New To JavaReplies: 3Last Post: 06-14-2011, 09:35 PM -
Method, returning reference to an object
By Saletra in forum New To JavaReplies: 3Last Post: 08-23-2010, 08:22 PM -
entities are passed by value or passed by reference
By syntrax in forum New To JavaReplies: 1Last Post: 12-17-2009, 07:13 AM -
Passing Class Reference to method
By nekt in forum Advanced JavaReplies: 5Last Post: 03-26-2009, 05:08 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks