0

Suppose I have a String Variable like this in Java:

String cat = "felix";

int felix = 6;

Is there some way in Java that I could compare the contents of cat - "felix" to the name of the int variable felix?

DIowa
  • 9
  • 1

1 Answers1

0

There is no way to do it with the method you are doing, but you can use hashmap:

Map<String,Integer> myMap = new HashMap<>();
myMap.put("felix", 6);
myMap.put("another key", -4);
int value = myMap.get("felix");
System.out.println(value);//prints 6
value = myMap.get("abc");//throws null pointer exception
Ofek
  • 1,065
  • 6
  • 19
  • This approach is not `null`-safe. If no mapping for a given `String` exists, it will throw a `NullPointerException` ([Ideone demo](https://ideone.com/qfIHG0)). It is also not what OP asked for. We should rather ask for clarification in the comments instead of posting speculative answers. – Turing85 Jan 03 '22 at 21:27