0

I'm pretty new to Java, so forgive me if this seems like a dumb question.

I have 3 classes, one of the being the main class.

Class 1 - class accounts. Just contains empty variables/objects

String firstName;
int age;

Class 2 - class random. Contains an array of many names, and contains methods to randomly pick a name and to randomly pick an age:

String Names[] = {"Sophia", .....,  "Sasha", "James"}; // About a 100 names

public void nameRandom(String name) {
    name = Names[rand.nextInt(Names.length)];
}
public void ageRandom(int age){
        age = rand.nextInt(64)+19;
}

Finally, Class 3, the main class ('howManyAccounts' is an integer that is obtained through scanner):

Account[] accounts = new Account[howManyAccounts]; 

for (int i = 0; i < accounts.length; i++){          
    accounts[i] = new Account();            
    random.nameRandom(accounts[i].firstName);
    random.ageRandom(accounts[i].age);          
}

System.out.println("NAME" + "          " + "AGE");
System.out.println("");

for (int x = 0; x < accounts.length; x++){      
    System.out.println(accounts[x].firstName + "          " + accounts[x].age);
} 

The variables are never saved and I can't seem to figure out why.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Java's primitive types a pushed to functions by value not by reference. – Albjenow Nov 16 '16 at 07:25
  • 2
    Java is `pass-by-value` so you can't do things like `public void ageRandom(int age){ age = rand.nextInt(64)+19; }` – QBrute Nov 16 '16 at 07:25
  • 4
    @Albjenow: *All* arguments are passed by value rather than by reference. – Jon Skeet Nov 16 '16 at 07:27
  • How do you suggest I fix it? – Curious Spider Nov 16 '16 at 07:32
  • @JonSkeet Since there is no deep copy, it appears more like by-reference when passing objects -- at least to me old C/C++ programmer. – Albjenow Nov 16 '16 at 07:37
  • 3
    @Albjenow: No, that's basically a flawed understanding of the type system in Java. You never pass an *object* at all - and the value of a variable or expression is never an object. It's always a primitive or a reference, and when you use a variable as an argument, the *value* of that variable is passed. With pass-by-reference, changes to the parameter itself (e.g. `parameter = new ParameterType()`) would be seen by the caller. It's really important IMO to understand the difference. See https://stackoverflow.com/questions/32010172 – Jon Skeet Nov 16 '16 at 07:39
  • @CuriousSpider The question is not stupid. Sometime in the past it was determined that Java would call their pointers for references. Before they was called pointers though. You can still see this on the `NullPointerException`, which is still used. – patrik Nov 16 '16 at 07:39

0 Answers0