Java and zip code example
Recently, answered an question about leading zero problem ZipCode, what is the most proper data type for country’s zip code?
1. ZipCode – int
In Java, some claimed it should declare as “int”, and use DecimalFormat to format and display the leading zero. For example,
package com.mkyong;
import java.text.DecimalFormat;
public class ZipCodeExample {
public static void main(String[] args) {
int zip = 123;
DecimalFormat format = new DecimalFormat("00000");
System.out.println(format.format(zip));
}
}
Note
Remember remove the leading zero in zip code, Java will treat it as Octal, and display different result.
Remember remove the leading zero in zip code, Java will treat it as Octal, and display different result.
2. ZipCode – String
Above solution is working, but i more prefer to use String as the data type of zip code. This is more flexible and scalable to hanlde other unknown zip code format in other country.
package com.mkyong;
public class ZipCodeExample {
public static void main(String[] args) {
String zip = "00123";
System.out.println(zip);
}
}
Do you have other suggestion on zip code?
Hi writing from Turkey, U have many followers in there. I love your tutorials. Thanks.
My suggestion is
String zip=”123″;
int zeros=5-zip.length();
String Zip=””;
for(int i=0;i<zeros;i++)
Zip+="0";
Zip+=zip;
System.out.println(Zip);
A zip code should be encapsulated in a class of its own. IT’s a value, so the class should be immutable. Furthermore, factory methods and/or constructors should check, if the zip code is well-formed, ideally also, if the zip code in questions actually exists. A proper toString method ensures, that the class can be seamlessly used with MessageFormat or EL.
Any additional information given by the code (e.g. the area information embedded in the U.S. ZIP+4 system or the department number in the French code) can be safely encapsulated as a method as opposed to an unsafe string manipulation.
Whilst most countries use more ore less elaborate number schemes, some use letter/number schemes (e.g. GB, NL). On top of that, those schemes can change over time, like the German codes, where two different systems (east and west) were transformed into a unified one. Using simple strings with this kind of versioning is troublesome at best.
Hi Frisian, you research a lot on zip code, the format is much complicated than i thought. For simple web app , a String should be enough, for developer who want to developer zip code related function, your way seem to work great!
The starting step would be as easy as:
These nine lines of code give you:
– immutability
– type safety
– hiding the implementation
– an undisputed single place for extensions, formatting and validations
– no refactoring nightmares
In my experience, as soon as one starts dealing with addresses, the application is there to stay, so one better designs for the long term.