aspose file tools
The moose likes Swing / AWT / SWT and the fly likes wrapper class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "wrapper class" Watch "wrapper class" New topic

wrapper class

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
how can i swap values of two integer class by using a functiion.
i.e class swap{
public static void main{
integer i=new integer(2);
integer j=new integer(5)
System.out.println(i+ " " +j);
swap(integer i,integer j)
Jesper Ottosson
Ranch Hand

Joined: Mar 21, 2000
Posts: 51
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Jesper- I don't think that will do it. See what happens when you test it:
<code><pre>class Test {
public void swap(Integer i, Integer j){
int temp = i.intValue();
i = new Integer(j.intValue());
j = new Integer(temp);
public static void main(String[] args) {
Integer a = new Integer(1);
Integer b = new Integer(2);
System.out.println("a: " + a);
System.out.println("b: " + b);
new Test().swap(a, b);
System.out.println("a: " + a);
System.out.println("b: " + b);
The key is that i and j are variables local to swap(). They start out pointing to the same arrays as a and b, but when you reassign them that has no effect on a and b.
Praveen- this isn't really possible in Java. To swap two values, a method has to have access not to the values themselves, but to an object or objects which contain the values. Unfortunately wrapper classes don't work for this because they are immutable - there are no methods which allow you to change the value within a given Integer. As an alternative though, here's a way you can swap two members of an int array:
<code><pre> public void swap(int[] array, int index1, int index2){
int temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;

"I'm not back." - Bill Harding, Twister
Betty Reynolds
Ranch Hand

Joined: Feb 16, 2000
Posts: 111
Or you can use my favorite object types strings/stringbuffers (there are almost no types that you can't convert to or between using using these classes). For example:

There are a number of ways to do it using these objects.

[This message has been edited by Betty Reynolds (edited April 08, 2000).]
jQuery in Action, 2nd edition
subject: wrapper class