Search code examples
javajava.util.scanneridentifier

Using scanner to create an object identifier?


Is there any way to create the name of an object depending on user input?

eg.

Object scan.nextLine() = new Object();

Solution

  • No it is not possible. There are no dynamic variables in Java. Java variable name have to be declared in the source code during compile time.

    If want to store the Object with the user entered values you can try using a Map to save the data as below.

    Map<String, Object> objects = new HashMap<String, Object>();
    String name = scan.nextLine();
    
    Object obj = new Object();
    objects.put(name, obj); // saving the objects in Map