-2

can we code to identify positive number and negative number in java using ternary operator.

import java.util.*;
public class negative{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        (a>=0)?System.out.print("positive number"):System.out.print("negative number");

    }
}
import java.util.*;
public class negative{
    public static void main(String args[]){
        Scanner sc=new Scanner(System.in);
        int a=sc.nextInt();
        (a>=0)?System.out.print("positive number"):System.out.print("negative number");

    }
}
  • 2
    What is the difference between both code snippets? Did you try it? – pzaenger Dec 11 '22 at 15:36
  • 2
    not sure if that what yo looking for or not System.out.print((a >= 0) ? "positive number" : "negative number"); –  Dec 11 '22 at 15:52

1 Answers1

2

In Java, you cannot use the Ternary operator like this. The ternary operator should always result in some value in java. This code will cause an error because of the print statement.

One other way of using ternary opertor for above checking positive or negative number is this way (it wont cause an error):

import java.util.*;

public class Negative {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    int a = sc.nextInt();
    System.out.println((a >= 0) ? "positive number" : "negative number");
  }
}
pzaenger
  • 11,381
  • 3
  • 45
  • 46