Wednesday, June 15, 2005

Java Samples


Generated during class with South Dakota State employees but hopefully useful to anyone who wanders this way.

[NOTE: My web host doesn't serve the *.java files, so download the zipfile at the end of this post instead. I'll rename with *.txt later.]

We began things with a Hello World program in Soon after we talked about defining classes, the basic building block of any java program. shows an example of a class with fields, methods, getters and setters (accessor methods), and a constructor. Along the way we also learned about overloading, as seen in

We learned more details about class definitions: (check with and are examples of how you can chain constructors. was used to show the difference between static and instance methods and fields. You can see the BankAccount class tested in Once we were comfortable with the static keyword, we talked about defining constants, using as our example.

We had a chapter that covered arrays, in which we looked at I added an aside about Collection classes in java, which are a more robust alternative to arrays in most cases, and we looked at Even though I got the bubble sort wrong in class, it's fixed in this example with some helper methods, sortMyArray and printArray. We looked at working with Calendars and dates in I also included a that shows how to get the functionality of a basic DateDiff command. Like other things, it's ugly in java.

You saw one class from the swing library, the JOptionPane, which was used to talk about getting user input. I also showed you the BufferedReader along with it in I would recommend the BufferedReader approach if your application runs from the command line, personally. For most other examples in class, we used, which abstracted reading and writing from the console with a few simple methods.

At this point we began to cover inheritance. We looked at a basic inheritance heirarchy in,, and We looked at abstract classes in and we briefly looked at interfaces in

We closed out with the basics of exception handlers and subclassing exception. The try{..}catch{...}finally{...} is probably best introduced by your material.

Our final two topics were File I/O and parsing XML documents. On the File I/O side, I had two classes: to demonstrate methods of reading from a file stream, and, to demonstrate writing to a file stream. In terms of XML, I have a class called which should help you get started parsing XML files.

Wow, that was a lot for three days. Even typing it out makes me tired. In regards to the samples, you can download them individually, or you can download a zip archive of the entire set. If you have questions or comments, don't hesitate to email me.


No comments: