aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Fill the code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Fill the code" Watch "Fill the code" New topic
Author

Fill the code

Srinu Nanduri
Ranch Hand

Joined: Mar 20, 2006
Posts: 42
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.


SCJP, SCWCD
gaurav singhal
Ranch Hand

Joined: Nov 18, 2005
Posts: 135
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

Joined: Apr 07, 2006
Posts: 23
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

Joined: Mar 20, 2006
Posts: 42
I got it now. Thanks a lot for your replies.
Asha Pathik
Ranch Hand

Joined: Feb 08, 2006
Posts: 143
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


SCJP 1.5
Edisandro Bessa
Ranch Hand

Joined: Jan 19, 2006
Posts: 584
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 ]

"If someone asks you to do something you don't know how to, don't tell I don't know, tell I can learn instead." - Myself
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Fill the code