Java – Calculate Execution Time

[code lang=”java”]
import java.util.Date;

public class TimeMillisecond {
public static void main(String[] argv) {

long lStartTime = new Date().getTime(); //start time

String sArray1[] = createArray(); //method execute

long lEndTime = new Date().getTime(); //end time

long difference = lEndTime – lStartTime; //check different

System.out.println("Elapsed milliseconds: " + difference);

}

static String [] createArray(){

String sArray[] = new String [100000];

for(int i=0; i<100000; i++)
sArray[i] = "Array " + i;

return sArray;
}
}[/code]


Java – Username Validation with Regular Expression

Username Regular Expression Pattern:

^[a-z0-9_-]{3,15}$

Description:

^    # Start of the line
[a-z0-9_-] # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen
{3,15} # Length at least 3 characters and maximum length of 15
$ # End of the line

Example:
[code lang=”java”]import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UsernameValidator {

private Pattern pattern;
private Matcher matcher;

private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";

public UsernameValidator() {
pattern = Pattern.compile(USERNAME_PATTERN);
}

/**
* Validate username with regular expression
* @param username username for validation
* @return true valid username, false invalid username
*/
public boolean validate(final String username) {

matcher = pattern.matcher(username);
return matcher.matches();

}
}[/code]


Java – Open Browser in Windows or Linux

A very useful Java code, to open a web browser from Java application in windows or Linux.
[code lang=”java”]
public class StartBrowser {

public static void main(String args[])
{
String url = "http://www.google.com";
String os = System.getProperty("os.name").toLowerCase();
Runtime rt = Runtime.getRuntime();

try {

if (os.indexOf( "win" ) >= 0) {

// this doesn’t support showing urls in the form of "page.html#nameLink"
rt.exec( "rundll32 url.dll,FileProtocolHandler " + url);

} else if (os.indexOf( "mac" ) >= 0) {

rt.exec( "open " + url);

} else if (os.indexOf( "nix") >=0 || os.indexOf( "nux") >=0) {

// Do a best guess on unix until we get a platform independent way
// Build a list of browsers to try, in this order.
String[] browsers = {"epiphany", "firefox", "mozilla", "konqueror",
"netscape","opera","links","lynx"};

// Build a command string which looks like "browser1 "url" || browser2 "url" ||…"
StringBuffer cmd = new StringBuffer();
for (int i=0; i<browsers.length; i++)
cmd.append( (i==0 ? "" : " || " ) + browsers[i] +" \"" + url + "\" ");

rt.exec(new String[] { "sh", "-c", cmd.toString() });

} else {
return;
}
} catch (Exception e) {
return;
}
return;

}
[/code]