Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to find difference between two numbers, diff must be Positive.

Java Code Example — Basic Programs

ADVERTISEMENT

Java Program to find difference between two numbers, diff must be Positive.

Objective

Write a Java program to find the positive difference between two numbers.

Algorithm / Approach

  1. Take two numbers as input.
  2. Use the ternary operator to check which number is larger.
  3. If x > y, subtract y from x; otherwise, subtract x from y.
  4. Print the positive difference.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter Num1: ");
  int x = s.nextInt();
  System.out.print("Enter Num2: ");
  int y = s.nextInt();
  int r = (x>y)?(x-y):(y-x);
  System.out.print("Diff. = "+r);
 }
}

Expected Output

Enter Num1: 12
Enter Num2: 15
Diff. = 3

Explanation of the Program

  • Two numbers, x and y, are evaluated.
  • The program uses the ternary operator (x > y) ? (x - y) : (y - x).
  • This ensures the smaller number is always subtracted from the larger one, guaranteeing a positive difference.

Complexity

Time Complexity O(1)
Space Complexity O(1)

Common Mistakes

  • Simply returning x - y, which can result in a negative difference.
ADVERTISEMENT