So, all variables in the conditions are static strings. type itself is a string in fact.
switch(type) {
case (INT || TINYINT):
preparedStatement = setInteger(preparedStatement, value, index);
break;
case (BIGINT || LONG):
preparedStatement = setLong(preparedStatement, value, index);
break;
case (DATETIME || TIMESTAMP):
preparedStatement = setTimestamp(preparedStatement, value, index);
break;
case (MEDIUMTEXT || ENUM || TEXT || LONGTEXT || VARCHAR):
preparedStatement = setString(preparedStatement, value, index);
break;
}
First, switch statements on strings are supported in Java 7+, but not in Java 6 and before.
Next, the || operator (the logical-OR operator) only works on boolean values, not String values. But you can get the same code to be run on multiple cases by listing the cases and not breaking until past the relevant code:
switch(type) {
case INT:
case TINYINT:
// This code will run for INT and TINYINT only.
preparedStatement = setInteger(preparedStatement, value, index);
break;
case BIGINT:
case LONG:
// This code will run for BIGINT and LONG only.
preparedStatement = setLong(preparedStatement, value, index);
break;
// etc.
Java 7 example:
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
Further I have never seen an OR statement inside of a switch like that. I would highly recommend not doing that.
Assuming you are using Java SE 7 (or later) and the constants are static final Strings, then the syntax is not Java.
case INT: case TINYINT:
What does this expression evaluate to?
INT || TINYINT
What are the datatypes for INT and TINYINT
I've only ever seen switch used with some primitives (and new in Java 7, string) literals or variables declared as final.
If this isn't throwing a compile error, then the || operator must be defined for whatever datatype those are. But unless that's somehow being resolved at compile time, that operator is not going to be allowed. (Again, this might be something new in Java 7 I'm not aware of.)
If you are trying to do "or" logic, the normative pattern (in pre-7 versions of Java at least), is:
switch(type) {
case INT:
case TINYINT:
preparedStatement = setInteger(preparedStatement, value, index);
break;
case BIGINT:
case LONG:
preparedStatement =
break;
It is supported on and after java 7
You cannot use logical operators in switch statements, even with Strings. You can only test one case at a time.
Related
I'm working on a switch statement and I'm wondering what happens when an argument is called with no value assigned?
For example if I called argument A, what would the execution look like?
switch (letter) {
case 'A':
case 'b': value = 2; break;
default: value = 1;
}
System.out.println(letter + "is worth" + value + "lollies"
}
If letter = 'A' then case 'A' will be executed until the next break is encountered.
As case 'A' is a no-op then case'b' will be executed value = 2 then the break would prevent the default case being executed.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
making a website in JSP on eclipse:
select[i] is acquired from the previous webpage correctly as a string from 1 to 5
each number represents a subject ie: if select[i]==1 so sub=Maths
I can not switch case on a string so I tried if else .. but sub is always equal to null (the declaration) ?? how can i make sub take the values in the if condition??
for (int i = 0; i < select.length; i++)
{
////
String sub=null;
if(select[i]=="1") {sub="Maths";}
else if (select[i]=="2") {sub="English";}
else if (select[i]=="3") {sub="Physics";}
else if (select[i]=="4") {sub="MI";}
else if (select[i]=="5") {sub="Software";}
////
rs=stmt.executeQuery("SELECT * FROM attends where userid= '"+user_id+"' and cid= '"+select[i]+"' ");
if(rs.next())//can not take it
{
out.println("You can not enroll in '"+sub+"' ");
}
else//can take it
{
int countUpdated =stmt.executeUpdate("INSERT INTO enroll (userid, cid) values ('"+user_id+"', '"+select[i]+"')");
out.println("Successfully enrolled in '"+sub+"' ");
}
}
This is one of the first problems I ever ran into while learning Java: the quandary of == vs equals. Fortunately, once you understand why they're different, it's easy to use them properly.
Whenever you're dealing with objects (as you are in this case), the == operator is used to determine whether two variables actually point to the same object. Objects are dealt with by reference in Java, so if object1 == object2, then the variable object1 actually refers to the same object that the variable object2 refers to.
This is not what you want here. You're trying to determine not whether two String variables point to the same object, but rather whether their contents are the same. For that, you should use the equals method, like so:
String sub=null;
if(select[i].equals("1")) {sub="Maths";}
else if (select[i].equals("2")) {sub="English";}
else if (select[i].equals("3")) {sub="Physics";}
else if (select[i].equals("4")) {sub="MI";}
else if (select[i].equals("5")) {sub="Software";}
This allows you to test whether the contents of sub are the same as the string "1", "2", etc.
And I believe your assumption about switch statements is incorrect: you can switch on a String in Java, and the equals method is used under the hood. So something like this:
String sub;
switch (select[i]) {
case "1":
sub = "Maths";
break;
case "2":
sub = "English";
break;
case "3":
sub = "Physics";
break;
case "4":
sub = "MI";
break;
case "5":
sub = "Software";
break;
default:
sub = null;
break;
}
might be preferable, because that's what switch statements are designed for.
Try this like
switch(select[i]) {
case "1":
sub="Maths";
break;
case "2":
sub="English";
break;
case "3":
sub="Physics";
break;
case "4":
sub="MI";
break;
case "5":
sub="Software";
break;
default:
sub="";
break
}
This question already has answers here:
How to use null in switch
(14 answers)
Closed 7 years ago.
Why is this failing to compile with an error of "case expressions must be constant expressions"? Isn't null a constant (known at compile time)?
Explicitly casting the null value to String as in case ((String)null) does not help too (I get the same error).
public static String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case null:
typeOfDay = "NULL";
break;
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
Yes, the case expressions must be constant expressions, but null is specifically prohibited by the JLS, Section 14.11, which describes the switch statement:
Given a switch statement, all of the following must be true or a compile-time error occurs:
Every case constant associated with the switch statement must be assignment compatible with the type of the switch statement's Expression (ยง5.2).
If the type of the switch statement's Expression is an enum type, then every case constant associated with the switch statement must be an enum constant of that type.
No two of the case constants associated with the switch statement have the same value.
No case constant associated with the switch statement is null.
At most one default label is associated with the switch statement.
(italics emphasis mine)
As a workaround, you can test for null outside of the switch statement.
The switch statement will throw a NullPointerException if you pass it a null value. Use a separate test to check for null values.
How to use the inputs of string array in switch case?
String[] mon=new String[]{"January","February","March","April","May","June","July","August","September","October","November","December"};
switch (mon)
{
case "January":
m=1;
break;
case "February":
m=1;
break;
}
Java (before version 7) does not support String in switch case. But you can achieve the desired result by using an enum.
private enum Mon {
January,February,March,April,May,June,July,August,September,October,November,December
};
String value; // assume input
Mon mon = Mon.valueOf(value); // surround with try/catch
switch(mon) {
case January:
m=1;
break;
case February:
m2;
break;
// etc...
}
Please see here for more info
Since JDK 7 you can have a String in a switch. but not a String array....
here's an example
in your code, you're trying to put the whole array into the switch.
try this:
String[] mon=new String[]{"January","February","March","April","May","June","July","August","September","October","November","December"};
String thisMonth = mon[5];
switch (thisMonth)
{
case "January":
m=1;
break;
case "February":
m=2;
break;
...
case "June":
m=6;
break;
}
You cannot use an array in a switch statement (before Java 7). If you are using Java 6 for Android development, you cannot switch on Strings either. Its better you use an enumeration for the months, then switch on the enumeration.
This question already has answers here:
Is "else if" faster than "switch() case"? [duplicate]
(14 answers)
Closed 9 years ago.
I need to check a small piece of logic and would highly appreciate if someone can give me some valuable input.
I have two ways of checking my logic and want to know which is more efficient.
1st way:
if(url.equalsIgnoreCase("1")){
url = "aaa";
}
else if(url.equalsIgnoreCase("2")){
url = "bbb";
}
else if(url.equalsIgnoreCase("3")){
url = "ccc";
}
else if(url.equalsIgnoreCase("4")){
url = "ddd";
}
else if(url.equalsIgnoreCase("5")){
url = "eee";
}
else if(url.equalsIgnoreCase("6")){
url = "fff";
}
2nd Way:
int temp = Integer.parseInt(url);
switch (temp) {
case 1:
url = "aaa";
break;
case 2:
url = "bbb";
break;
case 3:
url = "ccc";
break;
case 4:
url = "ddd";
break;
case 5:
url = "eee";
break;
case 6:
url = "fff";
break;
}
Please let me know which is more efficient. Is it bad to use Integer.parseInt(string)?
If your values really are 1-6, the clearest and most efficient way is using an array :
String[] URLS = {...};
url = URLS[Integer.parseInt(url) - 1];
Please let me know which is more efficient.
a switch statement is more efficient is your case
Is it bad to use Integer.parseInt(string)?
No. it's fine. but when you're using java7 you can use String-constants values in your switch cases but not on Android.
Asside from the efficiency: switch looks cleaner in most cases.
In terms of efficiency check this: Case vs If Else If: Which is more efficient?, but Way 2 looks to be a more clean and readable code.
As a general rule, the switch statement produces more efficient bytecode. With Java 7, switch statements with String was introduced, so you don't need to cast it.
In this case, switch is more efficient.
In fact, If you are using Java7, you may directly use string case rather than using Integer.parseInt().
It is not bad using parseInt but it will throw an exception if the string is not an integer.
otherwise, and I think you can see this for yourself, the switch/case is much more readible.
if your if construct would have a final else catching all other cases (including non numeric strings)
then you can do, assuming your ints are always positive
int temp = -1;
try {
temp = Integer.parseInt(str);
} catch (NumberFormatException ex) {
// ignore exception and use -1 as original value for default case
}
Readability and debugability (is that even a word?) are rather subjective but some people (including me) find the switch statement to be more clear. However, in many cases a compiler has a better chance of generating faster code using a switch compared to the if else construct.
The switch statement is faster for the following two reasons.
The switch statement is generally faster than if-else-if construct because the control is directly transferred to the respective case. While in the cases of if-else-if, the all the checks are going to be performed to reach the first matching condition. For example, if you assign temp = 6 the switch statement will execute the respective block directly. The if-else-if construct will iterate through all the conditions.
Calling the equalsIgnoreCase() is more costly than performing the equality check that happens at the background of the case matching.
for such a long list is a switch statement definitely the better choice. The longer the junction is if the better cut off a switch in comparison
Efficiency depends on the matching condition in both cases.Please conform your answer here.
I think an alternative approach would be to use a pre initialized map. It should have the (string)numbers as the key and the url results as value. Then you can simply do
url = map.get(Integer.parseInt(url));
This is probably even a much cleaner version then the long switch statement.
The switch has more features than the if else, because you can fall through cases.
See for details: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
class SwitchDemo2 {
public static void main(String[] args) {
int month = 2;
int year = 2000;
int numDays = 0;
switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}
will output
Number of Days = 29
So it also depends on your implementation requirements which one you use.