Return inside loops
📖 Scenario: Imagine you are checking a list of numbers to find if any number is even. Once you find the first even number, you want to stop checking and return that number immediately.
🎯 Goal: You will write a Java method that looks through an array of integers and returns the first even number it finds. If no even number is found, it returns -1.
📋 What You'll Learn
Create an integer array called
numbers with the exact values: 3, 7, 10, 5, 8.Create an integer variable called
notFound and set it to -1.Write a method called
findFirstEven that takes an integer array parameter called nums and uses a for loop with variable i to check each number.Inside the loop, use
return to immediately return the first even number found.If no even number is found after the loop, return the value of
notFound.In the
main method, call findFirstEven(numbers) and print the returned value.💡 Why This Matters
🌍 Real World
Finding the first item that meets a condition quickly is common in many programs, like searching for the first available seat or the first error in a list.
💼 Career
Understanding how to return early from loops helps write efficient code and is a common task in software development interviews and real projects.
Progress0 / 4 steps