Search code examples
javastringintegersign

Java - Construct a signed numeric String and convert it to an integer


Can I somehow prepend a minus sign to a numeric String and convert it into an int? In example:

If I have 2 Strings :

String x="-";
String y="2";

how can i get them converted to an Int which value is -2?


Solution

  • You will first have to concatenate both Strings since - is not a valid integer character an sich. It is however acceptable when it's used together with an integer value to denote a negative value.

    Therefore this will print -2 the way you want it:

    String x = "-";
    String y = "2";
    int i = Integer.parseInt(x + y);
    System.out.println(i);
    

    Note that the x + y is used to concatenate 2 Strings and not an arithmetic operation.