• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Liutauras Vilda
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Scott Selikoff
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
  • Frits Walraven
Bartenders:
  • Stephan van Hulst
  • Carey Brown

small swapping problem please please reply!!!!!

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

how to swap the contents of any two variable in java ?
public void fn()
{
int x=10,y=20;
swap(x,y);// doesnot not work since only values are passed
}
void swap(int x, inty)
{
int tmp=x;
x=y;
y=tmp;
}
please tell me how to swap values of (any) variabls in above example ?
can it be done in java or what?
[ February 19, 2002: Message edited by: Jigar Gosar ]
 
Ranch Hand
Posts: 233
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
HI,
You should be happy that it did not work(kidding).
The basic is that when ever you pass a variable to a function. You are alway passing a copy the variable. So the swap will be done to copy not to the actual variable.
Now coming to your question. One way you can achive your task by pass a object insted of variable(use wrapper class). Or declare the variable has class level variable.
-arun
 
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
2 ways to do that: (maybe more , but 2 i will mention)
1) like Arun said, use wrapper classes that are found in the java.lang package (ie. Integer, Double etc) to wrap the promtives inside them and then it will work.
2) wrap the numbers inside an array of one. ie. put the primitives inside an array (each one on its own). because arrays are passed "by refrence" (notice the " " ) it will work too.
 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This works, don't know if this is the intention

Erik Dark
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
All variables declared inside of methods (or code blocks) are local to the method. That means that they do not exist outside of that method.
In the original code you swapped to local variable values, returned NOTHING to capture the results of your efforts, and then let the method and the local variables end.

In Erics example, he declared two variables that are NOT local and therefore do not end when the method ends. His example shows static variables, but it would be more common to have then not static, but member variables. member variables are declared outside of any method, just in the body of the class. These are the things that track the STATE of the object.
If you are careful not to hide the member variables with local variables of the same name, you can work on them inside your method just like you showed. If you DO use the same name inside your method, then you need to indicate that you want to set the value of the member variable instead of the local variable by using the "this" keyword.

[ February 19, 2002: Message edited by: Cindy Glass ]
[ February 20, 2002: Message edited by: Jim Yingst ]
 
Jigar Gosar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
first thanks for replying
but none of u answer my question except
Roy Ben Ami
the array method is which actually works.thanks(why it didnt strike to )
now this is for people who suggested using wrapper classes i think they are immutable and hence of no use.
i know about the suff of pass by value & pass by reference.
so those of u think it can be done by wrapper classes please give me an example(which i think is not possible )
p.s. cindy and eric u have missed my point and explained something else sorry

[ February 20, 2002: Message edited by: Jigar Gosar ]
[ February 20, 2002: Message edited by: Jigar Gosar ]
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes you could use arrays, but that will not completely fix your problem.


The variables which hold the references to the wrapper classes are not immutable. However you still have to deal with the problem of local variables even with Wrapper classes.

Unless I am completely missing the point again . . .
[ February 20, 2002: Message edited by: Jim Yingst ]
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Cindy, what i meant is this code, which works gr8 and has no problems:

public class Ranch
{
public Ranch()
{
int []a={10},b={20};
swap(a,b);
System.out.println(a[0]+" "+b[0]);
}
public void swap(int a[],int b[])
{
int tmp=a[0];
a[0]=b[0];
b[0]=tmp;
}
public static void main(String[] a) {
new Ranch();
}
}

it doesnt matter the variables are local. they are still passed "by reference" and thus are changable.
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
as to your other question Jigar, nope!
the only way to do it in java is either arrays or wrapper classes (which i have to admit you are right are a bit more tricy because of the immutable).
thats if i may say it in a java forum is one of the disadvantages in my oopinion in java, but also one of the aspects that make this language so easy to use.
there is no way to pass objects truly by refrence in java (except RMI) and so we have to use these innovative ways.
in c# just for example, all you have to do is dd the word ref in front of the parameter in the function and it is passed by reference.
 
Cindy Glass
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Roy, sometimes I just need the question expained in VERY SIMPLE WORDS :roll: .
Some days just go like that . . .
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The thing is, I've never had a need for a swap function except in a context where there was already another existing containing object which held the objects I wished to swap. E.g. an array or List of some sort. In this situation, what you typically need is a method to swap two elements within the existing containing object. E.g.:
or
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Also, I edited a couple posts above to break up some overly long lines in the code sections (which were forcing the whole screen to be wider than otherwise).
 
Jigar Gosar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks roy for that array method once again but its clumsy(i am searching for a clean way, there is almost always a clean way in oops),however it solves my problem.

now let me put my question clearly for those people who are still missing the point.
class HowToSwap
{
public static int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z; // r they enough ?

/* suppose i want to write a static function that will swap contents of any of these two variables ???*/

public void swap(int x,int y)// i know that this func doesnot work so dont waste your
// time in explaining why it doesnot work just give me somithing that works
{
int t=x;
x=y;
y=t;
return;
}
void main bla bla bla (bla)
{
swap(a,z); // here i want that actual contents actually should be swapped;
}
}
if still u dont understand my question.
let me put it in other way.
i am giving u 'C++' code give me its java equivalent which just swaps .
class ICanSwap
{
public:
static int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z; // assume they r initialized some where else

public void swap(int &x,int &y)
{
int t=x;
x=y;
y=t;
return;
}
}
void main()
{
ICanSwap s;
s.swap( ICanSwap.a,ICanSwap.z); they r actually swaped
}
now dont tell me that java being platform independent,bla bla bla bla Language cannot perform some stupid swapping of variables thru functions.
and please give me some code that works and just dont tell me that, use objects or use wrapper classes, because i have tried everything but all in vain.
I will regard any person who answers this query as a true java guru.(Roy Ben Ami is close, for array method (the only method that works for now))
p.s. ( i still have a hunch that it cannot be done in java or am I underestimating THE language ? )
[ February 20, 2002: Message edited by: Jigar Gosar ]
[ February 20, 2002: Message edited by: Jigar Gosar ]
 
Roy Ben Ami
Ranch Hand
Posts: 732
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jigar, your assumption is correct.
to sum it up: there in no way other than what we told u here (arrays or wrapper classes) to do what u want in java.
there is no equivalant to pass by reference in java (like & in c++ or ref keyword in c#).
thats just ther way it is.
ultimatly, like Cindy pointed out, we would normally in a regular program NEED that kind of behaviour. there are always better ways around it.
but if u do need it use the around methods described above.
u can see it as a disadvantage in the language (like all c++ users do, but hey thats not the only thing c++ users see as disadvantage in java! pointers ring a bell? )
but, as java is designed to be easy to use and not complicated, thats just the way it goes.
hope i helped to clear it out a bit, and hey if u hear or find a solution im not aware of, feel free to update me also.
 
Jim Yingst
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I believe it could also be done with reflection - but would be pretty slow and ugly. And fundamentally unnecessary for any useful application, if one is prepared to be a bit more flexible about how data structures are defined. E.g. the line
public static int a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z;
can easily be replaced with

public static int numbers[26];
- after which a solution becomes trivial, as already shown.
As others have already indicated several times - if you're determined to formulate the problem the way you have, with the existing data structures (where "structure" means "unorganized jumble of data" in this case), then no, Java simply does not have an (elegant) solution to this. Yet somehow, we survive. :roll:
[ February 20, 2002: Message edited by: Jim Yingst ]
 
Jigar Gosar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
all said and done
yet i dont see how can it be done using wrapper classes. I saw examples int this thread about using array, but yet those who have mentioned the wrapper method still have not come up with an example.
I personally think it cannot be done using wrapper classes.
Anybody disagrees, feel free to prove your point (with an example)
 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jim pointed to the use of a wrapper class in one of his posts:

Originally posted by Jim Yingst:
The thing is, I've never had a need for a swap function except in a context where there was already another existing containing object which held the objects I wished to swap. E.g. an array or List of some sort. In this situation, what you typically need is a method to swap two elements within the existing containing object. E.g.:


The generic term 'wrapper' applies to more than the wrapper classes in the java.lang package such as Integer and Double. See my own little homegrown wrapper class below:

This class is a wrapper for the primitive integer type. It isn't one of THE wrapper classes, but it is a wrapper class. Jim calls it a containing object in his post, which is more generic than a wrapper.
Here is a little driver to demonstrate this code:

Here's the output:

As you can see, the values have been swapped.
You may have been looking for a way to use THE wrapper classes. As these are immutable, I'm not sure that's possible. I don't think the ranchers who suggested this approach were necessarily limiting it to the wrapper classes provided by Sun. It is possible to use wrapper classes to solve this problem.
If you're really looking for a language with the functionality of C++, I recommend you try C++. Java isn't C++: it's Java. If you think swapping primitive values is fun in Java, try it in SmallTalk.
 
Jigar Gosar
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well i have tried my hand on c++ long ago but I love java for its API its the best i think so far.
And that example was very nice and ELOBORATE.
It made lots of thing clear.
Thanks EveryBody,
Bye.
p.s.
Even I Belive that java is the best out there.
 
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is a very roundabout what of doing it to add to the pile. What makes it interesting is that it doesn't involve wrappers or arrays.

While this type of problem exists on the Java platform, i wouldn't give up Java's entirely pass by value. The desired activity is almost useless, the sillyness required to get it is unworrysome to me.
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Erik Dark,
I'm your suggestion will not work 'cos the values of x and y will still remain thesame after calling swap(). Try displaying the values of x and y after calling Swap() in the main() method and you'll see what I mean.
 
Politics n. Poly "many" + ticks "blood sucking insects". Tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic