Java program to Check that number is divisible by 9 or not using if-else and ternary operator
- public class DivisibleByNumber {
- /**
- * Check that number is divisible by 9 or not
- *
- * @param args
- */
- public static void main(String[] args) {
- // using java if-else
- System.out.println("==== using java if-else ===");
- checkNumber(37); // Output -> Not divisible
- checkNumber(0); // Output -> Divisible
- checkNumber(27); // Output -> Divisible
- // using java ternary operator
- System.out.println("==== using java ternary operator ===");
- checkNumberUsingTernary(37); // Output -> Not divisible
- checkNumberUsingTernary(0); // Output -> Divisible
- checkNumberUsingTernary(27); // Output -> Divisible
- }
- // using java if-else
- private static void checkNumber(int number) {
- if (number % 9 == 0) {
- System.out.println("Divisible");
- } else {
- System.out.println("Not divisible");
- }
- }
- // using java ternary operator
- private static void checkNumberUsingTernary(int number) {
- String result = number % 9 == 0 ? "Divisible" : "Not divisible";
- System.out.println(result);
- }
- }
Output -
==== using java if-else ===
Not divisible
Divisible
Divisible
==== using java ternary operator ===
Not divisible
Divisible
Divisible
No comments:
Post a Comment