This question already has answers here:
Difference between Return and Break statements
(14 answers)
Closed 5 years ago.
I am using a boolean that returns true. When something like this happens:
public boolean t(String label, String[] arguments) {
boolean j = false;
if (!j) {
return true;
}
return true;
}
However, inside of this boolean I have a switch statement. As you may know, you break out of switch statements usually. However I am doing something like this testing for booleans to be true or false. Would I return inside of a switch statement, or break if a boolean is false?
An example would be something like this:
switch (arguments.length) {
case 0:
if (j) return true;
break;
default:
break;
}
Which would be more useful, exchanging return true for break, or keep it the same?
A break statement would terminate execution of the switch statement and continue in the method. A return statement would leave the method entirely.
It's a matter of preference, really, as to which one is better. It comes down to method design.
I would say in most cases like you have above, it would be better to directly use a return statement and leave the method entirely.
That said, this:
public boolean t(String label, String[] arguments) {
boolean j = false;
if (!j) {
return true;
}
return true;
}
Can be simplified to this:
public boolean t(String label, String[] arguments) {
return true;
}
And if you're only checking one condition from one variable, then you don't need a switch statement; it's not as optimal.
I am doing something like this testing for booleans to be true or false
You shouldn't really "test" for boolean variables to be true or false, just return them.
Return call always returns the handler to the called function where as break in the switch statement is to avoid checking other cases present in the switch case. If you don want your program return any values then break is sufficient else return required.
Related
In documentation it is said you could equally use if-else multiple times or switch-case:
int condition;
setCondition(int condition) {
this.condition = condition;
}
Either switch-case
switch (condition) {
case 1: print("one"); break;
case 2: print("two"); break;
or
if (condition == 1) { print("one"); }
else if (condition == 2) { print("two"); }
Next, conditionis declared volatile and method setCondition() is called from multiple threads.
If-else is not atomic and volatile variable write is a synchronizing action. So both "one" and "two" string could be printed in the last code.
It could be avoided if some method local variable with initial value was used:
int localCondition = condition;
if (local condition == ..) ..
Does switch-case operator hold some initial copy of variable? How are cross threads operations implemented with it?
From the Java specification on switch statements:
When the switch statement is executed, first the Expression is evaluated. [...]
This suggests that the expression is evaluated once and that the result is temporarily kept somewhere else, and so no race-conditions are possible.
I can't find a definite answer anywhere though.
A quick test shows this is indeed the case:
public class Main {
private static int i = 0;
public static void main(String[] args) {
switch(sideEffect()) {
case 0:
System.out.println("0");
break;
case 1:
System.out.println("1");
break;
default:
System.out.println("something else");
}
System.out.println(i); //this prints 1
}
private static int sideEffect() {
return i++;
}
}
And indeed, sideEffect() is only called once.
The expression is evaluated once when entering the switch.
The switch may use the result internally as many times as it needs to determine what code to jump to. It's akin to:
int switchValue = <some expression>;
if (switchValue == <some case>)
<do something>
else if (switchValue == <some other case>
<do something else>
// etc
Actually, a switch compiles to a variety of byte code styles depending on the number of cases and the type of the value.
The switch only needs to evaluate the expression once.
So I'm currently doing a first year university assignment and I'm a little stuck on one of the questions. It goes as such.
Modify the setType() and setPlan() methods to return a boolean true/false if the chosen type or plan was invalid. I.e if the type was "Bogus", ignore the type, and return a "false" to the call. Modify the Test class to add an "if" statement that will report a false call.
My current line of code for the method looks like this:
public void setType(String newType) {
switch (newType) {
case "Basic":
mType = newType;
break
case "Enhanced":
mType = newType;
break
default:
break
}
My question is, how do I go about adding an if statement and does anything need to be changed to make the void method return a true/false value?
Try this:
public boolean setType(String newType) {
switch (newType) {
case "Basic":
case "Enhanced":
mType = newType;
return true;
default:
return false;
}
}
You don't actually need an extra if statement for doing this, and you can check two or more cases in a switch by using a fallthrough (two or more consecutive case).
You could define an array with all valid types in some globally accessible spot in your app:
public static final String[] VALID_TYPES = {"Basic","Enhanced"};
and then have a method that just iterates all those types and checks if a given value matches one of them:
public static boolean isValidType(String candidate){
for(String validType : VALID_TYPES){
if(validType.equals(candidate)){
return true;
}
}
return false;
}
The nice thing about this - in contrast to using switch statements - is that you can easily modifiy the list of valid types (add/change/remove types) without the need to touch your method that checks a given type for validity. So it's easy to maintain and less error-prone (in a switch, you might forget to add a case statement for each possible value, or you might forget to add a break statement somewhere, etc)
Best practice would say this is "parameter checking", and it's cleaner too to fail early:
public boolean setType(String newType) {
if (!newType.matches("Basic|Enhanced")) {
return false;
}
type = newType; // or whatever you need to do
return true;
}
Options for testing also include:
if (!Arrays.asList("Basic", "Enhanced").contains(newType))
which also neatly handles newType being null without extra code.
But the best way to deal with this is to use an enum, which would not allow bad values in the first place.
The other answers are good. Here's my take. The ternary operator, ? and : expression, is logically an "if then else".
public boolean setType(String newType) {
boolean result = (newType.equals("Basic") || newType.equals("Enhanced"));
mType = result ? newType : mType;
return result;
}
public class YourClass{
private String mType;
private static final List<String> VALID_TYPES = Arrays.asList("Basic","Enhanced");
public boolean setType(String newType){
if(!VALID_TYPES.contains(newType)){
return false;
}
mType = newType;
return true;
}
}
And similar for the setPlan method, just define another list of VALID_PLANS.
And about your test class:
if(!yourClassObject.setType("Some Invalid Type")){
System.err.println("Invalid type!");
}
adding a boolean property of class,like this:
public class Test
{
private boolean flag;
}
This is my first time asking a question here, so I'll ask you to bear with me: I am trying to create a public boolean method, isEven(), that will check if a number is evenly divisible by two and return a value of true or false based on that. However, as this is a public method, I am unsure of how exactly to write it; this is my process thus far:
public boolean isEven()
{
if(WHAT_GOES_HERE? % 2 == 0)
return true;
else
return false;
}
I would appreciate some advice on how exactly to go about writing this method; thanks in advance!
The simplest way would be
public boolean isEven(int value){
return value % 2 == 0;
}
Using an if/else statement to return or set variables to boolean values is almost always redundant. Since you can return the condition you put in the if/else itself, the if/else is not needed.
So I had a previous question but realized I posted the wrong offending code. I've marked the offending statements below.
What I am trying to do is set the precedence for each of the operators with that switch statement.
Maybe someone could point me in the right direction.
Just as a note, I AM running JAVA 7 so String Switch will work.
Code
opType.java
import java.io.*;
public final class opType {
public static opType ADD = new opType( "Add" );
public static opType SUB = new opType( "Sub" );
public static opType MULT = new opType( "Mult" );
public static opType DIV = new opType( "Div" );
public static opType MOD = new opType( "Mod" );
public static opType LPAR = new opType( "LParen" );
public static opType RPAR = new opType( "RParen" );
protected String name;
private opType( String n )
{
name = n;
}
public String getName()
{
return name;
}
Operator.java
public class Operator extends Token {
protected opType val;
public boolean isOperator() { return true; }
public boolean isOperand() { return false; }
protected int getPrec()
{
switch(val.getName())
{
case "LParen":
{
return 0;
break; //unreachable
}
case "RParen":
{
return 0;
break; //unreachable
}
case "Mult":
{
return 1;
break; //unreachable
}
case "Div":
{
return 1;
break; //unreachable
}
case "Mod":
{
return 1;
break; //unreachable
}
case "Add":
{
return 2;
break; //unreachable
}
case "Sub":
{
return 2;
break; //unreachable
}
}
return 0;
}
public static int compare( Operator a, Operator b )
{
if( a.getPrec() == b.getPrec() )
return 0;
else if( a.getPrec() < b.getPrec() )
return -1;
else
return 1;
}
public opType getVal() { return val; }
public Operator( opType v ) { val = v; }
}
If you put a return, then the function returns before the break is executed and therefore the break will never be reached.
Instead you could use a variable that you set to a desired value and after the switch return that. Or just get rid of the break statements.
you already have return which will make the break unreachable
The reason that the code is unreachable is due to the return behaving like a break in that context - they both complete abruptly.
If a statement completes abruptly, then execution at that line is immediately returned to its appropriate context; if it's a break, it'll attempt to either exit the switch or return to its associated label if one exists; if it's a return, it will return to its caller, with or without a value.
This is why the code is unreachable: the line of code after the return can not be reached.
To really understand what that means or entails, we have to look at the Java Language Specification, specifically 14.1:
Every statement has a normal mode of execution in which certain
computational steps are carried out. The following sections describe
the normal mode of execution for each kind of statement.
If all the steps are carried out as described, with no indication of
abrupt completion, the statement is said to complete normally.
However, certain events may prevent a statement from completing
normally:
The break (§14.15), continue (§14.16), and return (§14.17) statements
cause a transfer of control that may prevent normal completion of
statements that contain them.
Evaluation of certain expressions may throw exceptions from the Java
Virtual Machine (§15.6). An explicit throw (§14.18) statement also
results in an exception. An exception causes a transfer of control
that may prevent normal completion of statements.
If such an event occurs, then execution of one or more statements may
be terminated before all steps of their normal mode of execution have
completed; such statements are said to complete abruptly.
An abrupt completion always has an associated reason, which is one of
the following:
A break with no label
A break with a given label
A continue with no label
A continue with a given label
A return with no value
A return with a given value
A throw with a given value, including exceptions thrown by the Java
Virtual Machine
The terms "complete normally" and "complete abruptly" also apply to
the evaluation of expressions (§15.6). The only reason an expression
can complete abruptly is that an exception is thrown, because of
either a throw with a given value (§14.18) or a run-time exception or
error (§11, §15.6).
If a statement evaluates an expression, abrupt completion of the
expression always causes the immediate abrupt completion of the
statement, with the same reason. All succeeding steps in the normal
mode of execution are not performed.
Unless otherwise specified in this chapter, abrupt completion of a
substatement causes the immediate abrupt completion of the statement
itself, with the same reason, and all succeeding steps in the normal
mode of execution of the statement are not performed.
Unless otherwise specified, a statement completes normally if all
expressions it evaluates and all substatements it executes complete
normally.
The return statement effectively exits the method immediately. Since you've placed return statements inside the switch block for each case, whichever case is matched will, according to your code, return whatever value is indicated immediately. The break therefore cannot be executed, hence the error. You have two options:
1- Set a value, and return at the end of the method:
protected int getPrec(){
int prec = 0;
switch(val.getName()) {
case "LParen":
prec = 0;
break;
case "RParen":
prec = 0;
break;
case "Mult":
prec = 1;
break;
case "Div":
prec = 1;
break;
case "Mod":
prec = 1;
break;
case "Add":
prec = 2;
break;
case "Sub":
prec = 2;
break;
default:
prec = 0;
break; // technically unnecessary since we're at the end already but adding for completeness.
}
return prec;
}
2- Ditch the break; statements and keep the return statements as you've written them.
Personally I would prefer the first option as its cleaner and more readable to me. Plus it makes it easier to expand whatever actions need to be done in one or more cases if need be in the future.
By the way, watch your naming convention. You presently have:
public final class opType // bad naming
Since this is a class, the Java standard is to capitalize the first letter of the class. So it should be:
public final class OpType // good naming
Here you can comment the line return super.onOptionsItemSelected(item)
after commenting this line the code will run.
This Works for me
public boolean onOptionsItemSelected(MenuItem item) {
//return super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case R.id.aboutUS:
Intent i = new Intent("com.code.myapp.ABOUT");
startActivity(i);
break;
case R.id.preferences:
break;
}
return false;
}
Why isn't this structure acceptable? Anyway it returns a boolean value right??
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
}
It's not valid because there is a possibilty where nothing is returned. Your method is declared as returning a boolean value, so it MUST return a boolean value at some point in the code before the method is finished, regardless of the inner logic. If your if-statement if (condition) is false, the method doesn't have another return statement, so the code won't even compile. To fix this, add a "default" return value:
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
return false;
}
Not valid because you need to do a return some default value (return) .
What if conditions not satisfied ??
valid is :
public boolean a()
{
if(condition)
{
if(condition)
{
if(condition)
{
return true;
}
}
}
return false;
}
As a side note,To make your code mode readable,I suggest
if(condition && condition && condition)
{
return true;
}
return false;
Prefer to read jls-14.17
Though the method returns true when the condition is satisfied, it doesn't specify a return value when the condition isn't satisfied. The method should cover all the code paths (read conditional statements).
As the answers above correctly state, you absolutely have to return something in Java. C doesn't really care.
In order to avoid this I would recommend decreasing the level of nesting to do something like
boolean value=false; //default return
if(cond && cond)
return value;
if(cond)
return false; //if you want to be more specific
if(cond)
value=true;
return value;
so a value gets returned no matter what. On the plus side, readability increases