Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Fill the code

 
Srinu Nanduri
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test {
public static void main(String[] args) {
int x=10,y=20;
swap(x,y);
System.out.println("After Swapping : x "+ x);
System.out.println("After Swapping : y "+ y);
}

static void swap(int a,int b){
/*** Fill in the code ***/
}
}

Can we fill the swap(int a,int b) method with code after which x and y in main() method will print swapped values i.e., x = 20 and y = 10 respectively.
 
gaurav singhal
Ranch Hand
Posts: 135
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No we cant fill any code here becoz the arguments are passed by values.
So variable a and b are just the copy of variable x and y. And any modification made on the argument ie a and b will not be reflected in main variable x and y.
 
Sreeram Desigan
Greenhorn
Posts: 23
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Srinu,
Nothing can be done at the method swap(int a, int b) to swap the values of x and y in main. This is because when u call the method swap(x,y); only the values of x and y are passed to the swap method and the values of x and y which are 10 and 20 are assigned to a and b respectively. Now there is no relationship between the variables a and b and the variables x and y. so wat ever operations u do on a and b will not in any means reflect x and y.
Please let me know if further clarifications are needed.
 
Srinu Nanduri
Ranch Hand
Posts: 42
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it now. Thanks a lot for your replies.
 
Asha Pathik
Ranch Hand
Posts: 143
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I think if we use "int arrays" instead of "int primitives" we can swap the values:

public class Test {
public static void main(String[] args) {
int[] x ={10},y = {20};
swap(x,y);
System.out.println("After Swapping : x "+ x);
System.out.println("After Swapping : y "+ y);
}

static void swap(int[] a,int[] b){
int temp = a[0];
a[0]=b[0];
b[0]=temp;

}
}

Asha
 
Edisandro Bessa
Ranch Hand
Posts: 584
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Srinu,

On the exam be careful with varargs arguments. Don't be confused thinking that primitives passed as arguments for varargs methods can be changed. IT'S NOT TRUE.

Although varargs are treated as array inside the method, primitives passed as varargs still are NOT changed from within such function.

Please check this code sample out :

[ April 10, 2006: Message edited by: Edisandro Bessa ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic