Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Java language: switch statement

  Asked By: Boell    Date: Nov 28    Category: Java    Views: 2122

I'm trying to compile some code

switch (myclass.getSomeInt()){
case 1:
case 2:

I'm getting the following error:
"constant expression required at line x, column y"

Line X and column Y refers to the "switch(myclass.getSomeInt()" line.

Does that mean in switch(expr), expr must be a constant during compile
time? In this case what is the switch statement useful for?



5 Answers Found

Answer #1    Answered By: Taylor White     Answered On: Nov 28

I suspect the problem could be with return value of
myclass.getSomeInt(). Ensure that it returns an int
value. Ensure also that all numbers next to 'case' are
constants or constant  expressions. No variables or
expressions involving vairbales are allowed next to

Answer #2    Answered By: Cay Nguyen     Answered On: Nov 28

Your thinking is right - a switch  with a constant  required at that point would
be useless.

No, it's not meant to be a constant. The items in the "case" lines need to be
constants, of course.

Are you sure it's the switch line  it doesn't like? Compilers can get their
error messages a bit out of step sometimes.

You've obviously posted an indicative bit of code, not the real thing. I think
it might be better to post the real code.

Answer #3    Answered By: Corbin Jones     Answered On: Nov 28

Because I had to rush the project for a deadline, I rewrote it with if
then else statement.

I might have misread the error  message line  number and it might very
well be the case  statements that is throwing the error.

In my original code the case statements did not use a constant  by
itself. However, it was using a public static final constant integer.

case ToolBar.OPENFILE:
case ToolBar.SAVEFILE:

public class ToolBar{
public static final int OPENFILE=0;
public static final int SAVEFILE=1;

Looks like the above is not legal even though the variable is final?

Answer #4    Answered By: Taylor Evans     Answered On: Nov 28

Before handling the expression  in teh statement.Convert that to int value and
pass it to the switch.

Answer #5    Answered By: Benjamin Simpson     Answered On: Nov 28

You will be getting this error  when you try to use
some expression  or variable next to case:. See
following code for more clarifications.

class SwitchTest
static int x=0;
private static int getSomeInt()
return 2;

public static void main(String str[])
switch (getSomeInt()){
//case x: gives same error.
case: 1 // works fine.
case 2:


Didn't find what you were looking for? Find more on Java language: switch statement Or get search suggestion and latest updates.