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
...
Related
I've run into a problem with my multi branch if...else statements. In the challenge question they ask us to print out a line if certain variables are true|false. My statements will only print my if statement, however they compile. I feel I'm either missing something in my if statement that allows it to continue if a statement is not true|false.
Here is what I have:
if ( isBalloon && isRed ) {
isBalloon=false;
isRed=false;
System.out.println("Not a balloon");
}
else if ( isBalloon && isRed ) {
isBalloon=true;
isRed=false;
System.out.println("Balloon");
}
Also, for clarity; when we do a multi branch statement (else if) requires variable declaration, where as (else) is just anything that makes our if statement false. Is this correct?
I think this is easiest explained by pointing out that 'else if' in java isn't a separate keyword. So it is equivalent to the following (which is harder to read but points out why your code is executed only once)
if ( isBalloon && isRed ) {
isBalloon=false;
isRed=false;
System.out.println("Not a balloon");
} else {
if ( isBalloon && isRed ) {
isBalloon=true;
isRed=false;
System.out.println("Balloon");
}
}
this is what else if really does. When your code runs it hits the first if condition and when it is correct it will run the associated block. it then doesn't process the else block. (that is the idea: only if or else runs, not both).
It looks like if / else if / else if / else has multiple blocks on the same level but secretly they are nested.
for instance
if (a) {
// case a
} else if (b) {
// case b
} else if (c) {
// case c
} else {
// otherwise:
}
is actually:
if (a) {
// case a
} else {
if (b) {
// case b
} else {
if (c) {
// case c
} else {
// otherwise
}
}
}
I am using BlueJ IDE to write java programs.
I have a method with String return type. I have put the return statements within if-else, such that if the boolean variable "flag" has true value, then one value is returned, while if the value is false, another value is returned.
Now, the problem is that BlueJ asks for another return statement even after this, as shown below.
If I give another return after if-else, it works.
Why is this happening? I had learnt that there can be no statements after the return statement. So, why is the compiler asking for another return statement?
If someone wants the code for cut-paste purposes, here it is. This code is meant to convert binary numbers to their decimal equivalents, including fractions, but no negative numbers.
public class Conversions{
protected String Binary_Decimal(String str){
int a = str.indexOf('.');
boolean flag = false;
if (a == -1){
str += ".0";
a = str.indexOf('.');
flag = true;
}
String bd = str.substring(0, a);
String ad = str.substring(a + 1);
a = 0;
double num = 0;
for (int i = bd.length() - 1; i >= 0; i--){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a++;
}
if (flag == true){
return Integer.toString((int) num);
}
else if (flag == true) {
a = -1;
for (int i = 0; i < ad.length(); i++){
num += Math.pow(2, a) * Integer.parseInt(Character.toString(str.charAt(i)));
a--;
}
return String.valueOf(num);
}
return String.valueOf(num); //<-- WHY DOESN'T IT RUN WITHOUT THIS EXTRA return?
}
}
Here, str is the string that is input by the user using a different method Input().
The issue is that you wrote an if - else as an if - else if. The compiler does not understand or care that the two conditions you have are mutually exclusive and therefore cover all cases. Given how you wrote the branches, you need an explicit else or a catchall return for the compiler to be assured that the function always returns a String.
This is one example of why it is a bad idea to explicitly spell out the else when you have a set of conditions. The more important reason being that your if will often contain something much more complex and you might not negate it properly.
Delete the second ELSE IF clause and put the block directly after the first return statement, and consider that flag is a boolean. As follows:
if (flag) return Integer.toString((int) num);
a=-1;
for(....){
....
}
return String.valueOf(num);
In this way, the compiler should not notify you that error.
So, why is the compiler asking for another return statement?
Because you are missing a default return statement.
What if none of the conditions you have satisfied ? There must be something return default right ? That is what the issue is. That is why it is getting compiled when you uncomment that line.
Or even , you have an else statement, your program will have at least one satisfied return and it gets compiled too. Try it.
I had learnt that there can be no statements after the return statement.
This statement comes with some conditions. You have the return statement inside the if condition. So if your expression is not true, there is no way that the return gets execute.
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.
This might be a stupid question but we're beginners and I didn't find an answer to my problem so here it is: We're developping a file system (small based) and we have this method that is supposed to move files from one Directory to another. (Deleting the file or directory from one and adding to another.)
We're using ArrayLists to store the Items (Item is then superclass of Directory and File).
Because of the fact that everything has to be sorted alphabetically, the method to move contains a while loop to verify where the item has to be placed (no preferences to Directories or Files) but for some reason the break statement I inserted is ALWAYS executed (or at least that's what I think is the reason.) Thanks!
Here's the code:
if(item != null){
boolean bool = false;
int i = 0;
loop: while(!bool && i <= items.size()-1) {
if(i==0) {
if(checkIfAlphabetic(item.getName(), items.get(0).getName())){ items.add(0,item);
bool = true;
}
else{
break loop;
}
}
else if(checkIfAlphabetic(items.get(i-1).getName(), item.getName()) && checkIfAlphabetic(item.getName(), items.get(i).getName() )) {
items.add(i, item);
bool = true;
}
else i++;
}
if(!bool){
items.add(item);
}
setModificationTime();
}
I already excuse myself if there are some things unclear.
PS. Also for some reason the Item I want to add always gets added twice.
As requested, the code for checkIfAlphabetic:
private boolean checkIfAlphabetic(String search, String target){
int[] searchInt = search.codePoints().toArray();
int[] targetInt = target.codePoints().toArray();
int i = 0;
while(i<search.length() && i<target.length()){
if(searchInt[i] > targetInt[i]){
return false;
}
else if(searchInt[i] < targetInt[i]) return true;
else i++;
}
if(search.length() < target.length()){
return true;
}
else return false;
}
Your while loop is faulty. It will always stop after the first iteration, no matter what.
This is what happens in order of statements. This is pseudo-code, not Java. Don't copy/paste, it won't work.
boolean bool = false;
int i = 0;
// entering the while loop:
if (!bool && i <= items.size() - 1) // returns true. We go in the while loop.
if (i == 0) // returns true, we go in that block.
if (check... ) // if this returns true, this happens:
bool = true;
else // if the previous statement returns false, this happens:
break;
So here, if the check... returns false, we're gonna get out of the loop. Let's continue in the other case:
// nothing else happens inside the loop, so go back to the loop condition.
if (!bool && i <= items.size() - 1) // Hey, wait a minute, bool is true. So "not" true is false. The condition is therefore not met, let's leave the loop.
So this is what happens, after a single execution, no matter what, your code exits the loop. In your scenario, bool = true is the near absolute equivalent to a break.
This is what you need to fix.
If I had to write your code, this is how I'd do it:
List<Item> items = ... ;
java.util.Collections.sort(items, new ItemNameComparator());
private static class ItemNameComparator implements Comparator<Item> {
#Override
public int compare(Item a, Item b) {
return a.getName().compareTo(b.getName());
}
}
If you use Java 8:
List<Item> items = ...;
items.sort((a, b) -> a.getName().compareTo(b.getName()));
All the tools exist in the Java libraries, use them instead of reimplementing them again and again.
I want to know whether there is a performance difference in following two code blocks
1>
if(name == null) {
//something
}
if(name != null) {
//something
}
and
2>
if(name == null) {
//something
}
else {
//something
}
The first compares twice, the second compares once. The difference will not be noticeable, but it's there.
after benchmarkint it on 100.000.000 iterations, the first execution costs 719ms and the second 703ms.
I used a modulo so the conditions has to change every turn and avoid precompiled result. Please find the code below. I have noticed that this gap reduces when number of iterations increases.
public static void main(String[] args) {
Date start1 = new Date();
for(int i=0; i<100000000; i++) {
int it = i%2;
if(it == 0) {
double j = Math.random();
j++;
}
if(it != 0) {
double j = Math.random();
j++;
}
}
Date end1 = new Date();
Date start2 = new Date();
for(int i=0; i<10000000; i++) {
int it = i%2;
if(it == 0) {
double j = Math.random();
j++;
} else {
double j = Math.random();
j++;
}
}
Date end2 = new Date();
System.out.println((end1.getTime()-start1.getTime())+" / "+(end2.getTime()-start2.getTime()));
}
Just a brief comment to say that the compiler cannot optimize it in all cases, because name is visible within the first if block therefore it could have been modified in it, so it has to be checked again in the second if condition. Imagine this case:
if (name == null) {
// Does something
name = "Did it.";
}
if (name != null) {
// Does something else
}
It's clearly not equivalent to
if (name == null) {
// Does something
name = "Did it.";
} else {
// Does something else
}
If what you actually mean is that you should do something in one case and something else otherwise, please use if { ... } else { ... } - not just for (minimal) performance improvement, but also because your code should reflect what you actually mean.
Note that the two fragments are not necessarily equivalent, because the first block could re-assign name so that the second condition will also be true.
This can introduce hard to spot bugs, so I suggest that (before thinking about performance), you think about making the variable final if possible and use if/else when it makes sense (i.e. it should enter only one of the two branches) and chained if's when that makes sense (for example when the first if can establish a default value for the next one to use).
Yes there will, on the second one only one condition will be checked and on the first one two conditions would have to be checked.
An if clause that fails its evaluation has to make an "instruction jump" even if there is no else statement follwing it.
Assuming the first if is false, you'd be comparing these 2 execution scenarios:
1>
Check 1st condition
Skip to check 2nd condition
Do "something" inside the 2nd condition
2>
Check condition
Skip to "something" inside the else
Yes becuase both if cases will be evaluated in the first whereas only one if will be evaluated in the second.
yes, there will be a difference: in the second example, tehre's only 1 statement to be proofed, in the first one there are two.
but: the difference in performance will be absolutely minimal, in 99% of the cases you won't even notive any difference - make sure your code is as readable as it can be, thats much more important ;)
yes obviously the second code will perform inconsiderably better, because there is only one condition to check
I believe the compiler is smart enough to notice that the second if in the first example is redundant, so there won't be any performance change