Why am I get a warning "Dead code"? - java

if (myCondition1 && myCondition2 && myCondition3)
{
...
}
I wrote this code and run successfully. but I got warning about part of (...). The warning is "Dead code". It is just interesting to me. Do u have any idea?
thank u

"Dead code" is code that will never be executed. Most likely one of your conditions is hard-coded to false somewhere, making the conditional inside the if always false.

Dead code means it is never going to execute. E.g.
void someMethod() {
System.out.println("Some text");
return;
System.out.println("Another Some text"); // this is dead code, because this will never be printed
}
Same in case of your condition checking e.g.
String obj = "";
if(obj == null && obj.equals("")) { // here you get warning for Dead code because obj is not null and first condition is false so obj.equals("") will never evaluate
}

Your code inside the block is never reached. The reason is most likely that one of the conditions is always false.

If one or more of myCondition1, myCondition2 and myCondition3 are always false (like private const bool myCondition1 = false;) then that code inside the if will never be executed.

This could occur for a number of reasons. Either the whole of the if block is dead, caused by something like the following:
boolean condition1 = true;
boolean condition 2 = !condition1;
if(condition1 && condition2) {
//This code is all dead
Foo f = fooFactory();
f.barr(new Bazz());
}
Or you unconditionally leave the if block using something like return, break or continue, as shown below:
for(Foo f : foos) {
if(true) {
f.barr(new Bazz());
break;
//Everything after here is dead
System.out.println("O noes. I won't get printed :(");
}
}

Related

What does it mean dead code in programming languages(especially in dart)?

I was following the flutter guide(fileio) of voiderealms(youtube)
and i had this problem on the function readfile, the editor says that is dead code but i dont know what does it mean
i have tried to search on the web
String readFile(String file) {
try {
File f = new File(file);
return f.readAsStringSync();
}
catch(e) {
print(e.toString());
}
}
main(List<String> arguments) {
String path = 'C:/Users/danis/Desktop';
String txtFile = 'C:/Users/danis/Desktop/test.txt';
list(path);
if(readFile(txtFile, 'Hello World\n', FileMode.APPEND));{
print(readFile(txtFile));
}
}
Due to the ; after the if the if statement gets seperated from the block ({}), which means that it always gets executed, no matter what the condition says. However that code is not "dead" as it actually gets executed.
What does [...] dead code [/unreachable code] in [a] programming language [mean]?
Dead code is code that is useless, because it will never execute. A function is dead if it is not called anywhere, statements can be dead if they are after a return or throw:
// 1
print("alive");
return;
print("dead");
// 2
if(false) print("dead");
This is a bit of code that will never be executed because it doesn't make sense.
For instance:
if (false) {
print("Hello World");
}
In your case you have such warning because you wrote:
if (something);
Notice the ;, it means that there's nothing to execute within the if.
DartAnalyzer warns about dead code when it can statically deduct that the code will under no circumstances be executed.
int fun() {
return 5;
print('x'); // dead code
}
int fun() {
if(true) {
print('x');
} else {
print('y'); // dead code
}
}

does it matter whether I have one if clause between many else if?

I just found one thing that bothers me and left me puzzled:
I have a method that looks like this:
if( condition1){}
else if(....){}
if(){} // this is confusing, does it matter if it becomes else if?
//Would the behavior change?
else if(){}
else if(){}
Of course it matters. An else if condition is only evaluated if all the preceding if and else-if conditions of the same if-else-if block were false.
An if condition will always be evaluated, since it starts a new if-else-if block.
You should choose between the two based on the required logic.
if( condition1){}
else if(....){} // this condition is only evaluated if all the preceding
// conditions were false
if(){} // this condition will be evaluated regardless of the result of
// evaluation the preceding conditions
else if(){}
else if(){}
if(condition1)
.
.
else if(....){}
after else if(), if you add if (condition ..) statement then it will be considered separate if else block .
If your third if becomes else-if, it will be evaluated only when the first if-else if is false
If you leave it like that, it will be evaluated regardless whether the first if-else if is true or false
As others have pointed out, it does matter. But in case it helps, let me point out an important fact: there's no such thing as else if!
An else keyword is followed by a single statement. There are lots of kinds of statements: method invocations, value assignments... and blocks.
if (condition1)
doSomething();
else
doSomethingElse(); // a method invocation statement
// or...
if (condition2)
doSomething();
else { // a block statement, which itself contains statements
soSomethingElse();
andAnotherThing();
}
This should all look familiar, but consider that an if-else is itself a statement:
// *all* of this is just a single statement, the if-else statement
if (condition3) {
doYetAnotherThing();
} else {
doEvenAnotherThing();
}
Putting this all together, an else if is really just an else whose statement is itself an if-else. The following are exactly equivalent:
// the syntax you're used to:
if (condition1) {
doSomething();
} else if (condition2) {
doAnotherThing();
} else {
doAThirdThing();
}
// the same exact thing, written slightly more verbosely:
if (condition1) {
doSomething();
} else {
if (condition2) { // note that this if-else is within the else{...}
doAnotherThing();
} else {
doAThirdThing();
}
}
And that's really why the "plain" if in the middle of your stream of else-ifs starts a new line of questioning. Without the else in front of it, the previous if is just a plain if, not an if-else -- and thus that "nesting" doesn't happen.
Taking that last example I posted, and removing the else from before the if (condition2), we'd get:
if (condition1) {
doSomething();
} /*else*/ if (condition2) {
doAnotherThing();
} else {
doAThirdThing();
}
Note that without that else to next the else if(condition2), this is really what it looks like, and nothing more. Now all we need is to use slightly different formatting, and the logic becomes clear:
if (condition1) {
doSomething();
}
if (condition2) {
doAnotherThing();
} else {
doAThirdThing();
}
if else if blocks acts like switch blocks with one difference, As switch directly jump to the code block which matches the input case where as if else if block has to reach each condition to reach a particular code block.
Inserting another if{} block between a chain of if else if will simply create a new chain of if else if block from your newly inserted if blocks.

Java - multiple return statements - first one not returning?

I'm toying around with some Android programming, and was in the process of writing a couple methods to open and close a file. Well, I wanted to do some basic checks on the file and return true if the conditions were satisfied, or return false if it reaches the end of the method.
I was testing these with AndroidTestCase, and after I added a required permission to my manifest to fix my "canRead()" call, I started stepping through them. I see the debugger hit my "return true" statement, but then stepping over that, it moves on to the following line "return false" instead of actually returning.
I know I could wrap the "return false" in an else block, but am just curious why the function continues to execute after supposedly returning. Is a return statement inside an "if" block just returning out of the block, or should it be returning out of the whole function call?
public boolean OpenFile(String testFile) {
myFile = new File(testFile);
if (myFile.exists() && myFile.isFile() && myFile.canRead()) {
return true;
}
return false;
}
public boolean CloseFile() {
if (myFile != null ) {
return true;
}
return false;
}
If the condition in your if statement is true, then return true; gets executed and the method terminates.
To check this, just put a println(...) before the return false; instruction, you will see that it won't be executed. Check again your debug, you probably got confused by the tool.

Stop executing further code in Java

I have looked in the Javadoc but couldn't find information related to this.
I want the application to stop executing a method if code in that method tells it to do so.
If that sentence was confusing, here's what I want to do in my code:
public void onClick(){
if(condition == true){
stopMethod(); //madeup code
}
string.setText("This string should not change if condition = true");
}
So if the boolean condition is true, the method onClick has to stop executing further code.
This is just an example. There are other ways for me to do what I am trying to accomplish in my application, but if this is possible, it would definitely help.
Just do:
public void onClick() {
if(condition == true) {
return;
}
string.setText("This string should not change if condition = true");
}
It's redundant to write if(condition == true), just write if(condition) (This way, for example, you'll not write = by mistake).
return to come out of the method execution, break to come out of a loop execution and continue to skip the rest of the current loop. In your case, just return, but if you are in a for loop, for example, do break to stop the loop or continue to skip to next step in the loop
To stop executing java code just use this command:
System.exit(1);
After this command java stops immediately!
for example:
int i = 5;
if (i == 5) {
System.out.println("All is fine...java programm executes without problem");
} else {
System.out.println("ERROR occured :::: java programm has stopped!!!");
System.exit(1);
}
There are two way to stop current method/process :
Throwing Exception.
returnning the value even if it is void method.
Option : you can also kill the current thread to stop it.
For example :
public void onClick(){
if(condition == true){
return;
<or>
throw new YourException();
}
string.setText("This string should not change if condition = true");
}
You can just use return to end the method's execution
Either return; from the method early, or throw an exception.
There is no other way to prevent further code from being executed short of exiting the process completely.
I think just using return; would do the job

Efficient way of checking condition within a do while loop?

I am using a Do While loop but i have to test whether that condition is met half way through the loop so that if it is met it will skip that part. Is there an efficient way of doing this?
e.g. I currently have something like this:
do {
method1;
if (!condition)
method2;
} while (!condition);
EDIT: I apologise, i don't think i made it clear in the first place. The condition starts as being false, and at some point during the loop one of the methods will set the (global) "condition" to true at which point i want the loop to immediately end. I just think it's messy having to test the ending condition of the loop within it and was wondering if there was anything obvious i was missing.
Please provide more info about methods. If you can return condition from method1/2, then try:
do {
method1;
} while (!condition && !method2)
or if you pass by reference and method return always true:
while (method1 && !condition && method2 && !condition);
or:
while (!method1 && !method2);
EDIT: if:
public boolean method1/2 { ... logic ... ; condition = true; return condition;}
it's hardly depend on what you will do.
I assume that your are looking for is avoiding this additional test for efficiency because "condition" is not met most of the time (1 out of many)...
This optimization may be done by going deeper into what is really done in method1 and method2 (or on the data they are handling) and add a first "fake step" outside of the loop that will disable treatment of method2 only the first time. Would look like this:
prepare_for_loop_entering
do {
method2
method1;
} while (!condition);
if condition is the same on all the places you refer to it than
do {
method1;
method2;
} while (!condition);
as in your while loop condition will always be false (!condition will be true) unless you set it to true in method1; than you can just break; as soon as you set it to true in method1;
How about this:
method1;
while (!condition) {
method2;
method1;
}
what about this:
while (!condition) {
method1;
if(!condition)
method2;
}
How about the code below:
if(condition)
break;
Use the most generic form of a loop:
while (true)
{
method1;
if (!condition) break;
method2;
}
Further explanation
A while loop with a condition "condition" is exactly like:
while (true)
{
if (condition) break;
method1;
method2;
}
And a do-while is exactly like:
while (true)
{
method1;
method2;
if (condition) break;
}
We want neither of those, hence the code above.

Categories