Results 1 to 5 of 5

Thread: what is java equivalent to this c++ code...

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    what is java equivalent to this c++ code...

    Code:
    void swap(int & a, int & b)
    {
         int temp;
         temp = a;
         a = b;
         b = temp;
    }
    basically, how do i pass an integer variable by reference so I can change the value of the parameter variables after the function call.

  2. #2
    Fanatic Member x-ice's Avatar
    Join Date
    Mar 2004
    Location
    UK
    Posts
    671

    Re: what is java equivalent to this c++ code...

    There isn't that much difference between C and Java code.

    Code:
    public void swap(int a, int b)
    {
         int temp;
         temp = a;
         a = b;
         b = temp;
    }

  3. #3
    Fanatic Member sql_lall's Avatar
    Join Date
    Jul 2002
    Location
    Up Above (i.e. AUS)
    Posts
    571

    Re: what is java equivalent to this c++ code...

    That's not quite the same, because in that Java the values passed to the function will not be swapped.
    The problem is that primative data types in Java (such as int) are not used as pointers, whereas classes are.
    I believe there may be a library call, but if not you can wrap the values up as Integers (i.e. instances of the class Integer), pass these and unwrap, but that's a lot of extra code. I think Java 5 might do some of this for you with autoboxing, if you write a thing to swap two Objects.
    sql_lall

  4. #4
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Re: what is java equivalent to this c++ code...

    Swapping mostly used in arrays, pass the array "By ref", and the locations of the two vars to be swaped

    private void swap(int[] array,int locA,int locB){
    int tmp=array[locA];
    array[locA]=array[locB];
    array[locB]=tmp;
    }
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  5. #5

    Thread Starter
    Frenzied Member
    Join Date
    Jul 2005
    Posts
    1,168

    Re: what is java equivalent to this c++ code...

    thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width