Question

Can Anyone explain me how this code works.

  // Method returns null if bitmap not available 
    public Bitmap getBitMap(long id) {

        for ( Bitmap item : myBitmaps.keySet() ) {
            if ( item != null) {
                if ( item.getId() == id ) {
                    return item;
                }

            }
        }

        return null;

how come its possible to use two return (including one inside if block) in a function.sorry I am new to java.

No correct solution

OTHER TIPS

Simple.

The first return statement returns the item only if the two nested conditions are satisfied.

Once your loop is over (aka the two nested conditions are not satisfied), the second return statement triggers and returns null.

In short, if your myBitmaps array or Collection contains a Bitmap that is not null and whose id equals the given id for the method, that Bitmap instance is returned.

Otherwise, null is returned.

As fge mentions, a method has to fulfill all possible return paths (save for exceptional conditions).

If null was not returned outside your loop, the code would not compile.

This would happen because if your conditions were not fulfilled, your loop would terminate without returning anything, and so would your method.

When a return statement is called the function exits. You can have multiple return statements on different places because you might want to return different values depending on what happened in the function.

At a time only one return works. When return item executes it actually returns the control to the statement line from where this method was called. In this case return null will not get execute. And when For loop executed whole and nothing happened at that time return null statement will get execute.

So at a time only one return statement will get execute, no matter if there is more than one return statements in a method.

Basically there are 3 steps:

  1. Loop every Bitmap presents in myBitmaps
  2. If the bitmap is 'valid' (means not null) continue. Otherwise, let's iterate to the next Bitmap.
  3. If the id is the one you were looking at, return the Bitmap.

So what it does is: Get the Bitmap with the specified id if it exists.

the if condition should be like this:

 if ( item != null && item.getId() == id){
    return item;
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top