In this tutorial you will learn about the Java Program to check if a number is Positive or Negative and its application with practical example.
In this tutorial, we will learn to create a Java Program to check if a number is Positive or Negative using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is Positive and Negative Number.
A number which is greater than zero it is a positive number (Number>0).
else number which is less than zero it is negative number (Number<0).
A number which is equivalent to zero it is Not positive nor negative number (Number==0).
Java Program to check if a number is Positive or Negative
In this program we will find whether a number is positive, negative or zero series using if else statement. We would first declared and initialized the required variables. Next, we would prompt user to input any number. Later we will find that number is positive,negative or zero.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Java program to fing given number is negative positive or Zero import java.util.Scanner; public class Positive_Negative_number { public static void main(String[] args) { int number; //declaring and taking value from user.. Scanner sc = new Scanner(System.in); System.out.print("Enter any number "); number = sc.nextInt(); //checking conditon for positive number if(number>0) { System.out.println("The number is positive."); } //checking conditon for Negative number else if(number<0) { System.out.println("The number is negative."); } //checking conditon for number is Zero.. else { System.out.println("The number is zero."); } } } |
Output
Positive Number
Negative Number
Zero
In the above program, we have first declared and initialized a set variables required in the program.
- number =It will hold number given by user.
After that we take a numbers from user and find that a number is positive ,negative or Zero.
after that we check if number is greater than zero it means number is a positive number as shown in image below.
if condition falls compiler move to next statement that is if number is less than zero than it is negative number.
else number is Zero .