The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Swapping ints

Posted by Kishori Sharan on January 22, 2001 at 9:43 AM

For swapping the values you cannot use Integer class because the Integer class's objects are immutable. I mean once you have created an Integer object with a value then you cannot change its value. So you cannot use Integer class to swap two int values. Java has a class IntHolder in org.omg.CORBA package which can hold an integer value. Java also exposes the instance variable which holds the integer value. It is
public int value. So you can change the value contained by the IntHolder class directly. So you can use it as below.

////////////////// Test.java
import org.omg.CORBA.* ;

public class Test {

public static void main ( String[] args ) throws Exception {
IntHolder a = new IntHolder ( 10 );
IntHolder b = new IntHolder ( 20 );

System.out.println ( "Before swapping" );
System.out.println ( "a = " + a.value + " b = " + b.value );
swap ( a, b ) ;
System.out.println ( "After swapping" );
System.out.println ( "a = " + a.value + " b = " + b.value );
}

public static void swap ( IntHolder a, IntHolder b ) {
int temp = b.value ;
b.value = a.value ;
a.value = temp ;
}
}




Replies:
  • Swapping ints karthik January 22, 2001 at 10:29 PM (2)
    • A path Ivan Villanueva January 23, 2001 at 4:52 PM (1)
      • Re: karthik January 23, 2001 at 10:00 PM (0)

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us