How to test for an integer in Java

Java doesn’t have a tryParse method for integers. However, you can verify for an integer using the following method: public static boolean isInteger(String s) { try { Integer.parseInt(s); } catch(NumberFormatException e) { return false; } // only got here if we didn’t return false return true; }

How to properly validate email addresses in Java

If you are using Java, the InternetAddress class will validate your emails against the RFC 822 standard. The function below will filter out most invalid emails quickly: public static boolean isValidEmailAddress(String email) { try { new InternetAddress(email).validate(); } catch (AddressException ex) { return false; } return true; } This regex will also match email adresses. […]

How to get an Integer from a Java resultset

By default, ResultSet.getInt(…) only returns an int. If the database value is null, it will return 0. This is already covered in the documentation: “The default for ResultSet.getInt when the field value is NULL is to return 0″. This is also the case for resultset.getFloat(). This irritating behavior can easily be fixed with the wasNull […]

How to add days to a date in Java

To add years, days, hours or minutes to a Date object in Java, you need to use the java.util.Calendar class. //Adds one day to the current date Calendar cal = Calendar.getInstance(); // The current date cal.add(Calendar.DAY_OF_MONTH, 1); Date date = cal.getTime(); // 1 day in the future If you want to substract time, simply use […]

How to create a Date object for a specific date in Java

Creating a new date in Java is quite simple. Use the Calendar class to quickly create your Date object //Generate a date for Jan. 9, 2013, 10:11:12 AM Calendar cal = Calendar.getInstance(); cal.set(2013, Calendar.JANUARY, 9); //Year, month and day of month Date date = cal.getTime(); If you also need to set the time, you can […]