email:
website: http://www.siongboon.com
| 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
|
Java Regular
Expressions
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 |
|
|
|
This is an example of a typical Java coding structure and some Java naming convention for package, class, method, and variable. |
|
Java access modifier: public- Variables/methods using public modifier can be access easily by all objects. protected- Protected members can be accessed by another package through inheritence. Class CC managed to access protected member C through inheritence. Class CC inherited Class AA, therefore member C becomes part of Class CC. default- If there is no modifier specified, Java will treat it as the default modifier. Default members B gets a bit more difficult to access. Only classes within the same package can access to it. Member B using the default modifier can be access by Class BB. Class BB can creates an instance of Class AA or through static variable access to access to member B. private- is the most restrictive modifier. The private member A can only be access within the class AA itselfs. Class AA being the creator, is able to access all it's members A, B, C and D. It is recommended to start the data/method encapsulation using private modifier. Change the modifier when neccessary. There must be a good reason why private modifier is not use.
|
Future research the meaning on these defination: public interface ClassName What do these defination really means? |
|
| Byte Manipulation | |
|
|
|
//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 charchar c3 = (char)87;char c1 = '\u0057'; |
|
|
|
|
int hex = Integer.parseInt(HexString, 16); String str = Integer.toBinaryString(79); |
//parse hex string. HexString="FFFF", result-> hex=65535 //convert number 79 to a hex string "4f" //convert number 79 to a binary string "01111001" |
//defining
byte constant array |
|
//Bitwise
Operator<<
//left shift preserving the sign bit |
|
| Integer String
Manipulation |
|
int num = Integer.parseInt(String); |
//Example:
Convert from string to numerical value//parse hex string. HexString="FFFF", result-> hex=65535//convert number 79 to a string "79"//convert number 79 to a binary string "01111001" |
String str = "abc]123]XYZ"; |
|
//compare & match string |
|
|
|
Leading or padded zero |
String strDecimalFormat formatV = new DecimalFormat("#.##"); |
special numerical formatting |
DecimalFormat formatV = new DecimalFormat("###0.00"); //floating value to 2 decimal place |
Right align a 2 decimal place floating number |
| String subStr = Integer.toBinaryString(str.charAt(x)); res = res + inBetween + String.format("%8s", subStr).replace(' ', '0'); |
//convert char/int to 8 bit binary |
//to
check/compare the data/object type of a unknown java object |
|
|
|
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on. |
|
|
| Java structure to get the single instance of an object (singleton) | |
| AutoScheduleManager myAsm = AutoScheduleManager.getInstance(); public class AutoScheduleManager implements AxisObserver { protected static transient final Log logger = LogFactory.getLog(PcAdminService.class); AutoSchedule autoSche; PcAdminService pcA; private static AutoScheduleManager ass = null; public static AutoScheduleManager getInstance(PcAdminService pcA) { //object can only create once. constructor method is private if(ass == null) ass = new AutoScheduleManager(pcA); return(ass); } private AutoScheduleManager(PcAdminService pcA) { this.pcA = pcA; startScheduledShutdown(); //enable scheduled shutdown service when the service started. } } |
This singleton structure will ensure that the class object can only be created once. Constructor has to be defined as private while the class variable & getInstance method is static so that they can be access with the object being created. This is the first question that I ask myself when designing a new class object even since I learned about it; whether it can be created with multiple instance or only a single static instance of the object. In some application, especially when working with hardware devices, single instance is the only proper way to built your class. It can helps you to prevent mis-written codes, resulting in less bugs/crush program when the class is used by another programmer. |
| Time, Date,
Calendar,
Timer |
|
//Delay/sleep functiontry{Thread.sleep(1000);}catch(InterruptedException e){} |
|
//System time counting in millisecond. Measuring the
cpu time to execute certain tasklong sysMiliSecCount = System.currentTimeMillis( ); |
|
//Calendar, Date, Time (data & formatting function) |
|
|
//set periodic timer, Class need to implement Runnable Timer RFIDscanTimer = new Timer("RFID Sort"); RFIDtagSort rfidTagSorting = new RFIDtagSort(); logger.info("Scan Period : " + RFIDscanPeriod); RFIDscanTimer.schedule(rfidTagSorting, 100, RFIDscanPeriod); private class RFIDtagSort extends TimerTask { public RFIDtagSort() { } @Override public final void run() { //Run function will be executed every RFIDscanPeriod interval logger.info("timer routine."); } } |
Use the TimerTask for scheduling a periodic routine to execute . |
//timeout implementation |
| Array, Data Container | |
//Arraylist container example |
|
HashMap<Integer, Computer> map;//Iterator<Integer> i=map.keySet().iterator();Iterator<Computer> i=map.values().iterator(); |
|
//Example:
Ensure that the Array data container object is synchronized mySyncList = Collections.synchronizedList(arrayList);//Another synchronized example for Map containerTreeMap<object1,object2> myMap = new
TreeMap<object1,object2>();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. |
| Java debugging,
exception and error handling resources |
|
|
log4j Similar to System.out.println(); Save to project folder /lib /lib (factory logger).zip Save to project folder /resource /resource (factory logger).zip (Details of log file setup can be found in the file "log4j.properties". Includes a 2nd example to config Log4j for logging in Tomcat.) Log4j references: |
|
|
How to add *.jar library?Encountered the following errors?log4j:WARN No appenders could be found for logger (javax.swing.JApplet). |
|
|
public KnxSession() throws KnxCommException |
|
public class MyOwnException extends Exception |
A simple exception class, that accept customised error messages. |
//KnxCommExeception Classpackage knxEib.knxException; |
A complex exception class that has more functions. |
| File I/O,
Properties/Configuration file |
|
|
Example: File Write
String filename = getClass().getName()+".txt"; |
|
BufferedReader in = null; |
|
//monitoring new files added or removed from the file directory |
This class monitor new files added or removed from the directory. The class extends TimerTask which execute the run process every seconds. |
| Detect file modification.pdf |
|
Non-blocking mode is easy to write. I found it difficult when I learn that doing non-blocking input reading is so difficult using Java. I finally got the code to do the non-blocking reading of the input. Most Java examples that I saw were using blocking mode for their inputs. I think blocking mode would be better for long term maintenence. You might need to write extra thread just to handle those inputs under blocking mode; it may be more organised. |
//convert String into InputStream
|
|
//reading input from a keyboard |
Reading from a keyboard is similar to reading from a data stream. Infact data reading is always in the form of stream. |
|
Project example: reading_int_datastream.zipExample of the data in the binary.dat file:0x00 0x00 0x00 0x2A 0x00 0x00 0x00 0x2DActual int content represented in the binary file above:42 45
|
Other very good reference:- http://www3.ntu.edu.sg/home/ehchua/programming/java/J5b_IO.html (very good NTU website on data stream by Chua Hock Chuan), |
//Example
of reading configuration from a property fileprivate void loadNetworkConfig() |
Note: There is another better generic methods to read *.properties. Read more about "Apache Common configuration". Commons Configuration provides a generic configuration interface which enables a Java application to read configuration data from a variety of sources. Commons Configuration provides typed access to single, and multi-valued configuration parameters. |
//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 classpathInputStream 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 packageInputStream is = getClass.getResourceAsStream("file.txt"); |
|
//inside the file config.propertiesIP=192.168.1.1 |
|
| Get System or Environment variables | |||||||||||||||||||||||||||||||||||||||||||||
String system_variable = System.getProperty("user.name"); |
The string user.name is the string key required to retrieve the system variables string. The following list present the other possible system variable that you can retrieve from
|
||||||||||||||||||||||||||||||||||||||||||||
//Java code to get computer name, example "LSB-PC"
|
| Threading processes |
|
|
The coding examples on the
left are the various style of
using the Java threading
features.
http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html |
//Spinning off a new Thread process without writing
inside a proper class file } |
|
|
|
| Thread rf_reader = new Thread(rfid_reader); rf_reader.setDaemon(true); rf_reader.setName("SmartIDReader task"); //Provide the thread with a threadName rf_reader.start(); |
this.setDaemon(true); explains: setting daemon to true, will ensure that this thread is spin off from the main's method thread. When a program execute from main entry point, main itself is actually a thread. If daemon is set to true, the sub-thread spinoff will be under the main thread. When the main thread is terminated, all sub thread will be terminated, shutdownhook can also be activated. If daemon is set to false, the thread spin off as another separated thread by its own. When the main thread is terminated, the sub thread will still exists (with daemon set to false). |
| Java Destructor Method - ShutdownHook | |
//This example continue from the previous
myThreadClass example.//If the java program terminate
abnormally, shutdownhook will be activated.private ThreadClassShutdownHook tcShutdownHook = null; //add this to the thread class variabletcShutdownHook = new ThreadClassShutdownHook(tc);
//add this to
the thread class constructor |
Similar to C++, the implementation of a ShutdownHook can be like writing a destructor for Java. It can help to ensure that for any abnormal program termination, you can get to clean up and close all the resources in used. |
|
|
| Import/Loading *.DLL to Java code (Dynamic Link Library) | |
|
public class monitorController { //A native function in monitorController.dll private native void triggerMonitor(int mode); // ---------------- Load Library ----------------- // To load dll file static { try { //get current directory String getPath = System.getProperty("user.dir") + File.separator + "LIB" + File.separator; System.load(getPath + "monitorController.dll"); logger.info("monitorContoller.dll loaded.."); } catch(Exception ex) { logger.info("Exception while loading monitorController.dll: "+ex); } } // ---------------- onMonitor () ----------------- // On Monitor public void onMonitor() { triggerMonitor(1); } // ---------------- offMonitor () ----------------- // Off Monitor public void offMonitor() { triggerMonitor(0); } } |
The example shows the loading of *.dll library into a Java code. The example also shows the static initializer block, which is used to load the dll library. |
| Launching the default application by opening a file from Java | |
|
| |
| Executing a *.exe program from the command prompt (command-line interpreter) | |
| //Other examples //executing the fing program from the command prompt String cmd = "fing -n 192.168.234.0/24 -r 1 --session scanLog.txt -o table,csv,"+scanResultFileName; logger.info("Fing is now scanning the network."); try { Process p2 = Runtime.getRuntime().exec(cmd); InputStream is = p2.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader in = new BufferedReader(isr); String str = ""; for(int x=0;str != null;x++) { str = in.readLine(); if(str==null) //typically last line is a null. Do not add null string to the list continue; else if(str.contains("Error")) logger.error("from Fing.exe: " + str); //logger.debug("Line: " + x + " \tStr: " + str); } } catch(Exception e) { logger.error("Check if Fing software is installed."); logger.error("Command line \""+ cmd +"\" read error.", e); //halt 10 sec for user to read the error message. try{Thread.sleep(5000);}catch(InterruptedException e1){} System.exit(1); //terminate the program } logger.info("Fing scanning is completed."); |
| Network TCP/IP communication example | |
//how to get proper socket |
Reference:http://docstore.mik.ua/orelly/java-ent/dist/ch02_01.htm
|
InetAddress i = InetAddress.getLocalHost(); //get IP address of the local machine |
|
//Retreive all the network interface available in the system (Ethernet, WiFi, 2nd Ethernet port, etc...) |
|
|
|
//handling incoming client connection |
| Network UDP communication example (datagram packet listening) | |
//UDP example, from EIB/KNX communication program |
|
byte[] data = LantronixDevice.queryFirmwareVer; try |
UDP is a connectionless communication protocol and does not handle the integrity of the data being send. This does not mean that it cannot be implemented for communication that requires 100% error free communication. It simply means that the lower level protocol will not help you ensure that all your data bytes are being send over, and that your application will need to handle those error checking if you need it. There are various way to setup your UDP communicates. Two methods are breifly state for your awareness. - socket define wihtin DatagramSocket - socket define within DatagramPacket. For UDP communication to and only to one IP addressed device, you should define your socket in the object DatagramSocket. For packet communication with multiple UDP devices or acting as a listener, you can define your socket within the DatagramPacket object; there will be no restriction to which devices you can communicate within the network. UDP protocol is very flexible to implement. |
Accessing
mySQL using Java: When writing programs, there will be time we need to store data permanently.
Usually writing data to files would be sufficient. When the data is
becoming more and more complex, storing them in database might starts to make
sense. SQL provides a standardize data access interface without having
your program to manage the complexity of searching and storing the data.For this example, I am using the free database mySQL.1) download and install the following software |
|
SQL connection pool:------------------------------------------------4) download the following jar libraries |
Command Pattern: ExecutorServiceexample: ExecutorService_Queue.java, ExecutorService_QueueJob.java Command Pattern: Observerexample1: Observer command pattern.pdfexample2: Observer pattern - Wikipedia, the free encyclopedia.pdfexample3: JavaWorld - October - How-to Java_ Observer and Observable.pdf
|
As you write more and more programs, you will realise the efficiency of re-using the codes. We call them functions. When we write more and more functions, we will realised that more codes can be consolidated; many codes are repeated. Then came the object oriented programming concept. Even when we apply object orientated programming, we can still see similar codes pattern or structure reoccurring. This calls for command pattern. It is a well design coding structures that helps programmer to simplfy commonly use, complex algorithm. When programming complex structure, think about the existing command patterns solutions. Knowing how to apply them can save you days of proramming headache. Many frequently used and efficient algorithms were already being thought of and were simplfied for us for implementation. Study the command patterns, simplfies to keep your coding short and neat. This is the true art of programming. |
read log4j ndc (log the individual instance of client thread connected to the server) |
Design pattern reference: |
My Java Library
|
|
This utilities.zip contains my frequent/common used Java library, which contains the follow object- HexUtilities.java- ShutdownHook.java, ShutdownHookClass.java - UtilitiesThread.java |
|
//example for using the ShutdownHook class |
|
| KNX EIB communication for home automation server | KNX source code |
| TjLink TCP/IP communication for network Audio Video AV equipment (AV receiver, Projector) | TjLink source code example. |
| HID RFID door access security program | HID RFID source code |
| Server service to control all computers to wakeup or sleep | Wake&Sleep |
| SMS webservice server | SMS server |
| UDP communication with Xport, MatchPort | Java UDP client for XPort |
--------------------------
| 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 |
|
| int keyChar = evt.getKeyChar(); |
Create a message dialog box that helps to debug data in hex code. |
example to load image file to JPanel. |
| Java Applet | |
Inserting applet into html file, where MyApplet.class is the java class to invoke, basecode "./" is the root directory the MyApplet.class is located. Without the *.class will also works If your MyApplet.class is located in the directory /appDir If the *.class to invoke is located inside a *.jar library archive file |
|
How to signed a Java Applet for access to communication outside the server the applet reside on?
|
|
Applet - Do not put the main Applet class in a package Problem: Problem: |
Browser test for Java Applet, Note for Java applet, Note for Java Jar file, |
These formatted java source codes are generated by java2html_50.zip