A friend was telling me about a question he saw on an exam and wanted to know my thoughts on it. The exam wanted you to write out the function in pseudo code first and then write it in Java and ColdFusion. The question was pretty basic but it was a good one to think about. Write a method that will accept a sentence as an argument. The method will take this string and reverse the order of the words in the argument.

So following our instructions the first thing we need to do is talk out our thought process for this method.

  • create a variable to hold our new string
  • Split the argument into words using a space as the delimiter
  • loop over out list of words
  • take the current word in the loop and prepend it to our new string

That was pretty easy and gives us some really straight forward instructions on how to create our method. First I will write the method in Java. Lucky for us Java has a wonderful class called StringTokenizer. This class will allow us to break our string into tokens and has convenience methods for looping over the tokens and getting the next token.

As you might know ColdFusion can leverage any Java class. Because of that our method in ColdFusion should look pretty much the same. If your not familiar with ColdFusion the init method is just a way for us to pass something into the Java constructor.