For these types of problems, why do we always need to check the false case first and then return true?
Write a method that tests if two arrays contain the same element in the same order or not.
Returns false if not.
You only want to iterate through the list for as far as you have to. So this returns when the first occurrence of the test case is true, thus avoiding reading the remainder of the list. You'll only know if you need to return 'true' if you manage to make it through the whole list.
A return statement returns from the method call itself (Not always though, there could be code in a finally block that would be executed), while a break statement breaks the current loop being executed and the code continues after that.
If you want to write the loop in structured form, your method would look like this:-Line 3 tests whether you are comparing an object with itself, in which case there is no need to iterate the arrays. Lines 4‑11 are only executed if you haven't already proven the two objects are equal. Line 6 tests that the lengths are the same; as you (correctly) surmised, two arrays can't be equal and have different lengths. If the lengths are different, the loop won't start. Line 8 will cause your loop to stop whenever you encounter two different numbers.
By the way, if you look for the most dubious classification of methods known to modern science, you will find that method is a 1368, so it should probablly be marked static.
what i'm confused is that if the return statement on the last line is "return true" wouldn't the loop always return true b/c after the for loop it will go the next line which is"return true"?
A loop does not return anything since it simply defines a flow of execution. A method returns something and that happens when a return statement is executed. Once a method has returned, no other statement in that method will be executed.
Think of the method as a room and any return statement in that method as a exit door from that room. Once you exit from the room, nothing else in the room will be executed. In the code you gave, there are three exit points: lines 4, 9, and 13 above. Once you hit a return statement and exit from the method, no other statement in the method will be executed. It doesn't matter if the for-loop has not completed yet, once you hit that return statement, the entire method will be terminated, for-loop and all.
Basically, the logic is like this:
If the arrays are not equal in length, then it's guaranteed that they are not the same, so exit the method and return false.
Loop to compare elements of the arrays. If any two elements are not equal, then exit the method immediately and return false since one difference is enough to guarantee that the arrays are not the same and there is no need to compare the rest of the elements.
If you get past the for-loop without returning false, then that means no differences were found and the two arrays are the same. Therefore, return true.