2

I have set "phone" as int of 10 digit in database and take input as text which I parse using

String phone1=request.getParameter("phone");

int phone =Integer.parseInt(phone1);

but it does not work why?

6
  • What the exact error that you faced? Commented Mar 6, 2014 at 12:40
  • 4
    What doesn't work? What's the content of the string? Note that phone numbers could start with a + if the contain the country code or contain other characters like spaces or minues, e.g. 301-555-42. And what about reconstructing the string? Leading zeros would be stripped. Commented Mar 6, 2014 at 12:41
  • Please define does not work Commented Mar 6, 2014 at 12:41
  • 4
    not all 10-digit numbers can fit in an integer. Commented Mar 6, 2014 at 12:44
  • 4
    Phone numbers should remain as Strings not integers, there are way more unnecessary problems if you want phone numbers as integers. Commented Mar 6, 2014 at 12:45

3 Answers 3

6

In Java you can store in int variable numbers in range -2147483648 to 2147483647. This is not enough for your 10-digit telephone numbers. You can easily fix this using long:

long phone = Long.parseLong(phone1);

On the other hand I would rethink using number data types for storing telephone numbers. Why?

  • Because you can't store leading zeros if your numbers are not always exact 10 digits long.
  • Because you loose formating, like "123-456-..."
  • Because you can't save things like # or p, that are valid and used sometimes in phone numbers
Sign up to request clarification or add additional context in comments.

Comments

0

If your phone is in format sth like (+3212-45-356) or sth else. Before you parse it you have to make that string clean from that 'special characters'. Try parsing it to long.

String phone1=request.getParameter("phone");

Long phone =Integer.parseLong(phone1.replace("\\+","").replace.("-",""));

Comments

-1

One problem is, that a preceding 0 will make the number, octal, in base 8; and then digits 8 and 9 cause a NumberFormatException. Base 8 allows to represent 3 bits 0-1 with one digit 0-7.

long phone = Long.parseLong(phone1, 10);

This forces base 10.

Of course, as one does not calculate with phone numbers, and by this conversion looses preceding zeroes, this might be less suited. In many countries international numbers are entered with either preceding + or 00.

2 Comments

Looking into JDK sources: int parseInt(String s) {return parseInt(s,10);}
@BorisBrodski: you are right, I now remember that Sun changed it; no longer default octal when with 0.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.