0

Possible Duplicate:
Is Java pass by reference?

I need to modify the content of a variable that is passed to a function within that function.

The type is String. I want to inject a preceeding char when using the insertString function of an extendeded class of PlainDocument.

Community
  • 1
  • 1
HoNgOuRu
  • 717
  • 4
  • 13
  • 26
  • 1
    Short answer: **no**. Java never passes anything by-reference. It *does* pass references by-value, but that's **not the same thing**. – Joachim Sauer May 04 '12 at 14:30
  • 1
    Also: http://javadude.com/articles/passbyvalue.htm – Joachim Sauer May 04 '12 at 14:31
  • well, how can I modify a string on the fly ? – HoNgOuRu May 04 '12 at 14:31
  • In Java, there is only one parameter passing mechanism, pass-by-value, which is used for primitive and reference types. Passing a reference by value is similar to pass-by-reference in that it allows the reference to be modified. – Hunter McMillen May 04 '12 at 14:31
  • @HoNgOuRu Strings are immutable in Java, you can't modify them at all. You either need to create a new String or use a StringBuffer. – Hunter McMillen May 04 '12 at 14:32
  • 2
    `String` is immutable. In other words: no. – sp00m May 04 '12 at 14:32
  • I thought the straight answer to your question would be to use StringBuffer (since String is immutable). Why not, If you change the StringBuffer (inside your method), this should be reflected in the calling method too. After seeing so many answers with "No", I don't know ..Am I missing some thing here? – htulsiani May 04 '12 at 14:35
  • To modify a String on the fly use StringBuilder or StringBuffer. – Edwin Dalorzo May 04 '12 at 14:39
  • In general you can only pass by value in java (which means the objects reference's value is passed between methods), But if you change on the same object (without assigning a new object to the ref, your changes will be reflected in the calling method). e.gpublic class TestJava { private static void change(StringBuffer sb){ sb.append("Changed"); } public static void main(String[] args) { StringBuffer sb = new StringBuffer("Test"); change(sb); System.out.println(sb); } } – htulsiani May 04 '12 at 14:45

2 Answers2

4

Use a wrapper class:

public class Wrapper
{
    public String text;
}

// ...

public static void changeString(Wrapper w, String newText)
{
    w.text = newText;
}

You can use it like:

Wrapper w = new Wrapper();
w.text = "old text";
changeString(w, "new text");
System.out.print(w.text);

OUTPUT:

new text


Also see this answer: https://stackoverflow.com/a/9404727/597657

Community
  • 1
  • 1
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
1

The short answer is no, but you can always "simulate" the pointer by using an intermediate object.