Skip to content
Advertisement

Can I pass parameters by reference in Java?

I’d like semantics similar to C#‘s ref keyword.

Advertisement

Answer

Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:

JavaScript

Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement