-2

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?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
vsarunov
  • 1,433
  • 14
  • 26

2 Answers2

2

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.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0

Integer.valueOf("-") will throw a NumberFormatException because "-" by itself isn't a number. If you did "-1", however, you would receive the expected value of -1.

If you're trying to get a character code, use the following:

(int) "-".charAt(0);

charAt() returns a char value at a specific index, which is a two-byte unicode value that is, for all intensive purposes, an integer.

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145