0

I have the following structure in user.java

public class User(){

    string fname;
    string lname;
    string email;

    public User(){
        this.fname = randomCharGenMethod();
        this.lname = randomCharGenMethod();
        this.email = randomCharGenMethod();
   }
}

in another java class, I've created following objects.

static User user1 = new User();
static User user2 = new User();

when I'm going forward with the objects created, they both have same fname, lname, and email.

Actually, I want them to have unique fname,lname and email as they were generated from a string generating method

Pau
  • 14,917
  • 14
  • 67
  • 94
Ishi Silva
  • 59
  • 1
  • 7
  • 1
    I think we need to see `randomCharGenMethod` source code as well – DaveH Jun 05 '17 at 07:00
  • that works fine public static String randomCharGenMethod() { return RandomStringUtils.randomAlphabetic(5); } – Ishi Silva Jun 05 '17 at 07:02
  • How is this compiling if you are using `string` ? Is it a custom type ? – anacron Jun 05 '17 at 07:02
  • I used String sorry for the typing mistake – Ishi Silva Jun 05 '17 at 07:02
  • I can't be sure since you didn't share `randomCharGenMethod()` but my guess is that this is your problem https://stackoverflow.com/questions/5533191/java-random-always-returns-the-same-number-when-i-set-the-seed – Guy Jun 05 '17 at 07:02

1 Answers1

1

Is there any specific reason that the User1, User2 are declared static? When you are handling static variables, you should remember that they are loaded before the instance with their value.

Consider this code, as a simpler example:

public class User() {
static string fname;
static string lname;
static string email;

public User() {
    this.fname = randomCharGenMethod();
    this.lname = randomCharGenMethod();
    this.email = randomCharGenMethod();
 }
} 

any new instance of User will share the same value of fname, lname and email, because those are loaded before any instantiation.

Taking that into account, perhaps if user1, user2 are not static, they can hold values generated individually.

Assafs
  • 3,257
  • 4
  • 26
  • 39