C++ to Java

G

Guest

How can I write this in Java?

void change(string &s) {}


and how can I write this in Java?

void change(string s) {}



Because all Object in Java are passed by reference in functions, the
following Java code is equal to 1st C++ code, up.

void change(String s) {}

but with a test, I discover that this code is equal to 2nd C++ code.

Any help?

Thanks!
 
K

KC Wong

Version 1:
void change(string &s) {}

Version 2:
void change(string s) {}
Because all Object in Java are passed by reference in functions, the
following Java code is equal to 1st C++ code, up.

That's incorrect.
void change(String s) {}

but with a test, I discover that this code is equal to 2nd C++ code.

- Java pass parameters to functions by value
- java.lang.String objects are immutable. Once created, it cannot be
changed. When you do a String assignment,
e.g. String s = "ABC"; s = "DEF";
You're not changing the string "ABC" to "DEF"... instead, you're just
creating a new String object instance containing the value "DEF" and point
String variable s at it.

So to change a String, you get a copy from the parameter, change it, and
return a String. There're plenty of examples in the core API... see the API
documentation of java.lang.String for method trim().

Or if you really, *really*, REALLY must return void (and I don't know why
you must), then you can use a String array to do it. But that's very ugly,
very dirty code.

e.g. void change(String[] s)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,678
Members
48,796
Latest member
Greg L.

Latest Threads

Top