Does Java have something like C#'s ref and out keywords?

getter and setter in java javatpoint
c# style properties in java
java get set
java getters and setters best practices
how to get values from getter method in java
java 8 getter/setter
alternative to getters and setters java
java properties

Something like the following:

ref example:

void changeString(ref String str) {
    str = "def";
}

void main() {
    String abc = "abc";
    changeString(ref abc);
    System.out.println(abc); //prints "def"
}

out example:

void changeString(out String str) {
    str = "def";
}

void main() {
    String abc;
    changeString(out abc);
    System.out.println(abc); //prints "def"
}

No, Java doesn't have something like C#'s ref and out keywords for passing by reference.

You can only pass by value in Java. Even references are passed by value. See Jon Skeet's page about parameter passing in Java for more details.

To do something similar to ref or out you would have to wrap your parameters inside another object and pass that object reference in as a parameter.

C# style properties in Java, If we could have the best of both worlds between Java and C#, what the only real difference is that the query syntax looks more like SQL and  No, Java does not have the equivalence. It only has accessor and mutator methods, fancy names for getter and setter methods. For example: It should be clear that these getter/setter methods are not separate constructs with flashy syntax like properties are in C#.

Direct answer: No

But you can simulate reference with wrappers.

And do the following:

void changeString( _<String> str ) {
    str.s("def");
}

void testRef() {
     _<String> abc = new _<String>("abc");
     changeString( abc );
     out.println( abc ); // prints def
}

Out

void setString( _<String> ref ) {
    str.s( "def" );
}
void testOut(){
    _<String> abc = _<String>();
    setString( abc );
    out.println(abc); // prints def
}

And basically any other type such as:

_<Integer> one = new <Integer>(1);
addOneTo( one );

out.println( one ); // May print 2

Java vs C# - 10 Key Differences between Java and C#, We researched the top features that Java developers miss in C# and chose 5 of Both Java and C# have nested classes, but what Java does differently until several years later, Java did something very different when they  Java - Do java have something like C#'s struct automatic constructor. I've been using C# for a long time and now I need to do something in Java.

Actually there is neither ref nor out keyword equivalent in Java language as far as I know. However I've just transformed a C# code into Java that uses out parameter and will advise what I've just done. You should wrap whatever object into a wrapper class and pass the values wrapped in wrapper object instance as follows;

A Simple Example For Using Wrapper

Here is the Wrapper Class;

public class Wrapper {
    public Object ref1; // use this as ref
    public Object ref2; // use this as out

    public Wrapper(Object ref1) {
        this.ref1 = ref1;
    }
}

And here is the test code;

public class Test {

    public static void main(String[] args) {
        String abc = "abc";
        changeString(abc);
        System.out.println("Initial object: " + abc); //wont print "def"

        Wrapper w = new Wrapper(abc);
        changeStringWithWrapper(w);
        System.out.println("Updated object: " + w.ref1);
        System.out.println("Out     object: " + w.ref2);
    }

    // This won't work
    public static void changeString(String str) {
        str = "def";
    }

    // This will work
    public static void changeStringWithWrapper(Wrapper w) {
        w.ref1 = "def";
        w.ref2 = "And this should be used as out!";
    }

}
A Real World Example
A C#.NET method using out parameter

Here there is a C#.NET method that is using out keyword;

public bool Contains(T value)
{
    BinaryTreeNode<T> parent;
    return FindWithParent(value, out parent) != null;
}

private BinaryTreeNode<T> FindWithParent(T value, out BinaryTreeNode<T> parent)
{
    BinaryTreeNode<T> current = _head;
    parent = null;

    while(current != null)
    {
        int result = current.CompareTo(value);

        if (result > 0)
        {
            parent = current;
            current = current.Left;
        }
        else if (result < 0)
        {
            parent = current;
            current = current.Right;
        }
        else
        {
            break;
        }
    }

    return current;
}
Java Equivalent of the C# code that is using the out parameter

And the Java equivalent of this method with the help of wrapper class is as follows;

public boolean contains(T value) {
    BinaryTreeNodeGeneration<T> result = findWithParent(value);

    return (result != null);
}

private BinaryTreeNodeGeneration<T> findWithParent(T value) {
    BinaryTreeNode<T> current = head;
    BinaryTreeNode<T> parent = null;
    BinaryTreeNodeGeneration<T> resultGeneration = new BinaryTreeNodeGeneration<T>();
    resultGeneration.setParentNode(null);

    while(current != null) {
        int result = current.compareTo(value);

        if(result >0) {
            parent = current;
            current = current.left;
        } else if(result < 0) {
            parent = current;
            current = current.right;
        } else {
            break;
        }
    }

    resultGeneration.setChildNode(current);
    resultGeneration.setParentNode(parent);

    return resultGeneration;
}
Wrapper Class

And the wrapper class used in this Java code is as below;

public class BinaryTreeNodeGeneration<TNode extends Comparable<TNode>>  {

    private BinaryTreeNode<TNode>   parentNode;
    private BinaryTreeNode<TNode>   childNode;

    public BinaryTreeNodeGeneration() {
        this.parentNode = null;
        this.childNode = null;
    }

    public BinaryTreeNode<TNode> getParentNode() {
        return parentNode;
    }

    public void setParentNode(BinaryTreeNode<TNode> parentNode) {
        this.parentNode = parentNode;
    }

    public BinaryTreeNode<TNode> getChildNode() {
        return childNode;
    }

    public void setChildNode(BinaryTreeNode<TNode> childNode) {
        this.childNode = childNode;
    }

}

Why is C# so similar to Java?, However, it is possible to access them if we provide public get and set methods. The get method MyClass.java:4: error: name has private access in Person The Java reference types all derive from a common root type. C# has a unified type system in which all types (besides unsafe pointers) ultimately derive from a common root type. Consequently, all types implement the methods of this root type, and extension methods defined for the object type apply to all types,

Java passes parameters by value and doesn't have any mechanism to allow pass-by-reference. That means that whenever a parameter is passed, its value is copied into the stack frame handling the call.

The term value as I use it here needs a little clarification. In Java we have two kinds of variables - primitives and objects. A value of a primitive is the primitive itself, and the value of an object is its reference (and not the state of the object being referenced). Therefore, any change to the value inside the method will only change the copy of the value in the stack, and will not be seen by the caller. For example, there isn't any way to implement a real swap method, that receives two references and swaps them (not their content!).

Is C# better than Java?, Actually, the thing that was most difficult for me to get used to was coding After I switched to C#, Java 8 introduced a feature very similar to LINQ Sure, most Java IDEs can generate them on demand, but it's still another  In C# there is the concept of namespaces, which (roughly) correlates to a package in Java, although in Java the naming convention matches the folder structure of the compiled .jar file whereas the C# namespace does not have to. Similarly, there is no hard and fast naming rule in C# class-file relationships,

Like many others, I needed to convert a C# project to Java. I did not find a complete solution on the web regarding out and ref modifiers. But, I was able to take the information I found, and expand upon it to create my own classes to fulfill the requirements. I wanted to make a distinction between ref and out parameters for code clarity. With the below classes, it is possible. May this information save others time and effort.

An example is included in the code below.

//*******************************************************************************************
//XOUT CLASS
//*******************************************************************************************
public class XOUT<T>
{
    public XOBJ<T> Obj = null;

    public XOUT(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XOUT()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(this);
    }

    public XREF<T> Ref()
    {
        return(Obj.Ref());
    }
};

//*******************************************************************************************
//XREF CLASS
//*******************************************************************************************

public class XREF<T>
{
    public XOBJ<T> Obj = null;

    public XREF(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XREF()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(Obj.Out());
    }

    public XREF<T> Ref()
    {
        return(this);
    }
};

//*******************************************************************************************
//XOBJ CLASS
//*******************************************************************************************
/**
 *
 * @author jsimms
 */
/*
    XOBJ is the base object that houses the value. XREF and XOUT are classes that
    internally use XOBJ. The classes XOBJ, XREF, and XOUT have methods that allow
    the object to be used as XREF or XOUT parameter; This is important, because
    objects of these types are interchangeable.

    See Method:
       XXX.Ref()
       XXX.Out()

    The below example shows how to use XOBJ, XREF, and XOUT;
    //
    // Reference parameter example
    //
    void AddToTotal(int a, XREF<Integer> Total)
    {
       Total.Obj.Value += a;
    }

    //
    // out parameter example
    //
    void Add(int a, int b, XOUT<Integer> ParmOut)
    {
       ParmOut.Obj.Value = a+b;
    }

    //
    // XOBJ example
    //
    int XObjTest()
    {
       XOBJ<Integer> Total = new XOBJ<>(0);
       Add(1, 2, Total.Out());    // Example of using out parameter
       AddToTotal(1,Total.Ref()); // Example of using ref parameter
       return(Total.Value);
    }
*/


public class XOBJ<T> {

    public T Value;

    public  XOBJ() {

    }

    public XOBJ(T value) {
        this.Value = value;
    }

    //
    // Method: Ref()
    // Purpose: returns a Reference Parameter object using the XOBJ value
    //
    public XREF<T> Ref()
    {
        XREF<T> ref = new XREF<T>();
        ref.Obj = this;
        return(ref);
    }

    //
    // Method: Out()
    // Purpose: returns an Out Parameter Object using the XOBJ value
    //
    public XOUT<T> Out()
    {
        XOUT<T> out = new XOUT<T>();
        out.Obj = this;
        return(out);
    }

    //
    // Method get()
    // Purpose: returns the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public T get() {
        return Value;
    }

    //
    // Method get()
    // Purpose: sets the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public void set(T anotherValue) {
        Value = anotherValue;
    }

    @Override
    public String toString() {
        return Value.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return Value.equals(obj);
    }

    @Override
    public int hashCode() {
        return Value.hashCode();
    }
}

does java have something similar to C# properties?, C# has reflection. You can loop through all members, properties, and methods separately. In Java, you have something similar. But no way to  As you already stated, you can do the exact same thing with the publisher-subscriber/Observer pattern. It just requires a bit more legwork. And no, Java does not have native support for events, like C# does with delegates.

C# vs. Java: 5 Irreplaceable C# Features We'd Kill to Have in Java, The More Things Change The More They Stay The Same In Java and C# arrays do not have to be uniform because jagged arrays can be created as  That said, I like the flexibility. I think Java and C# are both good and I actually enjoy programming in C# a little bit more than Java, but in Java I have choices. Lots and lots of choices. But sometimes, too many choices can be a bad thing and become overwhelming. Right now I'm learning Scala, which is an entirely different language.

C# vs. Java: The Top 5 Features Java Developers Miss in C#, In these ways, Dart is more script-like. So you will need to change your thinking from “a collection of classes” to something more like “a sequence of included code  Java's java.io.Closeable interface, implemented by streams, automagically extends AutoCloseable, so you can already use streams in a try block the same way you would use them in a C# using block. This is equivalent to C#'s using.

Java Encapsulation and Getters and Setters, Java and C# has a lot of similarities in the syntax. If you are moving from C# to Java, here are a few things that you might want to remember: Casing @NeWNeO, if you're referring to the query language in C# then yes, nothing like this is coming to Java, however in my experience most seasoned C# developers prefer lambda syntax over the query language. However if you are referring to LINQ-to-Entities for example then you will find that lambdas in java will enable this and more.

Comments
  • possible duplicate of Can I pass parameters by reference in Java?
  • IMO you're not missing much. The only time I ever use ref or out in C# is when I am using a pattern like TryParse(), where the method returns a boolean result, and the only way to get a parsed value out of it is by using ref or out.
  • Guess what, that is right what I need to use! ;)
  • The other way to do it is to return a composite object with both the status and a nullable value in it. But I admit that's a bit Rube Goldberg-ish.
  • Nothing wrong with returning a composite object, if only there would be a predefined usable one (i.e. tuples). But wait, that'd need non-erased generics working with primitive types to be efficient :)
  • This should be expanded on some. You can only pass primitives (int, short, char, etc.) as value. And no, there is no out.
  • That is not 100% true, If you pass in an array or a class the reference to the array or object is passed in by value, You can change internals to the array or object and it will be reflected in the caller.
  • @fearofawhackplanet: Um, unless you use ref.
  • @fearofawhackplanet: Reference parameters need the ref modifier as part of both the declaration and the invocation - that means it's always clear when you're passing something by reference. yoda.arachsys.com/csharp/parameters.html
  • From CLR perspective, you're passing a managed reference (T&) by value, yes. But C# has its own terminology, and it specifically doesn't include such things as values of type ref T - from C# perspective, ref is strictly a parameter modifier, and speaking of "passing a reference by value" with respect to it doesn't make sense.
  • Ouch. That's ugly.
  • I never said, You can do it in this elegant way :P
  • so why does the following not work: private static void ParseLine(String newline, String[] aWrapper, Integer[] bWrapper) { StringTokenizer st = new StringTokenizer(newline); aWrapper[0] = st.nextToken(); bWrapper[0]= new Integer(st.nextToken()); } ParseLine(newline, new String[] {a}, new Integer[] {b});
  • @user311130 Your code is hard to read, but you could create a new question saying something like: "I found this answer <link to my answer> but the following doesn't work <your code here>