Saturday, 10 October 2020

Java program to check that number is positive or negative

 Java program to check that number is positive or negative using if-else and java ternary operator

  1. public class PositiveNumber {
  2.  
  3. /**
  4.   * Check that number is positive or negative
  5.   *
  6.   * @param args
  7.   */
  8. public static void main(String[] args) {
  9.  
  10. // using java if-else
  11. System.out.println("==== using java if-else ===");
  12. checkNumber(5); // Output -> Positive
  13. checkNumber(0); // Output -> Positive
  14. checkNumber(-3); // Output -> Negative
  15.  
  16. // using java ternary operator
  17. System.out.println("==== using java ternary operator ===");
  18. checkNumberUsingTernary(5); // Output -> Positive
  19. checkNumberUsingTernary(0); // Output -> Positive
  20. checkNumberUsingTernary(-3); // Output -> Negative
  21. }
  22.  
  23. // using java if-else
  24. private static void checkNumber(int number) {
  25. if (number >= 0) {
  26. System.out.println("Positive");
  27. } else {
  28. System.out.println("Negative");
  29. }
  30. }
  31.  
  32. // using java ternary operator
  33. private static void checkNumberUsingTernary(int number) {
  34. String result = number >= 0 ? "Positive" : "Negative";
  35. System.out.println(result);
  36. }
  37. }
Output -
====  using java if-else ===
Positive
Positive
Negative
====  using java ternary operator ===
Positive
Positive
Negative


No comments:

Post a Comment