Since Java doesnt support pointers, How is it possible to call a function by reference in Java like we do in C and C++??
In Java, except for primitives, passing Object to a method/function is always by reference. See Oli Charlesworth's answer for the example.
For primitive types, you can wrap it using array: For example:
public void foo(int[] in){
in[0] = 2;
}
int[] byRef = new int[1];
byRef[0] = 1;
foo(byRef);
// ==> byRef[0] == 2.
Usually in java this is solved by using interfaces:
Collections.sort(list, new Comparator() {
@Override
public int compareTo(Object o1, Object o2) {
/// code
}
});
Yes, you can implement Call by Reference in another way by "Pass by Reference".
In below code the original data --> x is manipulated by passing the reference object.
public class Method_Call {
static int x=50;
public void change(Method_Call obj) {
obj.x = 100;
}
public static void main(String[] args) {
Method_Call obj = new Method_Call();
System.out.println(x);
obj.change(obj);
System.out.println(x);
}
}
Output: 50 100
You cannot do call by reference in Java. Period. Nothing even comes close. And passing a reference by value is NOT the same as call by reference.
I used an array to do this...
package method;
import java.util.Scanner;
public class InterChange {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a[]=new int[2];
System.out.println("Enter two values");
for(int i=0;i<2;i++) {
a[i]=sc.nextInt();
}
hange(a);
for(int i=0;i<2;i++) {
System.out.println(a[i]);
}
}
static int hange(int b[])
{
int temp;
temp=b[0];
b[0]=b[1];
b[1]=temp;
return b[0]&b[1];
}
}
JAVA does allow internal reference using objects. When one write this assignment Obj o1 = new Obj(); Obj o2=o1; What does it do, that both o1 and o2 points to the same address. Manipulating any object's space, will reflect in the other's also.
So to do this, as mentioned above you can either use Array, Collections
Real pass-by-reference is impossible in Java. Java passes everything by value, including references. But you can simulate it with container Objects.
Use any of these as a method parameter:
And if you change its contents in a method, the changed contents will be available to the calling context.
Oops, you apparently mean calling a method by reference. This is also not possible in Java, as methods are no first-level citizens in Java. This may change in JDK 8, but for the time being, you will have to use interfaces to work around this limitation.
public interface Foo{
void doSomeThing();
}
public class SomeFoo implements Foo{
public void doSomeThing(){
System.out.println("foo");
}
}
public class OtherFoo implements Foo{
public void doSomeThing(){
System.out.println("bar");
}
}
Use Foo
in your code, so you can easily substitute SomeFoo
with OtherFoo
.