0
0
Javaprogramming~30 mins

Return inside loops in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the integer array
Create an integer array called numbers with these exact values: 3, 7, 10, 5, 8.
Java
Need a hint?

Use int[] numbers = {3, 7, 10, 5, 8}; to create the array.

2
Create the notFound variable
Create an integer variable called notFound and set it to -1.
Java
Need a hint?

Write int notFound = -1; to create the variable.

3
Write the findFirstEven method
Write a method called findFirstEven that takes an integer array parameter called nums. Use a for loop with variable i to check each number. Inside the loop, use return to immediately return the first even number found. After the loop, return the value of notFound.
Java
Need a hint?

Use a for loop and check if each number is even using nums[i] % 2 == 0. Return the number immediately if even.

4
Call the method and print the result
In the main method, call findFirstEven(numbers) and print the returned value using System.out.println.
Java
Need a hint?

Use System.out.println(findFirstEven(numbers)); inside main to print the first even number.