0

Java introduced switch case with Strings in its Java7. I was wondering if using such switch case will create garbage.

For example in my program,

String s = getString();
switch(s) 
{
    case ABC: // ABC is a final static constant
    ...
    case CDE: // CDE is also final static constant.
    ...
}

How java performs this switch case. Assume there are 10's of these switch cases. Will it create a new string everytime it is matching the string s with the case ABC and so on ?

If this is the case, it is very garbagy, so when I give switch case with 100 cases, then everytime 100 strings are going to be created.

2
  • There's no reason it would need to create any additional strings to do this, the string being checked (s) and the strings being compared to (your constants) are all already defined and cached in perm gen space. Commented Mar 21, 2013 at 16:15
  • 2
    Why do you think it would create a new string? Commented Mar 21, 2013 at 16:19

1 Answer 1

5

If the case values are constants then the same rules apply regarding the class constant pool as if it weren't in a case statement at all.

This is a good answer to a similar question which might help you.

Sign up to request clarification or add additional context in comments.

1 Comment

The case values must be constants - otherwise it won't compile.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.