Java Coding Example



Java Primitive Data Types
Type Contains Default Size Range
boolean true or false false 1 bit n.a.
char Unicode character unsigned \u0000 2 bytes (16 bits) \u0000 to \uFFFF or 0 to 216-1
byte Signed integer 0 1 byte (8 bits) -128 to 127 or (-27 to 27-1)
short Signed integer 0 2 bytes (16 bits) -32768 to 32767 or (-215 to 215-1)
int Signed integer 0 4 bytes (32 bits) -2147483648 to 2147483647 or (-231 to 231-1)
long Signed integer 0 8 bytes (64 bits) -9223372036854775808 to 9223372036854775807 or (-263 to 263-1)
float IEEE 754 floating point single-precision 0.0f 4 bytes (32 bits) 1.4E-45 to 3.4028235E+38
double IEEE 754 floating point double-precision 0.0 8 bytes (64 bits) 439E-324 to 1.7976931348623157E+308


Java Language References


Escape code for Java Regular Expression

http://www.wellho.net/regex/javare.html


Character Escape Codes Description
\n new line (0x0A)
\t tab (0x09)
\b backspace (0x08)
\r carriage return (0x0D)
\f form feed (0x0C)
\\ backslash
\' single quotation mark
\" double quotation mark
\?? octal
\x?? hexadecimal
\u?? unicode character

Java Regular Expressions   java.util.regex

My first encounter with regex happens when I was using String.split() function. The split char is represented by special char used by regex. I thought the function is easy to use but is spending a lot of time figuring why the string cannot be split. I was splitting the IP address which is separated by the '.' dot or period. My colleague drop me some notes from the website, and now I finally know what really happen. Great article I must say.

Class typically use for wild card search in String.

The following are some char keyword in used by the regular expressions class. In order to use the char, use \ followed by the char or insert the printable string between \Q and \E

metacharacters->   ([{\^-$|]})?*+.

There are more about regex than I thought after searching the web.

http://en.wikipedia.org/wiki/Regular_expression



String tx = "Delta values are labeled \"\u0394\" on the chart.";



Java Fundamental References

//Basic java class structure
public class ClassName
{
  public ClassName()
  {  //class constructor
  }

  public method1()
  {  //class constructor
  }

  public static void main(String args[])
  {  //entry point for running this program
  }
}


//Java do not have unsigned data type
//Representation of the unsigned for a signed data type.
byte temp;
int result;
result=(int)(temp[0]&0xFF);  
//extract the unsigned value


//f indicates that 1.5 is of data type float rather than a double.
//(any literal is intepreted as a double and not a float)
float x = 1.5f ;  
double x = 1.5;


//Casting a numeric value to a char
char c3 = (char)87;
char c1 = '\u0057';


//declare & allocate memory for byte array
byte remoteIP[] new byte[4];


//defining byte constant array
private static final byte[] MYCONSTANT = {0x040x04(byte)0xFF0x64};


//Bitwise Operator
>>>   //right shift without preserving the sign bit
>>    //right shift preserving the sign bit
<<    //left shift preserving the sign bit


//to check/compare the data/object type of a unknown java object
boolean x = aAnimal instanceof Fish





Time, Date, Calendar, Timer

//Delay/sleep function
try{Thread.sleep(1000);}catch(InterruptedException e){}


//System time counting in millisecond. Measuring the cpu time to execute certain task
long sysMiliSecCount = System.currentTimeMillis( );
//do the task
long taskTime = System.currentTimeMillis( ) - sysMiliSecCount;


//Calendar, Date, Time (data & formatting function)
Calendar cal;
cal = Calendar.getInstance();
int hourday = cal.get(Calendar.HOUR_OF_DAY);  //24 hour format
int hour = cal.get(Calendar.HOUR);            //12 hour format
int am_pm = cal.get(Calendar.AM_PM);          //
int minute = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
int msec = cal.get(Calendar.MILLISECOND);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd (EEE)");
SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm:ss aaa");
String data = sdf.format(cal.getTime());
String time = sdf2.format(cal.getTime());






Array, Data Container
//Arraylist container example
ArrayList<String> a;
a.add(new String("Hello"));
Iterator<String> itr = a.iterator();
while(itr.hasNext())
{
    System.out.println(itr.next());
}


HashMap<Integer, Computer> map;
map.put(45,comp);
//Iterator using the HashMap's key
//Iterator<Integer> i=map.keySet().iterator();
//Iterator using the HashMap's value
Iterator<Computer> i=map.values().iterator();
while(i.hasNext())
{
    Computer c = (Computer)i.next();
    c.setSubnet(netInfo.getSubnetMaskAddr());
}


//Example: Ensure that the Array data container object is synchronized
ArrayList<objectName> myArrayList = new ArrayList();
List<objectName> mySyncList;
//Get the list that is synchronized from ArrayList
mySyncList = Collections.synchronizedList(arrayList);

//Another synchronized example for Map container
TreeMap<object1,object2> myMap = new TreeMap<object1,object2>();
Map<object1,object2> mySyncMap;
//Get the list that is synchronized from ArrayList
mySyncMap = Collections.synchronizedMap(myMap);
//Java ArrayList is NOT synchronized, meaning it is possible that any two process can access the un-sychronized data at the same time, causing runtime error. Two process may try to write data to the same memory location.

//Access the ArrayList through mySyncList object to ensure that there are no two or more simultaneously process accessing to the same ArrayList object. This is also applicable to other container objects. The mySyncList List object can be cast back to ArrayList, since it is originate from ArrayList.





Integer String Manipulation

int num = Integer.parseInt(String);
int hex = Integer.parseInt(HexString, 16);
Integer.toBinaryString(a);

//Example: Convert from string to numerical value
//parse hex string
//convert a number to a binary string
String.split();





Java debugging, exception and error handling resources

log4j

Example: FactoryLog for logging info, error, debug, etc messages. Similar to System.out.println();

 

Save to project folder /lib

/lib (factory logger).zip

Save to project folder /resource

/resource (factory logger).zip (includes examples to config Log4j for logging multiple classes into individual log file.)


Log4j references:
http://logging.apache.org/log4j/1.2/manual.html
http://juliusdavies.ca/logging.html
http://www.laliluna.de/articles/log4j-tutorial.html



//Using LogFactory for debugging & logging example.
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

protected static transient final Log logger = LogFactory.getLog(YourClassName.class);

logger.error("");
logger.debug("");
logger.info("Class name:<"+this.getClass().getName()+">");
  //print out the class name


//Two examples to print out error messages:
e.printStackTrace();
System.out.println("Got an IOException: " + e.getMessage());



public KnxSession() throws KnxCommException
{
        try
        {
            int port = getLocalSessionPort();
            udp = new DatagramSocket(port);
            logger.info("\t\topened UDP port: " + port + "   (for session)");
        }
        catch(SocketException e)
        {
            logger.error("error while calling setupUdpService()",e);
            throw new KnxCommException("error message");
        }
}


//KnxCommExeception Class
package knxEib.knxException;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class KnxCommException extends Exception
{
    protected static transient final Log logger = LogFactory.getLog(Thread.class.getClass().getName());

    static private int errorCounter = 0;

    public KnxCommException(String msg)
    {
        super(msg);
        errorCounter++;
        printErrorCount();
    }

    public KnxCommException(String msg, Throwable t)
    {
        super(msg, t);
        errorCounter++;
        printErrorCount();
    }

    private int printErrorCount()
    {
        logger.error("exception history count : " + errorCounter);
        try
        {
            String filename = "resource\\" + getClass().getName() ".txt";
            BufferedWriter out = new BufferedWriter(new FileWriter(filename));
            out.write(filename + "\r\n");
            out.write("Error Count = " + errorCounter + "\r\n");
            out.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return(errorCounter);
    }
}





File I/O, Properties/Configuration file

Example: File Write

 

String filename = getClass().getName()+".txt";
try
{
    BufferedWriter out = new BufferedWriter(new FileWriter(filename));
    out.write(previousSessionID);
    out.write("\r\n");
    out.write("Session ID = " + previousSessionID + "\r\n");
    out.close();
}
catch(IOException e)
{
    e.printStackTrace();
}


BufferedReader input = null;
String fileName = "resource\\output_mac2ip.txt";

try
{
    FileReader file = new FileReader(fileName)// Open the file.
    input = new BufferedReader(file)// Tie 'input' to this file.
}
catch(FileNotFoundException x)
// The file may not exist.
    logger.error("File not found: " + fileName);
    System.exit(2);
}

String linetext;
while( (linetext = input.readLine()) != null )
{
}




//Example of reading configuration from a property file
private void loadNetworkConfig()
{
    String filename = "/config.properties";
    InputStream is =
getClass.getClassLoader().getResourceAsStream(filename);
    Properties myProperty = new Properties();

    try
    {
        myProperty.load(is);
        is.close();
    }
    catch (IOException ioe)
    {   //ensure that the file is in the classpath");
        logger.error("Error reading the properties file.");       
        System.exit(1);
    }

    String str;
    Int x;
    str = myProperty.getProperty("IP"null);
    x = myProperty.getProperty("PORT"null);
}



//Various method of loading file/resources
//The java code should obtain the resource using getClassloader() as the standard
//loading file that is located in the directory as specified in the classpath
InputStream is = getClass.getClassLoader().getResourceAsStream("file.txt");

//same as above (another way of writing the code)
InputStream is = getClass.getResourceAsStream("/file.txt");

//loading file that is located in the same directory as the *class file
//looking for file in the current class package
InputStream is = getClass.getResourceAsStream("file.txt");


//inside the file config.properties
IP=192.168.1.1
PORT=1234



Detect file modification.pdf


Threading processes

//Threading example
 public class myThreadClass extends Thread
{
 
//flag to stop the thread process
  private boolean fIsStopRequested=false;
  //flag to control process flow to be in syn with other critical function
  private static boolean fIsSynProcess=false;
 
//object holding the reference to this thread
  private Thread thisThread = null;

 
public myThreadClass()
  {
  }


  public void run()
  {  
//getting the thread process ID
    Thread thisThread = Thread.currentThread();
    String threadName = getClass().getName() " routine, thread started: " + thisThread.getName();
    while(true)
    {
     
//stop to stop thread
      if(isStopRequested())
        break;
      //other process in progress, hold thread for a moment
      while(isSynProcess())
      {
        try{Thread.sleep(300);}catch(InterruptedException e){e.printStackTrace();}
      }
     
//Place the looping thread process code here.
    }
  }

  private synchronized boolean isStopRequested()
  {
    if(thisThread==null)
      return(true);
    return(false);
  }
  
  public void requestStop()
  {
    Thread tempThread = thisThread;
    thisThread = null;
    //interrupt for used to exit from blocking function in the run() method's while loop
    if (tempThread != null)
      tempThread.interrupt();
  }

  private synchronized boolean isSynProcess()
  {
    return(fIsSynProcess);
  }

  private synchronized void holdThreadRun()    //prevent the run thread to terminate
  {
    fIsSynProcess=true;
  }

  private synchronized void releaseThreadRun()    //allow the run thread to terminate
  {
    fIsSynProcess=false;
  }
}

 
//Spinning off a new Thread process without writing inside a proper class file
Thread rescan = new Thread(new Runnable()
{
    public void run()
    {
        //ToDo: Place your code that
        //you need to run as another simultaneous process.

    }
});


//Another method of writing thread
Object obj = new Object();
new Thread(obj).start();
Object class must contain a method run();




Java Destructor Method - ShutdownHook
//This example continue from the previous myThreadClass example.
//ShutdownHook is registered for the myThreadClass thread process.
//If the java program terminate abnormally, shutdownhook will be activated.
//Shutdownhook will activate the ThreadClassShutdownHook which will start a thread
//to stop myThreadClass's thread tc.requestStop().
 private ThreadClassShutdownHook tcShutdownHook = null; //add this to the thread class variable
tcShutdownHook = new ThreadClassShutdownHook(tc);      //add this to the thread class constructor

public class ThreadClassShutdownHook extends Thread
{
  protected static transient final Log logger = LogFactory.getLog(Thread.class.getClass().getName());

  private
myThreadClass tc;
  
  public 
ThreadClassShutdownHook(myThreadClass tc)
  {
    this.tc = tc;
    logger.info(this.getClass().getName() " created. ShutdownHook registered.");
    Runtime.getRuntime().addShutdownHook(this);
  }
  
  public void remove()
  {
    Runtime.getRuntime().removeShutdownHook(this);
  }
  
  public void run()
  {
    logger.info("ShutdownHook activated for " this.getClass().getName()
      + ". Thread: " + Thread.currentThread().getName());
    tc.requestStop();
  }
}



GUI & Event Listener example
- Create window
- Window listener
- Mouse listener
- Keyboard listener


- example interface, inherirt, abstract (pc, network projector project)

- http://www.javamex.com/tutorials/threads/invokelater.shtml
any swing component codes that requires periodically refresh need to apply this invoke function.
http://www3.ntu.edu.sg/home/ehchua/programming/java/J5e_multithreading.html