• 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
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

problem...help me ..pls.

 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
I found this q. in a book..the o/p of this prog. is
(5,3)(3,5)(5,3)...but I expected it would be(5,3)(3,5)(3,5)
My q. is ..why the x,y value is not changing whereas I am calling the
the odes() method in the main???
Code:
_____________________________________________________
public class ex34
{
public static void main(String args[])
{
int x=5;
int y=3;
System.out.print("("+x+","+y+")");
odes(x,y);
System.out.print("("+x+","+y+")");
}
public static void odes(int x,int y)
{
int tem;
tem=x;
x=y;
y=tem;
System.out.print("("+x+","+y+")");
}
}
____________________________________________________________
<marquee> Ratul Banerjee </marquee>
*************THANKS IN ADVANCE********************************
 
Ranch Hand
Posts: 144
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the catch is that arguments are passed by values in methods and not by references, except in the case of array elements and object member variables. read some literature on this.
by the way, how come you didn't take your first "ship" of java in this post?;-)
 
Ranch Hand
Posts: 439
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The output is correct because look how they stored a value into a temporary variable temp and then assign it back. They are switching values back and forth.
first values are 5 and 3
when you pass them to method 5 gets assigned to tem and y is assigned to x so the value of x is now changed it it no loner contains 5 , it contains a 3 now. but y is assigned a value of 5
tem=x; //5
x=y; // 3 x now is 3
y=tem; // 5 y now is 5
so the result get's printed out 3 and 5
when you return back to main the values of x and y are unchanged
because they are copied to method call , they weren't used. So they printout 5 and 3
reply
    Bookmark Topic Watch Topic
  • New Topic