Archive for the 'JavaUsage' Category


Java.util.regex Example

Jun 27, 2012 in Java, JavaUsage

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegExp1 {
    private static final Pattern snRegExpPattern = Pattern.compile("^[A-Za-z0-9-_]+");

    public static void main(String []args) {
        checkMatch( "" );

        checkMatch( "abde" );

        checkMatch( "gh+ij" );

        checkMatch( "kl_mn" );

        checkMatch( "op-qr" );

        checkMatch( "st93uv" );

        checkMatch( "st93uv&" );


    private static void checkMatch(String name) {
        Matcher reMatcher = snRegExpPattern.matcher(name);
        if (! reMatcher.matches() ) {
            System.out.println("Error on " + name);
        else {
            System.out.println("OK on " + name);

Expected output :

Error on
OK on abde
Error on gh+ij
OK on kl_mn
OK on op-qr
OK on st93uv
Error on st93uv&

Hash table notes..

Aug 26, 2009 in Engineering, Java, JavaUsage, Software


  • Hash tables are backed by arrays.
  • A hash function is used to map the keys to an index within the backing array.
  • Put, Get, Delete operations all run in constant ( O(1) ) time.
  • Hash function determines performance.
  • Even with the best hash function, collisions can occur.
  • Main advantage of HTs over other data structures is speed.
  • Growing HTs need to be rehashed but the cost is amortized by constant cost of ‘put’.
  • Should not use HTs for small data sets, but everybody does.
  • Rehashing should occur when the load factor (occupied array slots / array size) reaches over .75.

Java example of basic cache (LRU) using LinkedHashMap ..

Aug 24, 2009 in Algorithms, Java, JavaUsage


import java.util.Map;
import java.util.LinkedHashMap;

public class t1 {

    final int MAX_ENTRIES = 2;

    Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
        // This method is called just after a new entry has been added
        public boolean removeEldestEntry(Map.Entry eldest) {
            System.out.println("eldest: " + eldest.getKey() + "=" + eldest.getValue());
            return size() > MAX_ENTRIES;

    public void cacheAdd(String pkey, String pstr) {
        // Add to cache
        cache.put(pkey, pstr);

    public static void main(String[] args) {
        t1 ot1 = new t1();
        ot1.cacheAdd("k1", "str1");
        ot1.cacheAdd("k2", "str2");
        ot1.cacheAdd("k3", "str3");
        ot1.cacheAdd("k4", "str4");

    /* --
// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
    // Object not in cache. If null is not a possible value in the cache,
    // the call to cache.contains(key) is not needed

// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);
-- */


Also, see
. . .

Java pattern matching example..

Jun 19, 2009 in Java, JavaUsage

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class TestPattern {
    public static void main(String[] args) {
	String pin = "1234567";
	String pinPattern = "[0-9]+";
	String result = null;

	Pattern pattern = Pattern.compile(pinPattern);
	Matcher matcher = pattern.matcher(pin);

	result = "";
	while(matcher.find()) {
	    result +=;
	if (result.equals(pin)) {
	    result = "PIN accepted";
	else {
	    result = "PIN invalid";

Notes from ‘Java Web Services’ book ..

Jun 18, 2009 in Books, Java, JavaUsage

SOAP – Simple Object Access Protocol
WSDL – Web Services Description Language
UDDI – Universal Discovery, Description and Integration

Major characteristics:
— XML-Based
— Loosely coupled – interfaces may change without loss of service.
— Coarse-grained – provide high-level business functions.
— Both synchronous and Asynchronous
— Supports RPC (Remote Procedure Calls)
— Supports document exchange

Interface vs Abstract Class ..

Apr 23, 2009 in Engineering, Java, JavaUsage, Software

  • — Inheritance from anything (including abstract)
    should be a function of the business model.
  • — If a class does not _really_ inherit from
    an abstract, one should not use it.
  • — Use interface to avoid the problem of multiple
  • — Use interface to improve modularity.. if one
    uses an abstract class and the class changes,
    it may break subclasses.
    (not method signatures but logic/code.. changing
    method signatures is a problem for both abstract
    and interface)
  • — Use interfaces when some part of the design
    will change frequently.
  • — Interface for plug-in architectures – like
    the strategy pattern.
  • — Use abstract class to provide basic services
    for derived classes (event, message handling)
  • — In favor of abstract class:
    • — interfaces may be more difficult to read in
      code logic.
    • — interfaces are somewhat slower due to

Notes on Java Collections..

Mar 23, 2009 in Java, JavaUsage, Uncategorized

Collections characteristics:

  • synchronized (hashtable-yes, hashmap-no, vector-yes, arraylist-no)
  • directionality (iterators)
  • allow null values (hashtable-no, hashmap-yes)
  • preserve insert order
  • duplicates (set-no, list-yes)


  • Collections interfaces: Collection, Set, List and Map.
  • To synchronize HashMap:

    Map m = Collections.synchronizeMap(hashMap);

  • Some implementations: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
  • An ArrayList is resizable, where as, an array is not.
  • Hashmap overrides?

    The methods to override are equals() and hashCode().

  • Difference between Enumeration and Iterator?

    Enumeration is read-only. Iterator provides remove and add methods
    and it is fail-fast in multi-threaded configurations.

Java profiler, notes on tracking memory leaks..

Sep 10, 2008 in Eclipse, Java, JavaUsage

Free profiler for Eclipse .. this is no longer active.. use TPTP instead..

Notes on hunting memory leaks..

Simple popup display widget ..

Aug 11, 2008 in Java, JavaUsage

import javax.swing.JOptionPane;
import javax.swing.JFrame;

public class JPopup extends JFrame {

    public JPopup(String msg) {
        JOptionPane.showMessageDialog(this, msg);

    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("usage: JPopup message");
        new JPopup(args[0]);


Java memory leak example..

Jul 11, 2003 in Java, JavaUsage

From “Java 2 Certification Study Guide” ..

Incorrect construct, produces a memory leak, otherwise known as memory “loitering”:

public Object pop() {
  return storage[index--];

The correct way:

public Object pop() {
  Object rv = storage[index];
  storage[index--] = null;
  return rv;