-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?

24
  • 6
    What value are you expecting? May 31, 2014 at 18:22
  • Unclear asking. See "minus is an operator", converting an operator into number is meaning less. May 31, 2014 at 18:23
  • how a "-" can be converted to an integer? May 31, 2014 at 18:24
  • 1
    You'll get NumberFormatException in this case. What else can you expect? May 31, 2014 at 18:24
  • 2
    @Mr.Sarunov: Ok, you should edit your question to explain that. May 31, 2014 at 18:34

2 Answers 2

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.

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.

3
  • This doesn't seem like what was being asked.
    – Makoto
    May 31, 2014 at 18:28
  • @Makoto I added a comment about "-" not being an integer. I provided an alternative if it was what he was looking for. May 31, 2014 at 18:29
  • @Mr.Sarunov int=2; isn't valid java. What are you trying to do? Can you add more detail to your question? May 31, 2014 at 18:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.