cresjoy cresjoy - 4 months ago 7
Java Question

Having trouble understanding return type placement( Big Java Ex 6.8)

Currently on the chapter in my book where we talk about for loops and loops. I have sometimes come across an issue where the method needs me to return something. For example consider my code
below. Basically the exercise is to get all the factors in ascending order. Now heres the issue

As you can see I need a return statement outside of the for loop. Now I guess my book didn't exactly explain this properly, or I didn't understand the concept
of return properly in java, but does our return statement always have to be in the most outer indentation if you will?

The thing is, I don't really want to return anything outside of the for loop. I just want to return

i
upon that condition. Why doesn't java let me do this?
Whats a good counter-action?

Ever since I started learning loops and for loops, I have been having trouble understanding this. I guess I could just
system.out.println(i)
instead of returning it? But then what should I
return
? I could also make it a
void
type, and then make another method to print it, I guess?

class factors{

private int num;

public factors(int num)
{
this.num = num;
}

public int getFactors()
{
for(int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
return i;
}
}
// I NEED TO PUT A RETURN STATEMENT HERE

}
}

public class test{
public static void main(String [] args)
{
factors fact = new factors(20);
System.out.println(fact.getFactors());
}
}


IT WORKS NOW ( I dont particularly like my solution)

class factors{

private int num;

public factors(int num)
{
this.num = num;
}

public void getFactors()
{
for(int i = 1 ; i<num ; i++)
{
if (num % i == 0)
{
System.out.println(i);
}

}
}





}

public class test{
public static void main(String [] args)
{
factors fact = new factors(20);
fact.getFactors();
}
}

Answer

The thing is, I don't really want to return anything outside of the for loop. I just want to return i upon that condition. Why doesn't java let me do this?

Java lets you do that. There is nothing wrong with returning inside the loop upon reaching the condition.

Java allows you to have multiple return statements, so adding another return 0; after the loop is allowed.

Java returns once it hits the first return statement, and other return statements are not executed (the method isn't executed anymore) (except for some rare edge cases with try-catch and return, but thats another story entirely).

But why is it required?

Java requires that for all possible paths there exists a return with the proper type. Even if you yourself can proof mathematically that the path Java complains about is never taken, the compiler might not be able to prove that the path is not possible at runtime. So you simply need to add an return there with a dummy value.

In your concrete example, there is a condition in which the loop gets never executed. If num <= 0, then the loop condition is never satified and the entire loop body is skipped. Without the return,the method is invalid, because you can't return nothing from an method with return type int.

So, in your example, the compiler is actually smarter then you, and prevents you from making a mistake - because it found the path you thought wouldn't occur.

new factors(-1).getFactors(); // you don't check the passed value at all ;)

From your comments, it seems that you want to return all factors. In java, you return once, and only once, from a function. This means you have to aggregate the results and return a List or array of values:

public List<Integer> getFactors(int num) {
    List<Integer> factors = new ArrayList<>();
    for (int i = 1 ; i<num ; i++)
    {
        if (num % i == 0)
        {
            factors.add(i);
        }
    }
    return factors;
}

public static void main(String[] args) {
    System.out.println(Arrays.toString(new factors(20).getFactors());
    // prints a comma-separated list of all factors
}
Comments