Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this happenning with switch (Java)? [duplicate]

Its pretty much clear that switch statements can take string value in Java and something like this :

String s="diljit"
switch(s){
 ..
 ....}

will always compile.. s is a object of type String.... but on the other hand switch statement cannot take objects of other classes? Why is this happening and How will i validate this question with a suitable answer..

Can switch statement take objects or not?

like image 297
Diljit PR Avatar asked Feb 06 '26 21:02

Diljit PR


1 Answers

Can switch statement take objects or not?

No you can't use any arbitrary object in switch statements. This is specified in the language itself. Even String is only allowed from Java 7 onwards. From JLS §14.11:

The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.

like image 135
Rohit Jain Avatar answered Feb 09 '26 11:02

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!