Java




Java Tutorial / Reference

This is an on-going tutorial for people starting out to program in Java, my goal is not to teach a complete and detailed explanation of Java but rather give related example that I believe can be digested by a person just starting to program in Java. There is a lot of hype and terms when you first starting out Java, enough hype that beginner's just quit before they even started. These points are very brief, the important thing is not to memorized every method, class, but rather where to go for reference. Java is an evolving language, every new release added / delete (deprecated) improvements. Most of these topics are the one's that have baffled me when I first encounter Java.

Parameters / Argument passing to the methods

All paramaters/arguments in Java are passed by value! I had a hard time accepting this in the beginning coming from several programming languages but the sooner you accept these the easier it will get (the more you resist these concept the harder it will get). Don't bother comparring C/C++ pointers to Java's object reference, Java don't have pointers.

Interfaces / Abstracts Concepts
Interface are like contract, pretend you have a blueprint of a house that has 4 bedrooms, 2 baths, garage, frontyard and backyard. The interface part is the blueprint, you will give this to the builder and tell the builder, you must build the house with 4 bedrooms, 2 baths, garage, frontyard and backyard but not tell the builder how to build it. The contract part is that the builder must build the house with 4 bedrooms, 2 baths, garage, frontyard and backyard.

Abstract on the other hand is also like a blueprint of a house that has 4 bedrooms, 2 baths, garage, frontyard and backyard. The abstract part is that you give the builder the blueprint but tell the builder, by the way, I already built the 2 baths and the garage, all you need is to build the 4 bedrooms, frontyard and backyard.

So interface, no implementation of methods, abstract, some implementation of methods. If all your abstract methods has no implementation, then might as well turn this abstract to interface, because that's what interface is pure abstract.

Use interface if you want to force a type like class making sure that the class implementing the interface will implement each and every method defined in the interface. Use abstract if part of your methods are already implemented (although the calling class can override these methods). Note that Java do not have multiple inheritance like C++ but you can implement multiple interfaces, so this is another way to use interface effectively. Interfaces can have variables (member) but they must be public static final. Interfaces, unlike classes can extend more than one iterface. For example: interface Son extends MoM, Dad. Son interface extends both Mom and Dad which means that all methods and constants defined by Mom and Dad are part of the Son contract, and also any method and constant inside the Son interface. Summary: An abstract class can have a partial implementation, protected parts, static methods, whereas interfaces are limited to public constants and methods with no implementation.

Polymorphism / Upcasting I've written an example of trying to show the polymorphism behavior, upcasting example. We have 3 students, named Joe, Tony, and Jeremy, they all went inside the class room, when the instructor did a roll call every student reply with their name. I've created an interface called Person that will enforce a method name getName() whoever implements(behavior) Person. Class Student implements Person so it must implement (behaviour) getName(). I've created an empty class room (Vector) that holds any kind of Objects (Student, Person, etc.) I created three new students named Joe, Tony, Jeremy, and put them inside the class room. When we do the roll call, I call each Person (cast to Student) and each one respond by their own name. Where is polymorphism in these examples.
The line: Person person = (Student)classRoom.elementAt(i); is where the polymorphism happens, when I add each student, I'm adding a student object, however, when I'm calling each student, I'm using Person not Student, but somehow with casting Student to a Person, the person object knows everybody's name. Clear as a mud ? Again, when I add the Student in the class room, they are Student type, but when I call each one, I use a Person object cast to Student. Which brings to the next point, person is cast to Student which is ok because a Student is a Person.
The line: class Student implements Person suggests that any Student is a Person which is true. Upcasting means going up to the hierarchy class, which is ok in this case because any Student is a Person. A Vector is a dynamic (shrinking/expanding) array like as opposed to fix size. A Vector holds only object and not primitive types, once you put an object into the vector it just become any other object, to retrieve, you have to cast it to a known object to make it usable, this is why Person is cast to Student before we can manipulate the Person object, otherwise we don't know what object type is inside the Vector. The file name 'RollCall.java' is here.

Collections Collections (Vector, ArrayList ...) holds reference to objects not the actual objects themselves. Below example proves this. I created an object with initial value, put it inside the vector, then get what's inside the vector and shows the value on the screen. Next, I modify the object outside the vector, then get what's inside the vector and show the value on the screen. This time, the value change eventhough I modify the value outside the vector, and did not put back inside the vector the modified object. This shows that the vector is holding the reference to the object and not the object itself.


     Vector v = new Vector();
     StringBuffer sb = new StringBuffer("John ");    // create a string
     v.add(sb);                                      // add sb in vector
     StringBuffer sbVector = (StringBuffer)v.get(0); // get the string inside the vector
     System.out.println("Before modifying, value is " + sbVector);
     sb.append(" Doe");                              // modify sb outside of the vector
     sbVector = (StringBuffer)v.get(0);              // get the sb inside the vector again
     System.out.println("After modifying, value is " + sbVector);


     Output is:
     Before modifying, value is John
     After modifying, value is John Doe

Accessing variables from current, super, super/super class

How to access same name variables current, super, super/super class
Assumes s is instance of class Son that extends Father.
Assumes Father extends GrandFather.  All classes contains a variable String str.

Son s = new Son();
s.str                // this refers to son's str variable
((Father)s).str      // this refers to father's str variable
((GrandFather)s).str // this refers to grandfather's str variable

What are Wrappers and why have them ? To be continued...

Static To be continued...

Overloading / Overriding Why return types are not part of overloaded signatures ? To be continued...

Servlets To be continued...

JDBC To be continued...

Call backs To be continued...




Live Weather


The live weather information consists of a wind direction, temperature sensor, and windspeed indicator. Specification for the weather gadget is at www.ibutton.com. Currently, it is up at my chimney. The weather instrument is hooked-up to a Windows 98 machine running a Java server using UDP protocol. The source for the Java server is here. On the client side, I'm using a Linux Servlet/JSP engine (Tomcat 4.0.3) server, when you click on the link, it access a servlets that connect to the server in the Windows 98, it then reads two lines, first one is the temperature and the second one is the windspeed. I forgot to calibrate the wind direction indicator before the weather instrument went up to the roof. I need a volunteer to climb on the roof and calibrate the wind speed direction sensors. It won't take very long to calibrate, about 3 - 4 minutes. The source for the servlet is here. Click here for the picture of the weather instrument.


Java Stand alone program


I wrote several stand-alone programs, while I was in the Coast Guard. I was working with large contract for ship repair, when we switched to a newer accounting system. This new system creates additional work, and it's clear that some type of computer program needs to be implemented. After researching existing software (Access, Excel,) I decided to write a Java program using AWT GUI. The program keeps track of the accounting information, generates needed reports, prints form by executing DOS program on the Windows NT server, keeps historical data about each contract, added efficient and convenient details such as vendors info and Contracting Officer info. This same program is re-written with improvements using Swing GUI. The program uses Java's Random Access File and the data is stored to a shared file server, It has a logging feature that captures user's name data and time and activity on each file. I also included a user manual and a reference manual for this program.


Final project for Java course (house alarm)


This is my final project for my Java course at a local community college. Basically, it's a house alarm, and the code runs on a PC. I made a model of the first floor of my house and put magnetic sensor's on all doors including the garage. This picture shows the top view of the model with the original house floor plan. Another picture shows the garage door open. This picture shows side view of the model. The magnetic sensors are connected to this pc board. The pc board contains pull-up resistor and a buzzer. The pc board is connected to the PC by an AVR or 8051 microcontroller board that communicates thru the RS-232 (serial port). Check my homepage for the AVR or 8051 microcontroller. The code in Java to communicate with the microcontroller is here. To present this project in class, I borrowed my friends laptop computer for a live demo.


TINI


This is part of my on-going home automation project. I'm running the TiniHttpServer 0.17 web server on the TINI platform from www.smartsc.com. The serial port 1 of the TINI is connected to an RS-485 network. One of the nodes of the RS-485 network is hooked-up to an AVR (ATMEL) microcontroller about 130 feet from the TINI. The file to get data from the RS-485 network is here. The file to send data to the RS-485 network is here. Using Servlets, the html form is presented to the user and the user can click any 110 volts appliances including the lawn sprinkler to turn on or off using X-10. The singleton object serial port code is here the singleton pattern ensures that no matter how many servlets is started, there will only be one serial port object on the TINI that will be created and it's true there is only one serial port 1 physically on the TINI. The last file is where I grouped all the constant together, Java purist will disagree by my use of interface to represent all my constant, but here is the code.




SitePlayer



SitePlayer?, the World?s smallest Ethernet web server. The first product in a family of embedded web servers designed to enable any microprocessor-based device to become web enabled easily and inexpensively. In approximately one square inch, SitePlayer includes a web server, 10baseT Ethernet controller, flash web page memory, graphical object processor, and a serial device interface. SitePlayer is a plug in module and can also be used as a web enabled option, product upgrade, or to retrofit older products. Example applications include audio equipment, appliances, thermostats, home automation, industrial control, process control, test equipment, medical equipment, automobiles, machine control, remote monitoring, and cellular phones.

The SitePlayer is a 1 x 1.5 inch device which has Ethernet capability, serial, I/O for only $29.95 (not including RJ-45) jacks. You can find more info at www.siteplayer.com. The Java code to toggle the SitePlayer I/O using TCP socket is here, and the Java code to toggle the SitePlayer I/O using UDP is here.. Make sure that if you use the UDP that the UDP receive enable is activate in the SitePlayer. Forum for the siteplayer is at http://groups.yahoo.com/group/siteplayer. Currently the SitePlayer is connected to the network through Ethernet, if any changes in my simulated door/window sensors, a microcontroller instruct the SitePlayer to send a UDP packet to the Linux server sending the data. The Linux server has a UDP server that waits for packet, and if it receives packet it then dumps the data to a MySQL database. This code also shows how to connect to a database using Java's JDBC and assumption that you have MySQL database already running. The code for the Linux server is here. The code for the microcontroller is here.



Servlets, JDBC, Web Developments


Here's a servlet that let you take a practice test on line, the test itself is a HTML form and the servlet grades the test. The HTML form is here, and the servlet code is here. Each test can handle multiple choice, fill in the blanks, or true/false questions.


Palm Pilot


I've been using the SuperWaba to develop program for the Palm Pilot. Check the website at www.superwaba.org, SuperWaba is similar to java and you can make pretty sophisticated program for the Palm Pilot/Handsping Visor devices. My personal notes on writing program for Palm Pilot using SuperWaba is here. I have created my first program, it's a Quiz program. Each quiz must contains 10 questions and answers. You can have many categories of quizzes. The source file for the quiz program is here. Additional source file to read a .pdb file is here. Another source file is to convert a text file in your PC to a Palm Pilot format .pdb file. The text file must be in this format: 3 lines of question, 3 lines of answer 1 line of correct answer, questions can be multiple choice or True/False. The text file must contains 70 files and no extra formatting, (Edit in DOS, Notepad, Advanced Editor in KDE). The source file to convert the text file to a Palm Pilot is here. You can have different quiz data file as long as you change the file name in the convert file. To convert two or more quiz data file, create a file named 'test.txt' using format 3 question line, 3 answer line, 1 correct answer line, times 10. Edit the Converter program variable typeC to 'Q000', then run the converter program, this will produce 'Q000.pdb'. Rename 'test.txt' then create another data file, edit the Converter program variable typeC to 'Q001', then run the converter program again, this will create 'Q001.pdb'. Repeat steps for as many quiz data file you have, remember that each data file has format 3 line of questions, 3 line of answers, 1 line of correct answer. Install the file Quiz.pdb, Quiz.prc, Q000.pdb, Q001.pdb ... (and all your created quiz data file) on your Palm Pilot. Click on the Quiz program then pick from the list of available categories, the list will match the number of your datafile (the first name on the list will correspond to 'Q000.pdb', second name on the list will correspond to 'Q001.pdb' and so on.) Make sure you edit the Quiz.java item names to match your category (if your file 'Q000.pdb' is about science and 'Q001.pdb' is about Java and 'Q002.pdb' is about history, then change the code in Quiz.java to String items[] = {"Science", "Java", "History", and so on ...};. You must hava the SuperWaba virtual machine installed in your Palm Pilot to run the quiz program, see http://www.superwaba.org/. The quiz program is tested on a Palm Pilot XE (Palm OS v. 3.5.0) and Palm Pilot E (Palm OS v. 3.1.1) using SuperWaba version 2.0b4. Here is a picture of the Quiz program on Linux screen capture and picture of the Quiz program on a Palm Pilot XE.
Another program for the palm, this is a mini conversion program metrics, fahrenheit, celsius, source code is here.


Cybiko wireless


What are cybiko wireless pda ? Click here for picture of the Cybiko classic. Check out www.cybiko.com, for under $10.00 you can find lot's in e-bay. Cybiko's are kid's pda with lcd screen 160x100 pixel, full QWERTY keyboard with function keys, Ni-MH 700 mAp rechargeable battery, RS232 connection port, built-in RF antenna, stylus, speaker, Charger, PC connection cable, memory expansion, CPU and the best of all... wireless communication. CPU is 32 bit, 11 MHz Hitachi H8s/2246, co-processor is Atmel AT90S2313 4 Mhz, RAM 512 KB, Flash disk 512 KB expandable to 1 MB, expansion cartridge 68-pin, Frequency 902-928 Mhz, 30 digital channels, 19200 bps wireless communication. Wireless communication is 300 feet outdoor, 150 feet indoor. Software Development Kit is available free at www.cybiko.com for Windows and Linux. These cybiko's make excellent, terminals (for siteplayer or TINI or Stamps). Classic style comes with RS-232 and the Extreme comes with USB. I had one cybiko as a master hooked-up to the P.C. running Java software polling 3 cybiko's acting as slaves. Code for the Java server is here. Two codes for the cybiko are available in 'C' language. Master cybiko code is here. Slave cybiko code is here. I had one master constantly polling three cybiko's for over a week without problem. Again, the possibilities are endless, it could be used as a terminal, or how about an e-mail terminal, anywhere inside or outside your house, you can find out if you have new e-mail and read it. These cybiko's are a lot cheaper than buying wireless palm or pocketpc. Search google for source codes, and other cybiko's user's group. Programming is not bad either, nice SDK, a few tutorials, and some complete programs free at www.cybiko.com. For under $10 dollars, it's pretty hard to beat the features of the cybiko, especially if you will use the wireless communication feature.


Home Automation




General notes on compiling Java between Linux and Windows


Unix/Linux end of line terminator = "\n"
Mac end of line terminator = "\r"
Windows end of line terminator = "\r\n"
If you are having problem with sockets try not to use println() but write explicit "\r\n" to the sockets
Error while running Tomcat 4.0.3 the error is Root Cause java.lang.NoSuchMethodError pointing to org.apache.jasper.compiler.TldLocationsCache.processJars(TldLocationsCache.java:202) Servlets is fine but everytime a JSP page is served, I get this error. Another error running Tomcat 4.1.18 JSP examples is this part of the source code if(pageContext != null) pageContext.handlePageException this occurs compiling the JSP page. After numerous hours of troubleshooting and searching the Internet, the solution for both of these problems is somehow I have a file named servlet.jar in my $JAVA_HOME/jre/lib/ext/ directory, by deleting the servlet file and leaving the servlet file only at $CATALINA_HOME/common/lib directory everything works fine.