int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
}
else
System.out.println("a is:"+a");
}
This code shows no output when running, why?
Your snippet annotated:
int a=10, b=5;
if(a>b) // is true (10>5)
{
if(b>5) // is false (5>5)
System.out.println("b is:"+b);
// no else case, so does nothing
}
else // never gets here
System.out.println("a is:"+a");
} // unmatched bracket
Make sure there’s no syntax errors in your full code (like unmatched brackets) and that there’s always an else case, be it for development purposes only.
That's dangling else ambiguity. You are matching wrong if clause with the else clause? It's a common error.
This is often due to poor formatting.
That's your code:
int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
}
else
System.out.println("a is:"+a");
}
That's a properly formatted code:
int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
}
else
System.out.println("a is:"+a");
}
See how each statement is indented. It's clear that the else clause is associated with the outer if. But, in your code it's hard to see.
Your IDE can properly format the code for you. If you are using Eclipse, for example, you can select your code and press Ctrl + I to format your code.
if(a>b) = true | No output
if(b>5) = false | No output (Reason: 5 is not greater than 5)
else block is not being executed
Your code shows no output because a > b but b = 5, not greater than. To solve this, change if(b>5) to if(b>=5).
This is another case where reformatting makes the question so much clearer.
int a=10, b=5;
if(a>b) { // 'true' - This block is executed
if(b>5) // 5 is not greater than 5, it's equal, so this isn't executed
System.out.println("b is:"+b);
} else { // This is not executed
System.out.println("a is:"+a);
}
When a bug gets confusing just take the program step by step and think as the compiler would. Also, I'd recommend forming a full block with { braces } for an else statement if you used braces for the if statement, it makes things tie together nicer and it's easier to read. Making sure things are indented properly also makes things easier to understand. Readability is important!
int a=10, b=5;
if(a>b)
{
if(b>5)
System.out.println("b is:"+b);
}
else
System.out.println("a is:"+a");}
In your code above In first if you are checking (a>b) i.e (10>5) the condition is true so execution of block inside first if is started.
In your second if condition (b>5) i.e (5>5) condition is false. So it terminates the program hence it doesn't displaying anything.
For better understanding I edit your code as below:
int a=10,b=5;
if(a>b) // This condition is true so this if block executed
{
if(b>5) // this is false so this block won't execute.
{
System.out.println("b is :"+b);
}
}
else // Alredy first if executed because true condition so this also not executing
{
System.out.println("a is :"+a);
}
// Thats why you don't get any output in this program.
Related
I am trying to run the below code with x =10 ."X is not equal to 10!" is getting printed. but As per documentation, the else belongs to the innermost if()? Also if we replace "1==2" in the if block with 1==1 then also "X is not equal to 10!" is getting printed.
I have corrected the code ..
Edit : Got the answer.
if(1==2)
if(x!=10)
System.out.println("X is equal to "+x);
else
System.out.println("X is not equal to 10!");
Indent correctly to see
if(1==2)
System.out.println(x);
if(x!=10)
System.out.println("X is equal to "+x);
else
System.out.println("X is not equal to 10!");
I think that answers it already.
But more detailed:
First if is not true, the first println does not get executed (apart from the described second version).
Second if is unconditionally evaluated, is not true, the else is executed.
Or ot reflect it on the quote, there is no "inner" if because there is no if enclosing any other if.
Or another aspect, you seem to think that the output is occurring because the first ifs condition is false, i.e. the else is attached to the first if. It is however attached to the second if because the conditional code influenced by the first if ends at the ;. To have more code influenced by the first if you could introduce a block of several lines, with a pair of {}.
your control structure is missing enclosing brackets. these are important to enclose the scope of your logic otherwise unless you're careful you'll end up with incorrect logic.
public class flow {
public static void main(String[] args) {
int x = 10;
if(1==2)
System.out.println(x); <--- this is 'dead code' will not be reached
if(x!=10)
System.out.println("x is equal to " + x);
else
System.out.println("x is not equal to 10!");
}
}
furthermore, your answer is printing 'x is not qual to 10!' in the console because your logic is evaluating the 'else' clause. the logic, if(x!=10) print equals to x, but if it is equal to 10 then print not equal to 10.
Please put open and close curly braces on your code:
if(1 == 2){
System.out.println(x);
if(x!=10){
System.out.println("X is equal to " + x);
} else {
System.out.println("X is not equal to 10!");
}
}
for more info: Is it bad practice to use an if-statement without brackets?
This question already has answers here:
What is the benefit of terminating if … else if constructs with an else clause?
(13 answers)
Closed 6 years ago.
I was thinking the other day about the creation of "else-if" statements and why the way of its execution causes each event to be guaranteed mutually exclusive.
For example:
if(condition A)
//condition
else if(condition B)
//will run if condition A is false and condition B is true
else if(condition C)
//will run if condition A is false and condition B is false and condition C is true
else if(condition D)
//will run if all the above conditions are false and condition D is true.
I would think it would make more sense for all the "else" statements to be checked if condition A is not true, and not just stop if either B or C are true. My intuition thinks it would be more natural to have the above code be equivalent to this:
if(condition A)
//condition
else {
if(condition B)
//...
if(condition C)
//...
if(condition D)
//...
}
So therefore, why do we define else-if the way we do? Is it to circumvent unnecessary nesting of if-else statements? I just think it is ambiguous and would make sense to have it be equivalent to my second code snippet.
Edit: to clear up confusion, I completely understand that these two statements are not always equivalent. My question is primarily asking why else-if is defined such that the first statement is not always equivalent to the second statement? I'm trying to understand why else-if runs the way it does.
Edit 2: I think I finally understand the underlying essence of my question. Generally, "else" checks if the above statement is false, and if it is, it runs the statement. However, in the case of elif, it checks to see if all the above statements are false before running. This is different from the duplicate question as it asks about the nature of if-else itself, rather than its exhaustiveness.
EDIT 3: I have opened a new question which is hopefully clearer, found here.
The reason one would prefer one style over the other is to ensure either the presence or lack of mutual exclusion when testing the conditions.
If it is the case that Condition B, C, or D are not mutually exclusive with one another, then...
...in the first scenario, only Condition B would fire, due to the mutual exclusivity of the else if statement.
...in the second scenario, Conditions B, C, and D would fire, due to the fact that they are not mutually exclusive due to the if statement.
Ultimately it depends on what you want to do. You may want to run multiple statements in this fashion. However, you probably don't. Fashioning your statements in a mutually exclusive way ensures that you don't run into strange logical bugs when you get a result or state that you didn't expect.
If you take your nesting approach, and apply it consistently, you would actually come up with this:
if (condition A) {
// A
} else {
if (condition B) {
// B
} else {
if (condition C) {
// C
} else {
if (condition D) {
// D
}
}
}
}
Each if gets treated the same way. The first if statement doesn't have any special ability to remove the else block from all the other if statements. The grammar you suggest gives else an inconsistent meaning.
Let's take a basic example.
Assume, You want to award a grade according to the score of the student and score is 60.
if(score <= 50) {
System.out.println("C Grade");
} else if(score <= 70) {
System.out.println("B Grade");
} else if(score <= 100) {
System.out.println("A Grade");
}
It will print B Grade.
if(score<=50) {
System.out.println("C Grade");
} else {
if(score <= 70) {
System.out.println("B Grade");
}
if(score <= 100) {
System.out.println("A Grade");
}
}
Now, According to you if we follow above approach where conditions are not mutually exclusive. It will print B Grade and A Grade which is not true.
So, in the cases where conditions in if are not mutually exclusive you will run into problems. That's why nesting of if..else is needed.
static void merge(int []part1,int []part2,int []array)
{
int index1=0;
int index2=0;
for(int k=0; k<array.length; k++)
{
if(index1==part1.length)
{
array[k]=part2[index2];
index2++;
System.out.println("fourth");
}
else if(index2==part2.length)
{
array[k]=part1[index1];
index1++;
System.out.println("third");
}
else if(part1[index1]<part2[index2])
{
array[k]=part1[index1];
index1++;
System.out.println("second");
}
else
{
array[k]=part2[index2];
index2++;
System.out.println("first");
}
}
}
The part1 and part2 lengths are 4,and the array length is 8. In this condition why is the "second" is the first to print and not the "first"?
The condition is all false, that is why the else is the first to print?
I am little confused about else if.
In a if(condition) else if(condition2) else ..., there is no first/second to be executed. Also this is not really java specific. Only the block for which the condition is true will be executed. Here you first have:
if(index1==part1.length)
=> index1 = 0
=> part1.length = 4
So this condition is false.
else if(index2==part2.length)
we have the exact same scenario here, condition is false
else if(part1[index1]<part2[index2])
here unless we know what's in the input arrays, we can't know if it's true of false, but based on your comment this condition is true, hence the code in this block is executed along with System.out.println("second");.
Think of what this code is trying to achieve (we're merging 2 sorted arrays into a third array that will be sorted as well), understand that it is within a loop, and for each loop iteration it is executing a different block depending on the conditions.
You print second in your third condition, that is, at the first for iteration, when the arrays have any elements in them AND part1[0] < part2[0]
When you chain if else the first block for which the condition is true, gets run, and no other.
if(a) {
x();
} else if(b) {
y();
} else if(c) {
z();
}
If a is true, x() is run, and no other methods.
If a is false and b is true, y() is run, and no other methods.
if a is false, b is false, c is true, z() is run, and no other methods.
It may help to realise that the above is equivalent to:
if(a) {
x();
} else {
if(b) {
y();
} else {
if(c) {
z();
}
}
}
That is literally how the compiler interprets it; however most human readers find the first version, with fewer braces and less indentation, easier to read.
In your code, if "second" is printed, we can be certain that the third condition is true.
The third condition is:
part1[index1]<part2[index2]
The first time around the loop, index1 and index2 are both zero, so this block runs when the first element of part1 is less than the first element of part2.
You could confirm this by adding another debugging println above "second":
System.out.println( "part1[" + index1 + "]=" + part1[index1]);
System.out.println( "part2[" + index2 + "]=" + part2[index2]);
System.out.println("second");
But note that debugging using println is a bad habit to get into -- learn to use a debugger as soon as practically possible.
I'm new to Java and working through some coursework. However, on the following piece of code I'm getting the error "Unreachable statement" when trying to compile. Any pointers as to what I'm doing wrong?
public String getDeliveredList() {
int count = 0;
while (count < deliveredList.size()){
return ("Order # " + count + deliveredList.get(count).getAsString());
count++;
}
}
Once you've returned from the function, logically it can no longer execute anything after that point -- the count++ statement will never be reached.
while (count < deliveredList.size()){
// function always ends and returns value here
return ("Order # " + count + deliveredList.get(count).getAsString());
// this will never get run
count++;
}
If you have returned from a function then any statement after the point from where the function returned are basically unreachable statements and the compiler will issue an error on such statements.
However the following code will not issue an error inspite of statements written after return
void max(int a,int b)
{
if(a>b)
{
System.out.println(a+" is greater");
return;
}
System.out.println(b+" is greater");
return;
}
This is because the first return statement is written within a nested scope and not immediately visible in the function scope. The program execution will only pass through first return statement when a>b. If it is not so then that block of codes is never executed. So in spite of having statements after return, the code is compile-able;
We have an application on Java 6 running on Weblogic application server 11. I am trying to debug an issue. My code is
if(a==0){
//Do A
}
else if(a==1){
// Do B
}
else{
// do C
}
My problem is that even if my if block is true and line 2 is executed still the debugger will go to line 8 in else block.
The code on my machine and on server are synched, so no mismatch.
Please help me finding what may be wrong with my code.
We need to know what does the // Do C.
If there is an assignation:
if (a == 0) {
b = 1;
} else if (a == 1) {
b = 0;
}
else {
b = null;
}
a typical optimization that some compilers do would be:
b = null;
if (a == 0) {
b = 1;
} else if (a == 1) {
b = 0;
}
And that is the bytecode executed. Let alone if the code is compiled to native by a JIT compiler.
So depending on your debug client and jdk you could see crazy current instruction lines. But it is fine as long as the state at the end of the block is the expected.
Sometimes the executions needs to close the statement. So it goes to the closing.
Make sure that no static values is assigned to a and if so, that is recompiled. Assignations of static are linked in compile time.
don't forget that = is an assignment and == is a comparison - in your case, you're assigning the value and then checking the result of the assignment, NOT performing a comparison.
Simply change
if(a=0){
//Do A
}
else if(a=1){
// Do B
to
if(a==0){
//Do A
}
else if(a==1){
// Do B
Shouldn't it be:
if(a==0)
...
else if(a==1)
...
else
...