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?

1
  • No, there is not. At least not with variable names. We can, however, use a Map<String, Integer>. Commented Jan 3, 2022 at 21:21

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

This approach is not null-safe. If no mapping for a given String exists, it will throw a NullPointerException (Ideone demo). It is also not what OP asked for. We should rather ask for clarification in the comments instead of posting speculative answers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.