Skip to content Skip to sidebar Skip to footer

What Is The Use Of Return Statement In A Void Function

I m new to java, what does return; mean? is it like break ? public void run() { if(imageViewReused(photoToLoad)) return; Bitmap bmp=getBi

Solution 1:

Yep, you can use it like a break.

Solution 2:

return ends the execution of the method in which it appears when it is called. For void methods, it simply exits the method body. For non-void methods, it actually returns a value (i.e. return X). Just be careful with try-finally: remember that the finally block will be executed even if you return in the try block:

publicstaticvoidfoo() {
    try {
        return;
    } finally {
        System.out.println("foo");
    }
}

// run foo in main
foo

This is a good reference for learning more about return.


is it like break?

Well in the sense that both statements 'end' a running process; return ends a method and break ends a loop. Nevertheless, it is important to know the differences between the two and when each should be used.

if the second imageViewReused(photoToLoad) returns true, BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad) won't be executed, right?

Correct - the method will "return" if the body of that if-statement is executed and no subsequent statements will be reached.

Solution 3:

Solution 4:

A function's execution is finished, when it comes to the return statement and then it returns back to its invoking code. In your case,

if imageViewReused(photoToLoad) is true, then the code block after return will not get executed.

Solution 5:

Here return act as end of function. You can avoid it by changing your code as,

publicvoidrun() {
        if(!imageViewReused(photoToLoad))
        {
          Bitmap bmp=getBitmap(photoToLoad.url);
          memoryCache.put(photoToLoad.url, bmp);
          if(!imageViewReused(photoToLoad))
          {
            BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
            Activity a=(Activity)photoToLoad.imageView.getContext();
            a.runOnUiThread(bd);
          }
    }

Post a Comment for "What Is The Use Of Return Statement In A Void Function"