Pass by Reference in java

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • rajujrk
    New Member
    • Aug 2008
    • 107

    Pass by Reference in java

    Hai All,

    I have to set of Programs, Both deals with Object, One is with Predefined Object and another one is User Defined Object.

    Program #1

    Code:
    class MyPass
    {
    	Integer i=new Integer(100);
    	public void pass(){
    		
    		System.out.println(i);
    		go(i);
    		System.out.println(i);
    	}
    	public void go(Integer x){
    		System.out.println(x);
    		x=200;
    		System.out.println(x);
    	}
    	public static void main(String arg[]){
    		MyPass mp=new MyPass();
    		mp.pass();
    	}
    }
    
    OUTPUT:
    
    100
    100
    200
    100

    Program #2

    Code:
    class Refer
    {
    	String name;
    }
    class PassByReference
    {
    	void calling()
    	{
    		Refer r=new Refer();
    		r.name="abc";
    		System.out.println("Before"+r.name);
    		called(r);
    		System.out.println("After"+r.name);
    	}
    	void called(Refer s)
    	{
    		s.name="xyz";
    		System.out.println("Inside"+s.name);
    	}
    	public static void main(String args[])
    	{
    		PassByReference p=new PassByReference();
    		p.calling();
    	}
    }
    
    OUTPUT:
    
    Beforeabc
    Insidexyz
    Afterxyz
    In Prg #1 object value doesnt changed
    In Prg #2 Change the value
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    Sorry, what exactly is the question?

    Comment

    • rajujrk
      New Member
      • Aug 2008
      • 107

      #3
      Originally posted by jkmyoung
      Sorry, what exactly is the question?
      My Question is, Both Programs Pass the reference, but in first program the value doesn't changed, in second one it changed, what happening inside in this programs? how these two code executes?

      Comment

      • Dheeraj Joshi
        Recognized Expert Top Contributor
        • Jul 2009
        • 1129

        #4
        Code:
        System.out.println("1" +i);
        go(i);
        System.out.println("4" +i);
        i = 100.
        Prints 100
        Goes to go function
        Prints 100
        Makes x = 200
        Prints 200
        Comes out of loop
        Prints 100

        200 value of x is available inside the function go. Not in the function who is calling it.

        Regards
        Dheeraj Joshi

        Comment

        • Dheeraj Joshi
          Recognized Expert Top Contributor
          • Jul 2009
          • 1129

          #5
          In second example, You are passing the object to the function whose scope is at class level.

          Regards
          Dheeraj Joshi

          Comment

          Working...