Java program to check that number is positive or negative using if-else and java ternary operator
- public class PositiveNumber {
- /**
- * Check that number is positive or negative
- *
- * @param args
- */
- public static void main(String[] args) {
- // using java if-else
- System.out.println("==== using java if-else ===");
- checkNumber(5); // Output -> Positive
- checkNumber(0); // Output -> Positive
- checkNumber(-3); // Output -> Negative
- // using java ternary operator
- System.out.println("==== using java ternary operator ===");
- checkNumberUsingTernary(5); // Output -> Positive
- checkNumberUsingTernary(0); // Output -> Positive
- checkNumberUsingTernary(-3); // Output -> Negative
- }
- // using java if-else
- private static void checkNumber(int number) {
- if (number >= 0) {
- System.out.println("Positive");
- } else {
- System.out.println("Negative");
- }
- }
- // using java ternary operator
- private static void checkNumberUsingTernary(int number) {
- String result = number >= 0 ? "Positive" : "Negative";
- System.out.println(result);
- }
- }
Output -
==== using java if-else ===
Positive
Positive
Negative
==== using java ternary operator ===
Positive
Positive
Negative
No comments:
Post a Comment