user3746295
user3746295

Reputation: 101

Test if the number is prime in Java

Test if the number is prime or not:

This is my code:

public static boolean isPrime(int x){
      if(x<=1) 
         return false;
      else if(x==2) 
         return true;
      else {
         for(int i=2; i<=x/2; i++){                        
             if(x%i==0) 
                return false;
         }
         return true;
      }
   }

My question is: the last statement 'return true', if the number is a prime, then no false return, but if the number is not a prime, then during the for loop, there will be a false return. And when the loop is finished, the program execute the statement below for loop--‘return true’. So I am wondering if the returned true will cover the returned false that happened during for loop. (Although when I am testing this code, the code works well for testing a number is prime or not, but I don't know why)

Upvotes: 0

Views: 368

Answers (5)

Dici
Dici

Reputation: 25950

A return statement makes the method exit, so if "return false" is executed the method exit returning false and return true will never be executed.

Upvotes: 0

Barranka
Barranka

Reputation: 21047

Why do you start the iteration on zero?

Consider what would happen when i = 1:

if(x % i == 0)    // i = 1, so x % i will be zero
    return false;

Even more, consider what would happen when i = 0:

if(x % i == 0)    // how would you define x % 0!?

Start the iteration on 2:

// ...
for(int i = 2; i <= x / 2; i++) {
    if(x % i == 0)
        return false;
}
return true;
// ...

Upvotes: 1

kirti
kirti

Reputation: 4609

if(x%i==0) return false;

if this condition comes true then it will return false and will not execute anything after that

and when above condition will be false it wil return true.

Upvotes: 0

Brian
Brian

Reputation: 17299

return false ends the method. When we say return, that means "stop what you're doing and give this value back to the method that called us."

Cases where this doesn't happen

  • try-finally blocks, any return statement or exception thrown in the finally block of a try block will override the returned value.
  • System.exit, this method never returns, so any statements after an exit call will not be executed.

Upvotes: 0

Eran
Eran

Reputation: 393771

After return false (or any return statement), the method will return without executing anything else, so return true won't be reached in this case, and therefore your code works fine.

Upvotes: 5

Related Questions