'Is there a way to print or call on a void methods parameter in java

I've been teaching myself java out of a book and I am trying to find out if I have a void method and I pass in two empty arrays through its parameter list, how can I use the methods parameters for later use. So for instance I put in 3 names with there score in like this " John Doe 98.3 " don't mind the parentheses. I want to make a sorting method later and be able to call that to sort the arrays String[] score, String[] names in the parameter list. In main after I call the method I try to print the array that I used for the parameter (on line 26 for me) but it returns null. How do I get the parameter list data from this void method?

Would prefer not to use objects unless there is no other way. Thanks for the insight.

 // imports

 import java.util.Scanner;

 import java.util.regex.Matcher;

 import java.util.regex.Pattern;



 public class Example {

     public static Scanner input = new Scanner(System.in);
     public static void main(String[] args) {
    

    int n;

    n = numOfStudents();

    input.nextLine();

    String[] studentScore;
    studentScore = new String[n];

    String[] studentNames;
    studentNames = new String[n];

    studentInfo(n, studentScore, studentNames);
    
    // prints null
    System.out.println(studentNames[1]);


 }

public static int numOfStudents(){

    int students = 0;
    System.out.print("Enter the number of students: ");
    students = input.nextInt();

    while (students < 1) {
        System.out.print("Number of students must be greater than 0: ");
        students = input.nextInt();
    }
    return students;
}

public static void studentInfo(int num, String[] score, String[] names){


    String[] arr;
    arr = new String[num];

    score = new String[num];

    names = new String[num];

    String strPattern = "-?\\d+(\\.\\d+)?";

    for(int i = 0; i < num; i++) {


        System.out.print("Enter a name and test score: ");
        arr[i] =input.nextLine();

        Pattern pattern = Pattern.compile(strPattern);
        Matcher matcher = pattern.matcher(arr[i]);

        while (matcher.find()) {
            score[i] = matcher.group();
        }

        names[i] = arr[i].replaceAll(strPattern, "");

    }
    System.out.println(score[1] + names[1]);
}

}



Solution 1:[1]

The trick is to know the difference between a reference and an object.

In java, all variables can only hold a small, fixed size amount of data, no exceptions. So, how in the blazes does Person p = new Person(); work, you should be wondering - you can make your own Person class and stuff it to the gills with fields with no issue; clearly a Person object can easily be neither small nor fixed size.

References is the answer.

This is what happens:

  • An object is created by invoking the Person constructor.
  • The reference to this object is the value of this invocation.
  • Your p variable holds this reference. This is a pointer; it lets java know where to find the object. It is not the object itself.

Imagine a giant beach. Objects are buried treasure. Variables are treasure maps written on little wipeable handheld whiteboards.

Person p = new Person();

is thus equivalent to:

  • Create a new treasure chest.
  • Bury it.
  • Draw the location to it on a map.
  • Return the map.

Next important thing to keep in mind: Java is pass by value. In java, those little whiteboards are never passed. Whatever whiteboards you hold are yours and yours alone. You cannot give them away nor receive any. Instead, whenever you want to give data to a method, you can instead show them what to copy on their whiteboards, and similarly, when a method returns information to you, all you get to is copy what is on their whiteboard.

Final important realization: Primitives (long, int, short, byte, double, float, boolean, and char - the list is hardcoded, you can't make your own) are all small and fixed size and just fit on these little whiteboards.

This explanation isn't 'java is a lot like this'. Nono, java is exactly like this. This metaphor does not have any failure modes; it is a pirate, beaches, and whiteboards version of how java works.

Note that = is assignment: In our pirate world it is the equivalent of wiping out a little whiteboard and copying something else on it. In contrast to foo.bar, foo[x], synchronized (foo), switch (foo) - these all dereference, meaning: In our pirate world those all involve: "Follow the map and dig in the sand".

Putting it all together, it explains the behaviour you witness. Let's go line by line through your code:

  • String[] studentScore;

Conjure out of thin air a new whiteboard. We shall name it studentScore, and we restrict it: It may either be blank, or have a map that leads to treasure of the String[] type; it is completely impossible to make maps to any other kind of treasure with it, the universe (the JVM) won't let it happen.

  • studentScore = new String[n];

This does multiple separate things. First, it conjures up a new treasure chest. It contains just enough room for n treasure maps (it's more like a little file folder than a big chest). After all, Strings themselves are objects too - they are treasures, and all string variables and references are therefore maps, not the whole thing. An array that can hold 'n' strings really just holds n treasure maps to strings. Next, this says: Draw on your studentScore whiteboard a map to this newly conjured up treasure file folder. Like all arrays of non-primitive types, it starts out with n blank maps. (a blank map = a null value).

  • studentInfo(n, studentScore, studentNames);

Your whiteboards are yours and cannot be handed out. So, this means: Walk over to Misses studentInfo. studentInfo knows how many arguments it has (in java all methods always have a set number of arguments), so she's ready to do your bidding, holding 3 fresh new blank whiteboards. You show her 3 whiteboards of your own: One with n written on it directly (n is an int, a primitive, therefore it's just written on your board. There's no map and no treasure involved), one with a treasure map leading to your studentScore buried treasure, and one to another buried treasure chest. Misses studentInfo duly copies these values and maps over on her 3 boards and goes to work.

  • score = new String[num];

Misses studentInfo takes her treasure map to the treasure you made and buried and wipes it clean, then, she conjures up an entirely new treasure chest, buries it, and copies the location over on her whiteboard.

  • score[i] = matcher.group();

Misses studentInfo fetches a shovel, follows her score treasuremap, digs down, and opens the treasure, which is a file folder with room for a bunch of treasure maps written on little whiteboards. She finds the i-th whiteboard, takes it out, wipes out whatever is there, and copies the treasuremap over that Mr matcher is currently showing her, as a result of doing his thing.

  • ... method ends ....

Misses studentInfo is done, and she returns nothing, so she takes her whiteboards and tosses them in the garbage.

  • You are standing there, your whiteboards are of course still completely unmodified, maps to treasure that nobody touched - maps to treasures that still hold all blank maps. You fetch a shovel, follow your map, dig down, open the file folder, and pull out the first little whiteboard. Of course it is blank.

So how do you 'fix' this?

Don't use = in your studentInfo method. Alternatively, do that, but return that value (you can only return one thing, so if your method needs to modify 2 treasure chests, that 'return it' plan is not going to work out).

Just ditch the score = new String[num]; part. If you do not do that, then your line of score[i] = foo digs down to find the treasure that the map misses studentInfo copied over from your little whiteboard leads to. And then she modifies what she finds there - which is great, because when you follow your map, it's a different map, but goes to the same place, so when you dig down, you'll see the effects of what Misses studentInfo did.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rzwitserloot