Click here to Skip to main content
15,866,422 members
Please Sign up or sign in to vote.
2.33/5 (2 votes)
See more:
I have code like this in C:

U16 var;

function1 (&var);
function2 (var)

How can i convert it to java?
Posted

Java does not support call by reference. You can make "var" a member of the class and do something like this:
Java
// Let function1 and function2 squares var.
public class Example {
    public static int var;
    public static void main(String []args){
    /// Equivalent of call by reference
    var = 5;
    function1(); // This changes the value of var(see function1())
    System.out.println(var);
    /// Call by value
    var = 5;
    function2(var); // This won't change the value of "var"
    System.out.println(var);

    }
    public static void function1(){ // Square "var" - equal to calling function1(&var) in C
    var = var * var;
    System.out.println(var);
    }
    public static void function2(int v){// Square "var" without changing var
    int v2 = v * v;
    System.out.println(v2);
    }
}

Output is:
25
25
25
5
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900