does default case MUST be included in switch statements in Java - java

I was just wondering if default case MUST be included in switch statements in Java. I understand it is good practice to include default cases. The reason why I ask is because for the code below, if I delete default case, the code will provide error. Could someone please help me clarify the concept? Thanks in advance for any help!
public class SwitchDemo {
public static void main(String[] args) {
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month"; //if delete will produce error
break;
}
System.out.println(monthString);
}
}

While the default clause is not mandatory, if you remove it, monthString may not be initialized, so you get a compilation error when you attempt to print it with System.out.println(monthString);.
You can remove the default clause if you give monthString a default value when you declare it. For example :
String monthString = "Invalid month";
This will give the same behavior as your current switch statement, which includes the default clause.

It is not required to have a default case, but it is a good idea to have one, since this catches cases that you intentionally do not want to handle (or unintentionally didn't handle).
As a point of reference, the Google Java style guide requires a default case.
In your code, assuming you are free of the strictures of a particular style rule requiring a default case, you don't need it; you just need to definitely assign monthString before you can use it (a requirement in the language specification). However, it doesn't make sense to assign a value for a month value outside the range 1-12 - it is logically wrong.
Throwing an exception is a sensible thing to do here, e.g.:
default:
throw new IllegalArgumentException("Invalid month");

If you looks your program you will find your error by own because of Initialization error.
Here
int month = 8;
String monthString; //it is a local Variable and not Initialized.
monthString is not initialized at the time of declaration and this Variable doesn't have global access (not a global Variable) so that it can initialize using any Constructor or any other source.
In your switch statement in all your case you have initialize the variable monthString. If you consider each case and default as a differen branch then you will realize that in all possible branch this code is getting executed. In each possibility variable monthString is initialized but If you Remove this code
default: monthString = "Invalid month"; //if delete will produce error
break;
then there may be a possibility of a default case (if all cases are getting Failed). So, Indirectly you are not consider this default case but there is a possibility of that.
If you still want to remove default case then Initialize your variable monthString at the time of declaration. It will also remove your Compile time error.
This is the reason of getting error after removing the default keyword.
Thank you

Related

Java switch statment, break statement unreachable

I am working on a program that is a simple game. I'm using a switch statement to return the file location of images that are assigned to buttons. In order to do this I am using a switch statement inside a method called "get Image View" it returns a string that can be fed into an image view that I will need to compare the image in the button to another image elsewhere. I think I may be over-explaining, anyway. my IDE (NetBeans) is telling me that my break statement is unreachable and I can not figure out why. I have used a switch statement that looks very similar to mine and there is an example in my textbook that is also very similar. I know that I still need to have a default return statement I just want to know what's up with my break statements. Thank you in advance!
public String getImageView(int button)
{
switch(button)
{
case 0: System.out.println("error");
case 1: return "1.png";
break;
case 2: return "2.png";
break;
case 3: return "3.png";
break;
case 4: return "4.png";
break;
case 5: return "5.png";
break;
case 6: return "6.png";
break;
case 7: return "7.png";
break;
case 8: return "8.png";
case 9: return "9.png";
case 10: return "10.png";
}
}
You can try something like below :
public String getImageView(int button){
String imageViewName = "";
switch(button)
{
case 0: System.out.println("error");
case 1: imageViewName = "1.png";
break;
case 2: imageViewName = "2.png";
break;
case 3: imageViewName = "3.png";
break;
case 4: imageViewName = "4.png";
break;
case 5: imageViewName = "5.png";
break;
case 6: imageViewName = "6.png";
break;
case 7: imageViewName = "7.png";
break;
case 8: imageViewName = "8.png";
break;
case 9: imageViewName = "9.png";
break;
case 10: imageViewName = "10.png";
break;
}
return imageViewName;
}
Hope this helps.
Well switch-state-statements behaves not like a big if-else-statement.
Consider this code:
int a = 0;
switch (a) {
case 0:
//do something
break;
case 1:
//do something else
break;
default:
//default case
}
Here the first case will be triggered as you can tell by the value of a.
If you want to first case be executed but also want to slip in the second case anyway you can omit the break in the first case.
So this code:
int a = 0;
switch (a) {
case 0:
System.out.println("case 0");
case 1:
System.out.println("case 1");
break;
default:
//default case
}
will output:
case 0
case 1
just like it is in your Code.
So maybe you should consider the break; in your first case. Otherwise it will execute the println but also returning 1.png.

Why can't you return a variable that has been initialized inside the function

In java if I have initialized a variable in a function that returns an that variable at the end, why can't I return that function?
Here's the some sample code, that I was working
private int spitNumber(int imgNum) {
int returnNum;
switch (imgNum) {
case 1:
case 14:
case 27:
case 40:
returnNum = 1;
break;
case 12:
case 25:
case 38:
case 51:
returnNum = 12;
break;
case 13:
case 26:
case 39:
case 52:
returnNum = 13;
break;
};
return returnNum;
}
When I compile the code I get the error message
error: variable returnNum might not have been initialized
return returnNum;
^
You're using switch but your switch does not cover all the cases.
Think when imgNum = 100, what value will your program assign to returnNum?
Nothing, right?
So you should initialize a starting value for returnNum or provide a default case for switch and assign your returnNum value there
Because you don't have any default case. the message shown says that the variable might not have been initialized, if your value is not among the handled cases.
Need to initialize the variable at the beginning of your code.
Example :
int returnNum = 0;
Primitive types like int, for example, cannot be null. You must initialize it.

Multiple args in a java switch

I am expecting my input to be one of three groups of chars and need to decide what to do with it based on which group it falls in. I'm trying to figure out how to define a switch with multiple cases to do this. Here is what I have so far:
while(in.hasNextChar())
{
char test = in.nextChar();
List<Signal> out = new List<Signal>(0);
switch(test)
{
case '1','0','x','X':
out.add(fromString(test));
break;
case ' ','/t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
}
return out;
}
You have the syntax wrong. You need to take advantage of fall-through:
switch(test) {
case '1':
case '0':
case 'x':
case 'X':
out.add(fromString(test));
break;
case ' ':
case '\t':
break;
default:
throw new ExceptionLogicMalformedSignal;
}
A case is just a label, very similar to what you'd use with a goto (which is essentially what is happening behind the scenes). It's not a statement, since it does nothing itself — it just names an address. So if test is '0', it can happily continue through the 'x' and 'X' cases to reach the actual statement code since there's not anything being done by those labels. Only break "ends" a case.
You can actually insert code between cases even without a break:
switch(test) {
case '1':
System.out.println("This is printed by case '1'");
case '0':
System.out.println("This is printed by both case '1' and case '0'");
break;
case 'x':
case 'X':
System.out.println("This is only printed by the Xs");
break;
default:
break;
}

Unable to get behaviour of Switch case in java

I have written small code in java 6
public class TestSwitch{
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:{
System.out.println(1);
case 3:
System.out.println(3);
case 4:
System.out.println(4);
}
case 2:{
System.out.println(2);
case 5:
System.out.println(5);
case 7:
System.out.println(7);
}
}
System.out.println("end");
}
}
Output: start 1 2 end
My editor is showing orphaned case for 'case 3' and 'case 5'.Still it is running
and showing output.
Does Nastated cases like concept is there in Java?
And Why it is giving above output? rather i thought it will be 'start 1 end'
Your response will be greatly appreciated!!
Switch replaces if else's but switch syntax != If else syntax.
You forgot to put break after each case.
So conditions under fall through.
Example:
case 0:
mColor.setText("#000000");
break;
You can find that in docs
The break statements are necessary because without them, statements in switch blocks fall through: All statements after the matching case label are executed in sequence, regardless of the expression of subsequent case labels, until a break statement is encountered.
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:
System.out.println(1);
break;
case 2:
System.out.println(2);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
case 5:
System.out.println(5);
break;
case 7:
System.out.println(7);
break;
default:
System.out.println("nothing");
}
switch(a){
case 1:{
System.out.println(1);
case 3:
You cannot nest cases like this. Switch should look either like :
switch(a){
case 1:
System.out.println(1);
break;
case 3:
....
or like this :
switch(a){
case 1:
System.out.println(1);
switch(a) {
case 3:
//...
break;
case 5 :
//...
And if you don't add break at the end of a case, the execution will continue after. You should add a break at the end of each cases if they should be executed separately.
You have wrong closing braces before case 2.
case 3,4 are interpreted as labels not cases.
Your code will give compilation errors as we can't use curly brace after case :
Exact code is:
public static void main(String... args){
int a = 1;
System.out.println("start");
switch(a){
case 1:
System.out.println(1);
case 3:
System.out.println(3);
case 4:
System.out.println(4);
case 2:
System.out.println(2);
case 5:
System.out.println(5);
case 7:
System.out.println(7);
}
System.out.println("end");
}
}
and output will be start
1
3
4
2
5
7
end because you have not use "break" after each case.
As their no break statement in case 1: the execution directly jumps to case 2: and ends up printing "start 1 2 end"..
You have not added break statement before case 2.
Refer this to know more about fall through.
Each break statement terminates the enclosing switch statement. Control flow continues
with the first statement following the switch block. The break statements are necessary
because without them, statements in switch blocks fall through: All statements after
the matching case label are executed in sequence, regardless of the expression of
subsequent case labels, until a break statement is encountered.
int a = 1;
System.out.println("start");
switch (a) {
case 1: {
System.out.println(1);
break;
}
case 3: {
System.out.println(3);
break;
}
case 4: {
System.out.println(4);
break;
}
case 2: {
System.out.println(2);
break;
}
case 5: {
System.out.println(5);
//no break will fall through and print 7 too
}
case 7: {
System.out.println(7);
break;
}
default:{
System.out.println("none");
}
}
See if a=1 then your case 1 will work then 1 will pe printed if as we have not using break after case 1 so all cases are working in flow so output is coming like this if you want to execute only one case at one time then you have to put break after one case like
switch(a){
case 1:
System.out.println(1);
break;
case 3:
System.out.println(3);
break;
case 4:
System.out.println(4);
break;
Then it will break out of the switch case on encountering break statement

How can I make this better

Ok here I have a switch case statement which is falling through and trying every option. Basically I want something that if the user enters the letter A in the textbox the background will change to b! if they dont enter the letter A then I want it to stop executing the code. But what has been happening is if the user enters lets say for example the letter Q when the background is letter A then the background will change to letter R instead of telling the user that they are wrong. basically I would like to know how I can stop the background from changing if the user does not enter the letter they are on here is the code.
public void afterTextChanged(Editable s) {
char ch = words.getText().toString().charAt(0);
switch(ch - 'A') {
case 0:
//A;
gestureViewer.setBackgroundResource(R.drawable.lettersb);
break;
case 1:
gestureViewer.setBackgroundResource(R.drawable.lettersc);
break;
case 2:
gestureViewer.setBackgroundResource(R.drawable.lettersd);
break;
case 3:
gestureViewer.setBackgroundResource(R.drawable.letterse);
break;
case 4:
gestureViewer.setBackgroundResource(R.drawable.lettersf);
break;
case 5:
gestureViewer.setBackgroundResource(R.drawable.lettersg);
break;
case 6:
gestureViewer.setBackgroundResource(R.drawable.lettersh);
break;
case 7:
gestureViewer.setBackgroundResource(R.drawable.lettersi);
break;
case 8:
gestureViewer.setBackgroundResource(R.drawable.lettersj);
break;
case 9:
gestureViewer.setBackgroundResource(R.drawable.lettersk);
break;
case 10:
gestureViewer.setBackgroundResource(R.drawable.lettersl);
break;
case 11:
gestureViewer.setBackgroundResource(R.drawable.lettersm);
break;
case 12:
gestureViewer.setBackgroundResource(R.drawable.lettersn);
break;
case 13:
gestureViewer.setBackgroundResource(R.drawable.letterso);
break;
case 14:
gestureViewer.setBackgroundResource(R.drawable.lettersp);
break;
case 15:
gestureViewer.setBackgroundResource(R.drawable.lettersq);
break;
case 16:
gestureViewer.setBackgroundResource(R.drawable.lettersr);
break;
case 17:
gestureViewer.setBackgroundResource(R.drawable.letterss);
break;
case 19:
gestureViewer.setBackgroundResource(R.drawable.letterst);
break;
case 20:
gestureViewer.setBackgroundResource(R.drawable.lettersu);
break;
case 21:
gestureViewer.setBackgroundResource(R.drawable.lettersv);
break;
case 22:
gestureViewer.setBackgroundResource(R.drawable.lettersw);
break;
case 23:
gestureViewer.setBackgroundResource(R.drawable.lettersx);
break;
case 24:
gestureViewer.setBackgroundResource(R.drawable.lettersy);
break;
case 25:
gestureViewer.setBackgroundResource(R.drawable.lettersz);
break;
would it be better if I set the pictures in an array and then went from there? Ive tried including If switch case, but it didnt work at all....
I'd pre-populae an array and invoke:
gestureViewer.setBackgroundResource(myArray[ch - 'A']);
It will make your code much more readable.
You can also do it with a Map<Character,MyImage> - it might allow you to add more features easily in the future.
If you do that, invokation will be using
gestureViewer.setBackgroundResource(myMap.get(ch));
Note that the array/map needs to be populated only once in the application's runtime.
You could, for example, put all the R.drawable.abc inside an Array and then address its index.
int[] bgImg = {R.drawable.a, ... , R.drawable.z}
char ch = words.getText().toString().toUpperCase().charAt(0);
int index = ch - 'A';
if(index > 0 && index < bgImg.length){
gestureViewer.setBackgroundResource(bgImg[index]);
} else {
gestureViewer.setBackgroundResource(R.drawable.standardImage);
}
Also note, that I'm using toUpperCase() to make sure you can substract the capital 'A'
Try:
public void afterTextChanged(Editable s) {
char ch = words.getText().toString().charAt(0);
int id = getResources().getIdentifier("letters" + ch, "drawable", context.getPackageName())
gestureViewer.setBackgroundResource(id);
}
}

Categories