Wednesday, 24 December 2008

Basic Mathematics in Java

The public final class Math contains all the basic numerical functions and constants.

Math.E (the base of the natural logarithms), Math.PI (ratio of circumference of a circle to its diameter).

Math.ceil, Math.floor do the expected operations, mapping doubles to ints.

Math.random, when first called creates a new PRN generator (thread-safe singleton, java.util.Random). If numerous threads are involved, multiple PRN generators ought to be instantiated. Returns a double value in the range [0,1).

Beware of the int division wall. This basically means 1/5 returns 0 since int/int returns floor(int). To avoid the "int division wall" cast to double, use decimals or write 1.0/5 to get result of division as a double.

Monday, 15 December 2008

The King of Swing

J2SE 5.0 brought in some new Swing changes.
  • Default theme is Ocean
  • New "Synth" customizable L&F (javax.swing.plaf.synth)
  • Apply a "policy" to JTextArea (to update position of caret even if updates don't occur on EDT)

Saturday, 13 December 2008

The JGoodies Animation Framework

This Java animation framework uses concepts from the W3C SML ("Smile") specification, an XML language for interactive multimedia presentations. SMIL 3.0 has recently been published (December 2008).

A key concept in the JG framework is an animation function f(t) that maps TIME to values of an attribute of an ANIMATION TARGET. e.g. within 10s the radius of a circle doubles in size at constant rate. Animation functions are continuous over time, hence a rendering system can display an animation over different frame rates and maintain the gist of the motion.

The base package is com.jgoodies.common.animation. The AnimationFunction interface maps long time values to Java objects.

Eclipse Jargon Revealed

Any user of Eclipse is exposed to a vast amount of jargon. This is a quick guide to decrypting this jargon.

BIRT - an Eclipse-based reporting system for web applications. Birt stands for Business Intelligence and Reporting Tools. Here are some examples including a Camtasia studio screencast. (Lotus produced some of the earliest screencasting software in 1994).

Wednesday, 10 December 2008

Exceptions to Java java.lang.Exceptions

The compile error: "unreported exception java.lang.Exception; must be caught or declared to be thrown" forces you to add a throws clause to a method that can throw an exception.

That's not the end of the story. If this class overrides an interface method, the throws clause must be declared at the interface level. Using Eclipse compiler it gives: "Exception is not compatible with throws clause in Interface.method()". Using Sun compiler you get a slightly different message but the intent is the same. Irritating.

What next in Java 7?

Good article on adding closures to Java. An interesting comparison is made between closures and inner classes. The article is by Angelika Langer. Closures are a very beautiful way of implementing mathematics. For example, a bisection algorithm can be elegantly implemented with closures.

To understand the limitations of inner classes versus closures we need to understand exactly the rules for inner classes in Java. An inner class can just a private class inside another class (like an embedded struct). Anonymous inner classes are used when creating ActionListeners e.g. button.addActionListener( new ActionListener() {} ).

Sunday, 7 December 2008

The Dichotomy of Mutable and Immutable in Java

String and StringBuffer are immutable and mutable analogues of one another. StringBuffers are used to implement the binary string concatenation operator.

Example: x = "a" + "b" + "c";
is compiled to x = new StringBuffer().append("a").append("b").append("c").toString();

You can also call append on ints, chars, floats and doubles.

When you instantiate a StringBuffer it has an initial capacity of 16 characters, however e.g. new StringBuffer(500) will create a StringBuffer with an initial capacity of 500 characters.

An interesting article on a mutable and immutable design pattern (as exemplified by String and StringBuffer) can be found on javaworld.

Java 6 Platform Overview

http://java.sun.com/javase/6/docs/

A very interesting tool that comes with Java 6 is the VisualVM. Details of how to run it are here.

And here is a getting started guide to VisualVM.

Saturday, 6 December 2008

Java Server Development with java.net

java.net.ServerSocket is a class for implementing server sockets. ServerSockets can be created unbound, or bound to a particular port. In either case, the constructor may throw an IOException, which may be thrown when attempting to open the socket. The most important method on a server socket is accept(), which listens for a connection to be made to the socket and accepts it. Example code (notice the interplay between the ServerSocket and Socket classes):

import java.net.ServerSocket;
import java.net.BindException;

ServerSocket listenSocket = null;
try {
listenSocket = new ServerSocket(serverPort);
while(true) {
// listen for and accept incoming connection
Socket clientSocket = listenSocket.accept();
// do something
}
} catch (BindException bindEx) {
// error message to say server is already running on serverPort
System.exit(0);
}

The socket class abstracts the concept of an endpoint of communication between two machines. A nice visual analogy of the socket idiom is the probe-and-drogue method of aerial refuelling used by the USAF. Pictures can be seen on aerospaceweb.

SSLServerSocket is a special instance of ServerSocket; these sockets aer generally created by an SSLServerSocketFactory.

Tactics for Analysing Complex Java Code

Complex Java code can be analysed quickly using the following methods.

1. Create a temp file with the code in Visual J# Express. Compress the code, refactor logically.
2. Use the program and get an idea of how it works: inputs and outputs.
3. Identify critical control paths, frequently used and unused areas of the code. (perhaps only 20% of the code is actually interesting or relevant).
4. Write up the program in Python-style pseudocode.
5. Use set theory concepts (e.g. partitions) to break up the code into mutex sections (e.g. partitions of the input space, partitions of inner classes etc).

Basics of HashMap

HashMap is an unsynchronized hashtable which permits null values. It extends the AbstractMap class, which is a partial implementation of the Map interface.

Methods inherited from Map include:

Object get(Object key)
Object put(Object key, Object value)
void putAll(Map t) - copy all mappings from t
Object remove(Object key) - returns previously associated value or null

To access the collection of keys and values in a Map, the interface declares the following methods:

public Set keySet()
public Collection values()

To iterate through the keys of a HashMap you can do:

final Iterator mapIterator = map.keySet.iterator();
while (mapIterator.hasNext()) {
final String key = (String) mapIterator.next();
final CustomType value = (CustomType) map.get(key);
}

HashMap provides constant-time performance for its basic operations (get and put) i.e. RETRIEVAL and INSERTION, assuming the hash function distributes the elements properly among the buckets.

Basics of gnu.getop

A Java port of GNU getopt based on C getopt() functions in glibc. Getopt partitions the inputs to the command-line program into optional and non-optional inputs.

import gnu.getopt.Getopt;

Getopt g = new Getopt("porridge", (String[]) args, "a:b:c:");
g.setOpterr(false); // we'll do our own error handling

while((c=getopt())!=-1) {
switch(c) {
case 'a': _alpha = g.getOptarg(); break;
case 'b': _beta = g.getOptarg(); break;
case 'c': _gamma = g.getOptarg(); break;
}

Once these options are processed, the next phase is to process non-optional arguments.
A summary of useful methods on Getopt object:

g.getopt() - returns the current option passed to the command-line
g.getOptind() - returns the NEXT index in ARGV of the next element to be scanned (non-optional argument)

Friday, 5 December 2008

IntelliJ Keyboard Shortcuts

IntelliJ is a very fast editor from jetbrains and does remote debugging more than twice as fast as Eclipse. Searching is also slicker than Eclipse. Here are some handy shortcuts for jet-setting across your source code.

Cntrl-N Jump to class
Cntrl-E Scroll through open files
Cntrl-F and F3 Search and repeat last search
Cntrl-F12 Jump through class (fields and methods)

Alt-F7 Find usages (also click "Open in new tab" to get tabbed search)
Alt-left, Alt-right Scroll through panes (Cntrl-E if you want to jump >1 step at a time)
Cntrl-B Jump to DECLARATION
Cntrl-Alt-B Jump to IMPLEMENTATION

Alt-3 go to Find screen

The Cntrl-MouseUp/MouseDown combination can be used to dynamically zoom in/out of the current pane. This is the same key combination in Internet Explorer for the same operation.

The founder of JetBrains is Sergey Dmitriev whose hobbies include pure mathematics, including functional analysis. here's an interview with him. Official bio is here.

Thursday, 4 December 2008

Basics of java.lang

rt.jar contains a lot of the core Java classes, such as those in java.lang, and java.net. When learning the core classes think of what each one is and what they are used for. Try and think of at least three examples in each case (use Google code search to help you).

Examples:

java.lang.Character (implements Serializable, Comparable). Character is a wrapper for a char. Useful e.g. when processing a character input from stdin or from gnu.getopt. Characters can be converted to strings using toString().

java.lang.System (extends Object). This fundamental class contains sytem-wide operations that act on the currently running virtual machine.

  • Exit the VM. exit(statusCode) terminates the VM. A value other than zero indicates abnormal termination
  • Bring in code from a shared library. static void load(String filename), static void loadLibrary(String libname)
  • Garbage collect. System.gc() prompts the VM to run the garbage collector.
  • Reference std input, stderr and stdout. This is done via the static PrintStream fields System.in, System.err and System.out
  • Restrict sensitive operations. This can be done by creating a SecurityManager and calling setSecurityManager on the System class.

java.lang.System is the moral equivalent of java.lang.Runtime; both classes facilitate interaction with the currently running VM. Many methods on System e.g. System.gc, can also be called on the Runtime class, e.g. Runtime.gc.

Coding Conventions - Lower Camel Case and Upper Camel Case

Java generally uses "lower camel case" (LCC) for method names. Example: br.readLine();
C# generally uses "upper camel case" (UCC) for method names. Example: sr.ReadlLine();

This is also reflected in the use of "main" in Java and "Main" in C#.

Strings are represented by "class String" in both Java and C#. The difference is in C# String is aliased to string which is more natural to use and similar to C++.

One of the earliest commercial examples of camel case is the 1950s CinemaScope film projection system.

Old School java.io

Java's BufferedReader extends the abstract Reader class, which reads character streams.

import java.io.BufferedReader;
import java.io.FileReader;

try {
BufferedReader br = new BufferedReader( new FileReader( someFile ) );
while ( br.ready() ) {
String line = br.readLine();
// processLine(line)
}

br.close();
} catch (Exception e) {}

read() will read one character, readline() will read a line. Don't forget to close the reader when you're done. The BufferedReader has two constructors, one that takes a "regular" Reader object, and the other that takes a Reader and the size of the buffer.

Tuesday, 2 December 2008

To sun.misc.Signal or not sun.misc.Signal?

In Java an application can install its own signal handler via sun.misc.Signal. This is deprecated in Java 1.6.

http://www.ibm.com/developerworks/java/library/i-signalhandling/

Blog Archive