Query in Java- Initialization error -
public class switch { public static void main(string args[]){ int month=4; string season=""; // question: giving error if not initializing here, y ? switch(month){ case 12: case 1: case 2: season="winter"; break; case 3: case 4: case 5: season="spring"; break; case 6: case 7: case 8: season="summer"; break; case 9: case 10: case 11: season="autumn"; break; default: system.out.println("bogus month"); } system.out.println("april in "+season+"."); } }
i created example code using if else , there showing no initialization error variable season here it's showing initialization error it. where's wrong?
this same code using if else here season wasn't initialized , yet gave no error.
public class ifelse { public static void main(string args[]){ int month=4; string season; if(month==12 || month==1 || month==2) season="winter"; else if(month==3 || month==4 || month==5) season="spring"; else if(month==6 || month==7 || month==8) season="summers"; else if(month==9 || month==10 || month==11) season="autumn"; else season="bogus month"; system.out.println("april in "+season+"."); } }
the difference in switch
, default case
doesn't set season
. try set value in default
, don't initialize variable. not give error.
something like:
default: season = "default"; system.out.println("bogus month");
this because compiler knows before printing season
value have value set after executing switch
sure since default
sets value season
. in if-else
sure season
have value after executes.
Comments
Post a Comment