Is it possible to define variables dynamically? Last night I was writing some code (C and VB2010) and I ran into a problem related to defining variables in my program. The variables needed depend on the number of entries added by the user and the number of users. Even using dynamic memory allocation we have a size limit, but I wonder about this type of thing sometimes. We can define as many variables as we need (to a limit of course) when writing the code, but can't we define more at runtime?For example: say your whole program is done and when user says 'x', this cannot be created as variable; rather we require a variable to store that x. Why cant we make x a variable at runtime? Can't we build a bridge between compile-time and runtime with some rules?
How can variables be created at runtime?
computer science;compiler
Dynamically typed languages can define variables dynamically. Javascript has prototype based objects that can be defined and used as follows:var myObj =  {}; // Empty object// Define var1 in myObjmyObj.var1 = Hello World;// Use var1    console.log(myObj.var1);// Prints: Hello World// Redefine var1 in myObjmyObj.var1 = 1336;// Use var1 againconsole.log(myObj.var1 + 1);// Prints: 1337In statically typed languages, such as Java, you need to solve it in a different manner. One easy way to emulate dynamic variables is to use the Map data structure (Map in Java, aka. Dictionary in .NET or Associative Arrays) much like how dynamically assigned variables do under the hood in languages such as Javascript:Map<String, Object> vars = new HashMap<String,Object>();// Define a variable:vars.put(var1) = Hello World;// Use a variable:System.out.println(vars.get(var1));// Prints: Hello World// Redefine variable (1336 int is actually boxed into an Integer object):vars.put(var1) = 1336;// Use the variable again, type casting is needed:System.out.println(1 + ((Integer) vars.get(var1)));// Prints: 1337So there are ways to emulate dynamic type variable handling in a statically typed language such as Java, but it will be more verbose than in a dynamically typed javascript.Edit:Just to answer the OP in a more direct manner:say your whole program is done and when user says 'x', this cannot be created as variable; rather we require a variable to store that x. Why cant we make x a variable at runtime?As I alluded in my answer: Yes, you can emulate this behavior. I've created a small Java class to demonstrate the example and is available as a Gist. Feel free to run the example code and continue hacking on it.