Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To use a string value as a variable name [duplicate]

Tags:

java

Is it possible to use String as a variable name.. like in this example -

String musicPlaying = "music2";
Music music1 = new Music("blaalla");
Music music2 = new Music("blalala");
Music music3 = new Music("balaada");

if(!musicPlaying.stillPlaying) { // As you can see i am using string as a variable name.
  changeMusic();
}
like image 709
julian Avatar asked Jan 07 '14 14:01

julian


People also ask

How can you use string as a variable name?

String Into Variable Name in Python Using the vars() Function. Instead of using the locals() and the globals() function to convert a string to a variable name in python, we can also use the vars() function. The vars() function, when executed in the global scope, behaves just like the globals() function.

How do you make a variable name a string in Python?

The items() or the iteritems() function can be utilized to get the variable name in the form of a string in Python.

How do you string a variable in JavaScript?

You write the string as normal but for the variable you want to include in the string, you write the variable like this: ${variableName} . For the example above, the output will be the same as the example before it that uses concatenation.

Can we declare variable name as string in Java?

Declaring (Creating) Variablestype variableName = value; Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.


2 Answers

What you can do is by associating (mapping) those values to the Music object. Here is example:

Map<String, Music> musics = new HashMap<>();
String musicPlaying = "music2";
musics.put("music1", new Music("blaalla"));
musics.put("music2", new Music("blalala"));
musics.put("music3", new Music("balaada"));

if(!musics.get(musicPlaying).stillPlaying) { // As you can see i am using string as a variable name.
  changeMusic();
}
like image 98
Wins Avatar answered Sep 19 '22 12:09

Wins


You can't do this in Java, but you can almost do it using a map.

Map<String, Music> map = new HashMap<String, Music>();
map.put("music1", music1);
map.put("music2", music2);
map.put("music3", music3);

if(map.get(musicPlaying).stillPlaying) {
  // happy listening 
}
like image 24
Silviu Burcea Avatar answered Sep 21 '22 12:09

Silviu Burcea