[java] return in for loop or outside loop

Today, someone attended me to bad use of the return keyword in Java. I had written a simple for loop to validate that something is in an array. Supposing array is an array of length n, this was my code:

for (int i = 0; i < array.length; ++i) {
    if (array[i] == valueToFind) {
        return true;
return false;

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction. Therefore, better code would be:

int i = 0;
while (i < array.length && array[i] != valueToFind) {
return i != array.length;

The problem is that I can't come up with a proper explenation of why the first for loop isn't a good practice. Can somebody give me an explanation?

This question is related to java for-loop while-loop

The answer is

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.

That's incorrect, and suggests you should treat other advice from that person with a degree of skepticism.

The mantra of "only have one return statement" (or more generally, only one exit point) is important in languages where you have to manage all resources yourself - that way you can make sure you put all your cleanup code in one place.

It's much less useful in Java: as soon as you know that you should return (and what the return value should be), just return. That way it's simpler to read - you don't have to take in any of the rest of the method to work out what else is going to happen (other than finally blocks).

Now someone told me that this is not very good programming because I use the return statement inside a loop and this would cause garbage collection to malfunction.

That's a bunch of rubbish. Everything inside the method would be cleaned up unless there were other references to it in the class or elsewhere (a reason why encapsulation is important). As a rule of thumb, it's generally better to use one return statement simply because it is easier to figure out where the method will exit.

Personally, I would write:

Boolean retVal = false;
for(int i=0; i<array.length; ++i){
    if(array[i]==valueToFind) {
        retVal = true;
        break; //Break immediately helps if you are looking through a big array
return retVal;

There have been methodologies in all languages advocating for use of a single return statement in any function. However impossible it may be in certain code, some people do strive for that, however, it may end up making your code more complex (as in more lines of code), but on the other hand, somewhat easier to follow (as in logic flow).

This will not mess up garbage collection in any way!!

The better way to do it is to set a boolean value, if you want to listen to him.

boolean flag = false;
for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind) {
        flag = true;
return flag;

Some people argue that a method should have a single point of exit (e.g., only one return). Personally, I think that trying to stick to that rule produces code that's harder to read. In your example, as soon as you find what you were looking for, return it immediately, it's clear and it's efficient.

Quoting the C2 wiki:

The original significance of having a single entry and single exit for a function is that it was part of the original definition of StructuredProgramming as opposed to undisciplined goto SpaghettiCode, and allowed a clean mathematical analysis on that basis.

Now that structured programming has long since won the day, no one particularly cares about that anymore, and the rest of the page is largely about best practices and aesthetics and such, not about mathematical analysis of structured programming constructs.

The code is valid (i.e, will compile and execute) in both cases.

One of my lecturers at Uni told us that it is not desirable to have continue, return statements in any loop - for or while. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return or continue will take effect.

See Why is continue inside a loop a bad idea? for an example.

The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.

With regards to the Garbage Collection - I have no idea why this would be an issue.

Since there is no issue with GC. I prefer this.

for(int i=0; i<array.length; ++i){
    if(array[i] == valueToFind)
        return true;

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with for-loop tag:

List append() in for loop Prime numbers between 1 to 100 in C Programming Language Get current index from foreach loop how to loop through each row of dataFrame in pyspark TypeScript for ... of with index / key? Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply? Python for and if on one line R for loop skip to next iteration ifelse How to append rows in a pandas dataframe in a for loop? What is the difference between ( for... in ) and ( for... of ) statements? While, Do While, For loops in Assembly Language (emu8086) How to print star pattern in JavaScript in a very simple manner? TypeError: 'list' object cannot be interpreted as an integer Loop through a comma-separated shell variable ValueError: max() arg is an empty sequence Python iterating through object attributes Skip over a value in the range function in python Python loop for inside lambda Python: Total sum of a list of numbers with the for loop Check if object value exists within a Javascript array of objects and if not add a new object to array python - if not in list Java 8 forEach with index Are list-comprehensions and functional functions faster than "for loops"? Why is printing "B" dramatically slower than printing "#"? Excel VBA For Each Worksheet Loop How to find sum of several integers input by user using do/while, While statement or For statement How can I use break or continue within for loop in Twig template? How to loop over files in directory and change path and add suffix to filename break statement in "if else" - java Python: How to keep repeating a program until a specific input is obtained? How to increment a number by 2 in a PHP For Loop Is there a need for range(len(a))? Postgres FOR LOOP How can I loop through a List<T> and grab each item? How to get a index value from foreach loop in jstl How to write a function that takes a positive integer N and returns a list of the first N natural numbers Reverse a string without using reversed() or [::-1]? "for loop" with two variables? How to frame two for loops in list comprehension python How to add leading zeros for for-loop in shell? for or while loop to do something n times How to use continue in jQuery each() loop? Single Line Nested For Loops Multiple conditions in a C 'for' loop Java 8 Iterable.forEach() vs foreach loop How to find the maximum value in an array? Sum values from an array of key-value pairs in JavaScript Using for loop inside of a JSP Python For loop get index Could someone explain this for me - for (int i = 0; i < 8; i++)

Questions with while-loop tag:

While, Do While, For loops in Assembly Language (emu8086) MySQL Insert with While Loop Python loop to run for certain amount of seconds How to break a while loop from an if condition inside the while loop? How to find sum of several integers input by user using do/while, While statement or For statement Python: How to keep repeating a program until a specific input is obtained? Creating multiple objects with different names in a loop to store in an array list ORA-06502: PL/SQL: numeric or value error: character string buffer too small How to break out of a loop in Bash? for or while loop to do something n times A variable modified inside a while loop is not remembered Bash scripting, multiple conditions in while loop Printing one character at a time from a string, using the while loop SQL Server 2008 Insert with WHILE LOOP How to break out of while loop in Python? mysqli_fetch_array while loop columns How to write a simple Java program that finds the greatest common divisor between two numbers? How to kill a while loop with a keystroke? JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100 Break out of a While...Wend loop How do I plot in real-time in a while loop using matplotlib? Multiple conditions in WHILE loop return in for loop or outside loop while-else-loop How to check if all elements of a list matches a condition? How to get out of while loop in java with Scanner method "hasNext" as condition? Declaring variables inside or outside of a loop How to populate HTML dropdown list with values from database How do I exit a while loop in Java? Exit while loop by user hitting ENTER key Are "while(true)" loops so bad? Bash loop ping successful Foreach value from POST from form Why is “while ( !feof (file) )” always wrong? How can you run a command in bash over and over until success? How to use: while not in Do while loop in SQL Server 2008 For-loop vs while loop in R Which loop is faster, while or for? 'do...while' vs. 'while' Else clause on Python while statement For vs. while in C programming? Using a Loop to add objects to a list(python) While loop in batch Are loops really faster in reverse? Syntax for a single-line Bash infinite while loop How do you Make A Repeat-Until Loop in C++? Immediate exit of 'while' loop in C++ How to emulate a do-while loop in Python? How can I stop a While loop?