0

Why does return statement is throwing error when used Math function in a method.

public class HCF_1 {
    
    static int hcf(int a, int b)
    {
        int res = Math.max(a,b);
        while(true)
        {
            if(res%a==0 && res%b==0)
                return res;
            else res++;
        }
        return res;
    }
    public static void main(String[] args) {
        
        System.out.println(hcf(5,25));
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
Gaurav
  • 19
  • 1

3 Answers3

2

This may or may not be helpful, but IMO while(true) statements are a real code smell. You can rewrite this method as:

public class HCF_1 {
   
   static int hcf(int a, int b)
   {
       int res = Math.max(a,b);
       while(res % a != 0 || res % b != 0)
           res++;
       return res;
   }
   public static void main(String[] args) {
       System.out.println(hcf(5,25));
   }
}

Now there is only a single return statement, and no shortcuts.

Note that the operations !(res % a == 0 && res % b == 0) are the same as res % a != 0 || res % b != 0, due to to the properties of Boolean Logic: ~(A AND B) == ~A OR ~B.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Skaman Sam
  • 628
  • 4
  • 13
0
public class HCF_1 {
        
        static int hcf(int a, int b)
        {
            int res = Math.max(a,b);
            while(true)
            {
                if(res%a==0 && res%b==0)
                    return res;
                else res++;
            }
            return res; //last line of the method hcf is unreachable
        }
        public static void main(String[] args) {
            
            System.out.println(hcf(5,25));
        }
    }

The while loop is a never-ending loop and is escaped only under the condition mentioned inside if block which is a return statement and not a break statement. Therefore the last line of the method hcf return res; is unreachable in any condition.

Aayush Sahu
  • 126
  • 1
  • 1
  • 10
0

the segement of your code in if-else the cause to be unreachable for the last line of your return res, you so have to do 2 things:

  1. remove the return inside if and add break instead.
  2. return the last line of method which is return res;
public class HCF_1 {

    static int hcf(int a, int b) {
        int res = Math.max(a, b);
        while (true) {
            if (res % a == 0 && res % b == 0)
                break;
            else
                res++;
        }
        return res;
    }

    public static void main(String[] args) {

        System.out.println(hcf(5, 25));
    }
}
Mustafa Poya
  • 2,615
  • 5
  • 22
  • 36