- Convert Java util.Date to sql.Date
This piece of code shows how to convert a java util Date into a sql Date for use in database.
java.util.Date util_date = new java.util.Date();
java.sql.Date sql_date = new java.sql.Date(util_date.getTime());
- Convert Array to Map
import java.util.Map;
import org.apache.commons.lang.ArrayUtils;
public class Main {
public static void main(String[] args) {
String[][] states = { { "UP", "Lucknow" }, { "MP", "Bhopal" },
{ "Maharashtra", "Mumbai" }};
Map stateCapitals = ArrayUtils.toMap(states);
System.out.println("Capital of Maharashtra is " + stateCapitals.get("Maharashtra"));
System.out.println("Capital of UP is " + stateCapitals.get("UP"));
}
}
- Regular Expression for validating an email
private final static Pattern EMAIL_PATTERN = Pattern
.compile("^([_A-Za-z0-9-\\+]*[a-zA-Z]+[_A-Za-z0-9-\\+]*)(\\.[_A-Za-z0-9-]+)*@"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
private boolean isEmail(String value)
{
return EMAIL_PATTERN.matcher(value).matches();
}
- Regular Expression for validating a password
private final static Pattern PASSWORD_PATTERN = Pattern
.compile("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{6,20})");
private boolean isValidPassword(String value)
{
int passwordLength = value.length();
if(passwordLength >= 6) {
return true;
} else {
return false;
}
}
- Convert String to date
java.util.Date = java.text.DateFormat.getDateInstance().parse(date String);
- Always try to use primitive datatypes instead of wrapper class
int a = 5;
int b = 5;
Integer a1 = new Integer(5);
Integer b1 = new Integer(5);
System.out.println(a==b);
System.out.println(a1==b1);
The first sysout will print true whereas the second one will print false. The problem is when comparing two wrapper class objects we cant use == operator. It will compare the reference of object and not its actual value.
Also if you are using a wrapper class object then never forget to initialize it to a default value. As by default all wrapper class objects are initialized to null.
Hope it helps someone!
0 Comment(s)