-1

first off sorry if this question has been asked before (if it has i couldn't find it)

this is my code

public class Methods {

    public static void main(String[] args) {
        String playerOne = "this is blank";
        lols(playerOne);
        System.out.println(playerOne);
    }

    
    public static String lols(String playerOne) {
        playerOne = "this is filled";
        return playerOne;
        
    }
}

I want the playerOne String to change to "this is filled" but when it prints it says "this is blank"

i am unsure why this code is not working.

thanks for the help.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Brevan960
  • 3
  • 1
  • 1
    Beside Stultuske's answer, also check [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Federico klez Culloca Sep 24 '20 at 07:07

1 Answers1

0

you already are returning the String, you are just not doing anything with the result.

Change this:

public static void main(String[] args) {
    String playerOne = "this is blank";
    lols(playerOne);
    System.out.println(playerOne);
}

to either this:

public static void main(String[] args) {
    String playerOne = "this is blank";
    playerOne = lols(playerOne);
    System.out.println(playerOne);
}

or to this, and directly use the returned value without storing it:

public static void main(String[] args) {
    String playerOne = "this is blank";
    System.out.println(lols(playerOne));
}
Stultuske
  • 9,296
  • 1
  • 25
  • 37
  • An explanation on why their code doesn't work would probably be helpful here. E.g. [Passing a String by Reference in Java?](https://stackoverflow.com/a/1270782/11441011) – maloomeister Sep 24 '20 at 07:07
  • the explanation is: the OP isn't using the returned value, as is stated in the first sentence of my answer. – Stultuske Sep 24 '20 at 07:08
  • 1
    @Stultuske yes, but OP is clearly expecting to be able to modify the string pointed to by `playerOne` by passing it to the method. – Federico klez Culloca Sep 24 '20 at 07:09