Java Program to check a number is positive or negative

Here we are explaining how to write a java program to check a number is positive or negative. This is a simple program and easy to understand. So first we have to read the number from the user and we will check the number is greater than zero, if true then we will display the number as positive. If the number is less than zero then we will display the number as negative. Else we will display the number is neither positive nor negative

What is the syntax of the if-else statement?

The syntax of the if-else statement is shown below.

if (Condition)
{
 // Block of codes, which is executed when the condition is true.
}
else
{
 // Block of codes executed when the condition is false.
}
 

How to implement the java program to check whether a number is positive or negative?

First, we have to declare the class NumberCheck.Then we declare the integer variable, number. Read the number from the user into the variable number. Then check if number>0, then display the number is positive.Else check if number < 0,then display the number is negative.Else display the number is neither positive nor negative.

ALGORITHM

STEP 1: Declare the class NumberCheck with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variable number.

STEP 4: Read the number from the user into the variable number.

STEP 5: By using the if condition checks if number > 0 if true then display the number is positive.

STEP 6: Else if number < 0 then display the number is negative.

STEP 7: Else display the number is neither positive nor negative.

 

Java Source Code

                                          import java.util.Scanner;

public class NumberCheck {
 public static void main(String args[]) {
  int number;
  System.out.println("Enter the number:");
  Scanner sc = new Scanner(System. in );
  number = sc.nextInt();

  if (number > 0) {
   System.out.println("The Number is positive");
  } else if (number < 0) {
   System.out.println("The Number is negative");
  } else {
   System.out.println("The number is neither positive nor negative");
  }
 }
}
                                      

OUTPUT

Enter the number:-6
The Number is negative