I'm newbie to Java programming language. So I tried out a sample program (i.e :- Enum Comparison with Switch-Case Statement). Below is the program for your reference
public class TestClass {
public enum Company {
Google(1),
Microsoft(2),
JPMorgan(3),
WellsFargo(4);
private int companyRatings;
private Company(int companyValue) {
this.companyRatings = companyValue;
}
}
public static void enumComparison(Company type) {
switch (type) {
case Google:
System.out.println("Company Name : " + type + " - Company Position : " + type.companyRatings);
case Microsoft:
System.out.println("Company Name : " + type + " - Company Position : " + type.companyRatings);
break;
case WellsFargo:
System.out.println("Company Name : " + type + " - Company Position : " + type.companyRatings);
break;
default:
System.out.println("Company Name : " + type + " - Company Position : " + type.companyRatings);
break;
}
}
public static void main(String[] args) {
enumComparison(Company.Google);
}
}
So if you see the above program you can notice that i have missed break
keyword in the 1st case (i.e:- Case Google:
). In C#
the break
keyword is mandatory in the switch statements, It would result in compile time error if the keyword is missed. But I noticed in Java that it is not the case(No Compile time error for missing the break keyword
).
So in the Main
method I'm passing Company.Google
as an argument. Since the break keyword is missed out in the 1st case(Case Google:
) but it is moving to the second case(Case Microsoft:
) and prints the value, even though there is a type mismatch. It's weird and I'm not sure why this happens? So it prints the duplicate values. I'm confused.
Output
Company Name : Google - Company Position : 1
Company Name : Google - Company Position : 1