Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reference parameters? 2

Status
Not open for further replies.

timmay3141

Programmer
Dec 3, 2002
468
US
I'm learning java with a background in C++. I was writing a method, but was surprised to discover that I couldn't use a reference parameter using C++ syntax. How do you use them? Surely there must be some way. Also, C++ pointer syntax doesn't work. Is it even possible to declare a pointer in java?
 
Almost everything in java is passed by reference. You don't do anything special. No pointers.
 
In Java all parameters are passed by value. If the parameter is a primitive data type, then the data value of the actual parameter is passed. If the parameter is a reference to an object, then the reference value is passed.
 
Whoops - I stand corrected.


It is confusing. Pass by reference is not the same as passing the value of a reference.

SomeObject o1 = someObject.instance();
o1.color = Color.GREEN;
change(o1);
change2(o1);
//o1 is still RED.
...
private void change(SomeObject o) {
o.color = Color.RED;
//now o1 color is read.
}

private void change2(SomeObject o) {
o = null;
//doesn't change o1, still RED.
}
 
Thank you, that was very helpful. I'm not sure how I will adjust to life without explicit pointers and references, but I'll find a way :).
 
There are some workarounds. What specifically were you trying to do?
 
It can be quite simple, just change the way you think ...

Code:
public class Test {
   public String setS1(String s) {
      s = s +" hello";
      return s;
   }

   public void doSomething() {
     String s = "abcdef";
     System.err.println(s);
     s = setS1(s);
     System.err.println(s);
   }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top