Saturday, 10 October 2020

Java program to Check that number is divisible by 9 or not

 Java program to Check that number is divisible by 9 or not using if-else and ternary operator 


  1. public class DivisibleByNumber {
  2.  
  3. /**
  4.   * Check that number is divisible by 9 or not
  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(37); // Output -> Not divisible
  13. checkNumber(0); // Output -> Divisible
  14. checkNumber(27); // Output -> Divisible
  15.  
  16. // using java ternary operator
  17. System.out.println("==== using java ternary operator ===");
  18. checkNumberUsingTernary(37); // Output -> Not divisible
  19. checkNumberUsingTernary(0); // Output -> Divisible
  20. checkNumberUsingTernary(27); // Output -> Divisible
  21. }
  22.  
  23. // using java if-else
  24. private static void checkNumber(int number) {
  25. if (number % 9 == 0) {
  26. System.out.println("Divisible");
  27. } else {
  28. System.out.println("Not divisible");
  29. }
  30. }
  31.  
  32. // using java ternary operator
  33. private static void checkNumberUsingTernary(int number) {
  34. String result = number % 9 == 0 ? "Divisible" : "Not divisible";
  35. System.out.println(result);
  36. }
  37. }
Output -
====  using java if-else ===
Not divisible
Divisible
Divisible
====  using java ternary operator ===
Not divisible
Divisible
Divisible


No comments:

Post a Comment