0

For example, I have such code:

SomeClass item = new SomeClass();
OtherClass.someVoidMethod(item);  //there was some changes with item

and then in class, where was called method someVoidMethod(item) item will not change, cause we use in this method copy of that item. In C/C++ there is pointers. I'm looking for something like that in Java.


there is better example: There i cant edit string from method

public class Main {
public static void main(String[] args) {
    String string = "String";
    changeIt(string);
    System.out.println(string);
}
public static void changeIt(String string){
    string = string + " edited";
}

And what suntax I need, to do that? I tied to use *string and so on, but i do this wrong.


i find that this code wil not work the way i want

public class Main {
public static void main(String[] args) {
SomeClass someClass = new SomeClass();
    OtherClass.changeIt(someClass.getValue());
}
}

class SomeClass {
private String value;
public String getValue() {
    return value;
}
public void setValue(String value) {
    this.value = value;
}
}
class OtherClass {
public static void changeIt(String string){
    string = "someStr";
}
}

so i need to use something like that:

public static void main(String[] args) {
SomeClass someClass = new SomeClass();
    someClass.setValue(OtherClass.changeIt(someClass.getValue()));
}
public static String changeIt(String string){
    return "someStr";
}

and there is no other way?

aioobe
  • 413,195
  • 112
  • 811
  • 826

1 Answers1

1

To make a Long Story short: use Parameters as Inputs to a method, and use the return value as Output. This will make your code better readable and easier to maintain.

For example:

public class Main {
    public static void main(String[] args) {
        String string = "String";
        String modifiedString = changeIt(string);
        System.out.println(modifiedString);
    }

    public static String changeIt(String string) {
        return string + " edited";
    }
}

If you wrap your string into a mutable Container, than you can modify it in your method. However for your example code I would strongly recommend to not use this Approach!

class StringContainer {
    String content;
}

public class Main {
    public static void main(String[] args) {
        StringContainer container = new StringContainer();
        container.content = "String";
        changeIt(container);
        System.out.println(container.content);
    }

    public static void changeIt(StringContainer container) {
        container.content += " edited";
    }
}

The StringBuilder, as mentioned by @aioobe, would also be a good alternative to use.

slartidan
  • 20,403
  • 15
  • 83
  • 131