<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Moose56 blog &#187; Java</title>
	<atom:link href="http://www.moose56.com/blog/category/java/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.moose56.com/blog</link>
	<description></description>
	<lastBuildDate>Fri, 13 Jan 2012 07:24:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Java Paint: Part 1</title>
		<link>http://www.moose56.com/blog/2008/04/15/java-paint-part-1/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-paint-part-1</link>
		<comments>http://www.moose56.com/blog/2008/04/15/java-paint-part-1/#comments</comments>
		<pubDate>Tue, 15 Apr 2008 16:47:59 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/04/15/java-paint-part-1/</guid>
		<description><![CDATA[Java includes a load of libraries for creating applications with graphical user interfaces (GUI). One of the first things that a programming student is introduced to when learning about Java GUI development is drawing shapes onto a &#8220;canvas&#8221;. In this post I am going to talk about Java Swing objects that can help achieve this [...]]]></description>
			<content:encoded><![CDATA[<p>Java includes a load of libraries for creating applications with graphical user interfaces (GUI). One of the first things that a programming student is introduced to when learning about Java GUI development is drawing shapes onto a &#8220;canvas&#8221;. In this post I am going to talk about Java Swing objects that can help achieve this and begin to flesh out a little program that demonstrates some of the ideas that are covered.</p>
<p><span id="more-36"></span></p>
<p>This is a really good place to start for some intermediate Java topics and we will cover:</p>
<ul>
<li>Inheritance</li>
<li>Collections</li>
<li>Double buffering</li>
<li>Polymorphism</li>
</ul>
<p>So before we get going here is a little disclaimer; the following code is an example of how to go about implementing the requirements. It is not the only way or the right way. Second, I am not a Java guru, expert, oracle etc. I just like to tinker with stuff and thought I would share my findings to help others.</p>
<p>So lets begin, first up we need some form of specification. What do we actually want the program to do? I want the user to be able to select a type of shape (Circle or Square) and be able to click on the window of the application and draw the specified shape. I also want everything that the user draws to remain on the window when the window is moved or minimized. The window should be of a specific size and the user should not be able to maximize the window.</p>
<p>Did you get all that? so the fist task might be to dig all of the program features out of this brief paragraph. One thing that quickly becomes apparent however is the large amount of stuff that is not specified. This is a real pain when trying to design a program as the person that list the requirements will usually have a good idea of what they want it to do and will focus on that. This leaves a load of small decisions that still need to be made. In this example there are a few, take the shapes for example. The different types have been specified (square and circle), but the size, color and border are anyones guess. Also the method that the user has to select a specific shape is not specified.</p>
<p>As you can see even with a relatively small program the requirements can be large. For the sake of this little tutorial though I will finish with the specification as I want to focus on the way Java works and how to go about implementing this in Java. You will see how the specification is fulfilled and any other requirements decided further into the post.</p>
<p>As this is part 1 I am only going to implement a limited set of features. I have decided to split it as there are a number of things to take in and it would turn into the longest post in the world and become very boring and hard to follow if I crammed everything into one post. So in this post I will cover setting up a frame and a canvas, mouse interaction with the canvas, and drawing onto the canvas. I will then put this all together and produce a program that can draw a square.</p>
<h2>The Frame</h2>
<p>The following code is taken from <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/toplevel.html">here</a> and is adapted for this example. The class MainFrame creates a window on the screen. This is the window that everything else will happen within. This is an important part of the application because it interacts with the underlying operating system and handles all the displaying stuff so we don&#8217;t have to worry about it.</p>
<p>The main method is used to get everything up and running by calling the createAndShowGUI() method which contains all the code to specify how we want our frame to look and behave.</p>
<p>
<pre class="viewsource"><code class="java">
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MainFrame {

    private static void createAndShowGUI() {

        // Create and set up the window.
        JFrame frame = new JFrame("A Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // Set frame size
        frame.setSize ( 300, 350 );
        // prevent frame from maximising
        frame.setResizable (false);
        // center the frame on the screen
        frame.setLocationRelativeTo (null);
        // display it
        frame.setVisible(true);
    }

    public static void main(String[] args) {

        // Schedule a job for the event-dispatching thread:
        // creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}</code></pre>
</p>
<p>Compiling and running this code should give you an empty window in the center of your screen like the one pictured below.</p>
<p><img src="http://65.38.103.130/~moose56/blog/wp-content/uploads/2008/03/mainframe.jpg" alt="mainFrame.jpg" width="344" height="394" border="0"/></p>
<p>For a bit more info on what is going on in the main method check out this <a href="http://www.velocityreviews.com/forums/t133638-swing-and-threads.html">forum post</a>.</p>
<h2>The Canvas</h2>
<p>As well as the JFrame class Java Swing also provides a JPanel class. The JPanel is described as a lightweight container panel. Basically this means you can use it to contain other controls or other objects. What we are going to use it for in this example is the canvas which the user paints on. This will be where the majority of our applications logic will be held as the canvas will be responsible for listening for user input and the dealing with it should the users perform an action.</p>
<p>In order the get a picture of what this is imagine that the JFrame created in the previous example is a blank table and the JPanel is a clean piece of paper we are going to lay on top of it to draw on. The image below shows are frame with a JPanel covering the JFrames content pane. The content pane is the part of the JFrame that we are going to put are JPanel in. In the picture the JPanel has been colored white as by default its transparent.</p>
<p><img src="http://65.38.103.130/~moose56/blog/wp-content/uploads/2008/03/mainframe-with-panel.jpg" alt="mainFrame_with_panel.jpg" border="0" width="346" height="386" /></p>
<p>Because we need the JPanel to react to user input and we will also want to override a few of its method (you will just have to trust me on this for now). I am going to create a sub class of JPanel called CanvasPanel. This is were all are code will go.</p>
<p>In order to detect the user clicking onto the CanvasPanel we need to add a MouseAdapter and a MouseMotionAdapter to the CanvasPanel. This can be done in the constructor. A small demo version of the CanvasPanel class is shown below.</p>
<p>
<pre class="viewsource"><code class="java">
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.JPanel;

class CanvasPanel extends JPanel {

    public CanvasPanel () {

        this.setBackground ( Color.WHITE );

        // add the input listners
        addMouseListener ( new MouseAdapter () {
            public void mousePressed ( MouseEvent e ) {
                System.out.println ("Mouse Pressed: X = " +
                    e.getX () + ", Y = " + e.getY () );
            }
        });

        addMouseMotionListener ( new MouseMotionAdapter () {
            public void mouseDragged ( MouseEvent e ) {
                System.out.println ("Mouse Dragged: X = " +
                    e.getX () + ", Y = " + e.getY () );
            }
        });
    }
}</code></pre>
</p>
<p>As you can see its pretty simple at the moment. All we have is a constructor that sets the background color to white and then adds are mouse input listners. Within these two listners I have stuck a couple of rudimenty console output lines to test that its all working. In order to get our MainFrame object using this fancy new CanvasPanel we need to update the createAndShowGUI method to this:</p>
<p>
<pre class="viewsource"><code class="java">
private static void createAndShowGUI () {
    // Create and set up the window.
    JFrame frame = new JFrame ( "A Frame" );
    frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );

    /*
     here is the new line
    */
    frame.getContentPane().add(new CanvasPanel());

    // Display the window.
    frame.setSize ( 300, 350 );
    // prevent frame from maximising
    frame.setResizable ( false );
    // center the frame on the screen
    frame.setLocationRelativeTo ( null );
    frame.setVisible ( true );
}</code></pre>
</p>
<p>So as discussed previously we a telling our MainFrame object to use our CanvasPanel by adding a new CanvasPanel object to the MainFrame&#8217;s ContentPane. Running this should display a frame that looks the same as before but when you click on it the X and Y coordinates are printed to the console.</p>
<h2>The Shapes</h2>
<p>So you want to add a shape? Well yes of course you do or you would not have bothered to read this far. A shape is an interesting thing in Java and I advise you to have dig around in the libraries to see what is already available. To cut a long story short Java already has a pretty good shape class hierarchy in the standard library. I know is a favorite topic for lecturers to use when talking about inheritance and its all in the Java library. The majority of objects that Java specifies for representing shapes impliment the Shape interface. In this iteration of the example we want to focus on the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Rectangle.html">Rectangle</a> class.</p>
<p>Before we can start painting however we need to understand a few other things about the CanvasPanel object we created earler. What we need is to override the paintComponent within CanvasPanel. This method is called every time something is updated or changed like the location of the frame on the screen or another application&#8217;s window passes in front of our window. The paintComponent method is passed a <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/awt/Graphics.html">Graphics</a> object. A quick look at the documentation for this and we find a number of very usefull sounding methods like drawRect() and drawOval(). The Graphics object is the thing we need. Everything we want to display we draw on this object.</p>
<p>Now before we get going with our rectangle I need to talk about a few things. What I want to happen is that when a user clicks on the CanvasPanel a new square is drawn. If the user drags the mouse over the panel then a line of squares should be drawn. This raises a few questions. How do I remeber where all the squares are meant to be and how do I triger the paintComponent method myself?</p>
<p>First up I think we need a Square object to see what we are talking about:</p>
<p>
<pre class="viewsource"><code class="java">
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

public class Square extends Rectangle {
    int SIZE = 20;
    Color squareColor = Color.RED;

    public Square ( int x, int y ) {
        super();
        this.x = x;
        this.y = y;
        this.height = SIZE;
        this.width = SIZE;
    }

    public void paintMe ( Graphics g ) {
        g.setColor ( squareColor );
        g.fillRect ( x, y, width, height );
    }
}</code></pre>
</p>
<p>I have extended the Java Rectangle class and have added a special method called paintMe to my Square which takes a Graphics objects and draws a square onto it. We now have to add a little bit to the CanvasPanel in order for it to be able to store the Square objects and pass a Graphics object to them. First off I need an array to hold all of the Square objects that are created by the user. Initially you may be thinking easy, declare an Array, no problem. Thinking about it though this is not a good idea mainly because we do not know how big the array needs to be. The user may draw 1 Square or 1000 so we need a container object that can handle this. Introducing the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html">ArrayList</a>. With an array list we don&#8217;t need do declare a size as it has the ability to shrink and grow depending on what is added or removed from it.</p>
<p>So every time we detect mouse activity on the CanvasPanel we create a new shape and add it to the ArrayList. Then we call the repaint() method which trigers the repainting of the Canvas and draws the new shape. This is done by overriding the paintComponent() method and looping through the ArrayList and calling the paintMe() method of each shape. All of these modifications are shown in the updated version of the CanvasPanel class below:</p>
<p>
<pre class="viewsource"><code class="java">
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.ArrayList;
import javax.swing.JPanel;

class CanvasPanel extends JPanel {

    // declare arraylist to store shapes
    ArrayList&lt;Square&gt; s = new ArrayList&lt;Square&gt;();

    public CanvasPanel () {

        this.setBackground ( Color.WHITE );

        // add the input listners
        addMouseListener ( new MouseAdapter () {
            public void mousePressed ( MouseEvent e ) {
                newSquare ( e.getX (), e.getY () );
            }
        } );

        addMouseMotionListener ( new MouseMotionAdapter () {
            public void mouseDragged ( MouseEvent e ) {
                newSquare ( e.getX (), e.getY () );
            }
        } );
    }

    private void newSquare ( int x, int y ) {

        // add new square to list
        s.add(new Square( x, y ));

        // repaint screen
        repaint ();
    }

    public void paintComponent ( Graphics g ) {
        super.paintComponent ( g );

        // loop through each square
        for(Square tmp:s)
            // paint it
            tmp.paintMe(g);
    }
}</code></pre>
</p>
<p>As you can see every time input is detected a call to newSquare() is made with the X and Y of the input. A new Square is created and added to the ArrayList and then a call to repaint() is made. This invokes the paintComponent() method which loops through all the shapes and passes them the Graphics object for each Square to paint its self onto.</p>
<h3>Tidy up</h3>
<p>If you run the program now you should be able to draw squares onto the canvas, but there is one small issue in that the square is drawn from top left corner. I want the mouse pointer to be in the middle of the square when it is drawn. To do this we simple change the way the Square object interprets the X and Y values that it&#8217;s given by offsetting them by half of the squares length so that the constructer now looks like this:</p>
<p>
<pre class="viewsource"><code class="java">
public Square ( int x, int y ) {
    super();
    this.x = x - (SIZE/2);
    this.y = y - (SIZE/2);
    this.height = SIZE;
    this.width = SIZE;
}</code></pre>
</p>
<p>Now run the program and the squares are nicely centered on the pointer.
<p><img src="http://65.38.103.130/~moose56/blog/wp-content/uploads/2008/04/squares.jpg" alt="squares.jpg" border="0" width="352" height="392" /></p>
<h2>Thats a wrap</h2>
<p>That&#8217;s it for part 1. In the next part I will cover double buffering.</p>
<h2>Resources</h2>
<p>You can download the source files for part 1 <a href="http://65.38.103.130/~moose56/blog/wp-content/uploads/2008/04/part1.zip" title="part1.zip">here</a>.</p>
<p>Here are some of the books and web pages that I found really useful in trying to understand this topic:</p>
<h3>Books</h3>
<ul>
<li><a href="http://www.amazon.co.uk/Core-Java-Fundamentals-v/dp/0131482025/">Core Java</a> (newer version available)</li>
<li><a href="http://www.amazon.co.uk/Head-First-Java/dp/0596009208/">Head First Java</a></li>
<li><a href="http://www.amazon.co.uk/Killer-Game-Programming-Java-Book/dp/0596007302">Killer Game Programming in Java</a></li>
</ul>
<h3>Web Pages</h3>
<ul>
<li><a href="http://java.sun.com/products/jfc/tsc/articles/painting/">Painting in AWT and Swing</a></li>
<li><a href="http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html">Performing Custom Painting</a></li>
<li><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/index.html">Using Swing Components</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/04/15/java-paint-part-1/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Java private class fields not so private</title>
		<link>http://www.moose56.com/blog/2008/02/05/java-private-class-fields-not-so-private/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-private-class-fields-not-so-private</link>
		<comments>http://www.moose56.com/blog/2008/02/05/java-private-class-fields-not-so-private/#comments</comments>
		<pubDate>Tue, 05 Feb 2008 11:39:24 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/02/05/java-private-class-fields-not-so-private/</guid>
		<description><![CDATA[Brushing up on some Java I came across an interesting &#8220;feature&#8221; of private class fields that reference mutable objects. I thought it might help someone if I show how to get round the issue. In order to illustrate this problem we first need a basic (very basic) class: class Person { Person(int year, int month, [...]]]></description>
			<content:encoded><![CDATA[<p>Brushing up on some Java I came across an interesting &#8220;feature&#8221; of private class fields that reference mutable objects.</p>
<p>I thought it might help someone if I show how to get round the issue.</p>
<p><span id="more-16"></span></p>
<p>In order to illustrate this problem we first need a basic (very basic) class:</p>
<pre class="viewsource"><code class="java">
class Person {

    Person(int year, int month, int day) {
        GregorianCalendar calendar = new GregorianCalendar(year, month, day);
        this.dateOfBirth = calendar.getTime();
    }

    public Date getDateOfBirth() {
        return dateOfBirth;
    }

    private Date dateOfBirth;
}
</code></pre>
<p>So apart form its limited functionality what is wrong with this class? It has a private class field and an accessor method for it so in theory it is nice and safe encapsulated in the class right? Wrong!</p>
<p>The class field is a references to an object. When the accessor method is called it returns a copy of the reference to that object. Now the class and the code that called the accessor method both have a reference to the same object. This means that the code that called the accessor method can change the object and the Person class can do nothing about it.</p>
<p>Here is a little example, first a Person object is created:</p>
<pre class="viewsource"><code class="java">
Person aPerson = new Person(1958, 1, 5);
</code></pre>
<p>A call to getDateOfBirth() would return a reference to a Date object with a year of 1958. All good so far.</p>
<p>Now for the mayhem; The code below creates a new Date object called newDateOfBirth. It is a copy of the Person&#8217;s dateOfBirth object reference. 10 years in milliseconds is calculated and added to newDateOfBirth in effect bringing the newDateOfBirth forward 10 years.</p>
<pre class="viewsource"><code class="java">
Date newDateOfBirth = aPerson.getDateOfBirth();

double tenYearsInMilliSeconds = 10 * 365.25 * 24 * 60 * 60 * 1000;

newDateOfBirth.setTime(newDateOfBirth.getTime() + (long) tenYearsInMilliSeconds);
</code></pre>
<p>Because newDateOfBirth is a new variable it is reasonable to think that it is a new object on its own and has nothing to do with the Person object. The problem here though is because a reference was passed to it newDateOfBirth and aPerson.dateOfBirth are both looking at the same object. Any change made to newDateOfBirth will effect aPerson.dateOfBirth. The following code proves this:</p>
<pre class="viewsource"><code class="java">
System.out.println(aPerson.getDateOfBirth());
</code></pre>
<p>This will give the year 1968 not 1958.</p>
<p>A simple way to fix this problem is to return a reference to a copy of the object instead of the reference itself. This is a simple change to the getDateOfBirth method:</p>
<pre class="viewsource"><code class="java">
public Date getDateOfBirth() {
    return (Date) imutabledateOfBirth.clone();
}
</code></pre>
<p>By using the clone method this problem is fixed, smily faces all round.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/02/05/java-private-class-fields-not-so-private/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Java string reverse methods analyses</title>
		<link>http://www.moose56.com/blog/2008/01/25/java-string-reverse-methods-analysed/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=java-string-reverse-methods-analysed</link>
		<comments>http://www.moose56.com/blog/2008/01/25/java-string-reverse-methods-analysed/#comments</comments>
		<pubDate>Fri, 25 Jan 2008 13:53:27 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/01/25/java-string-reverse-methods-analysed/</guid>
		<description><![CDATA[Following on from my previous post about making a simple palindrome detector, I analyse the performance of five different methods for reversing a string in Java. First, here are 5 different reverse methods: The good old for loop version public static String reverse_loop (String in) { String out = ""; for (int i=0; i&#60;in.length(); i++) [...]]]></description>
			<content:encoded><![CDATA[<p>Following on from my previous post about making a simple palindrome detector, I analyse the performance of five different methods for reversing a string in Java.</p>
<p><span id="more-14"></span></p>
<p>First, here are 5 different reverse methods:</p>
<p>The good old for loop version</p>
<pre class="viewsource"><code class="java">
public static String reverse_loop (String in) {
    String out = "";
    for (int i=0; i&lt;in.length(); i++) {
        out += String.valueOf(in.charAt((in.length()-1)-i));
    }
    return out;
}
</pre>
<p></code></p>
<p>A string buffer with an extra variable version</p>
<pre class="viewsource"><code class="java">
public static String reverse_buffer_var (String in) {
    StringBuffer sb = new StringBuffer(in).reverse();
    return sb.toString();
}
</pre>
<p></code></p>
<p>A string buffer without an extra variable version</p>
<pre class="viewsource"><code class="java">
public static String reverse_buffer (String in) {
    return new StringBuffer(in).reverse().toString();
}
</pre>
<p></code></p>
<p>A Recursive version from <a href="http://stephan.reposita.org/archives/2007/11/12/string-reversing-part-ii-tail-recursion/">here</a></p>
<pre class="viewsource"><code class="java">
public static String reverse_recur (String in) {
    if (in.length() &lt;= 1) {
        return in;
    }
    return reverse5(in.substring(1)) + in.charAt(0);
}
</pre>
<p></code></p>
<p>A tail recursive version from <a href="http://stephan.reposita.org/archives/2007/11/12/string-reversing-part-ii-tail-recursion/">here</a></p>
<pre class="viewsource"><code class="java">
public static String reverse_tail_recur(String str) {
    if (str.length()  &lt;= 1) {
        return str;
    }
    return reverse_tail_recur(str, "");
}

private static String reverse_tail_recur(String str, String acc) {
    if (str.length() == 0) {
        return acc;
    } else {
        return reverse_tail_recur(str.substring(1), str.charAt(0) + acc);
    }
}
</pre>
<p></code></p>
<p>So I created a string and passed it to each of these methods. Using NetBean's performance tools I recorded the amount of time it took for each method to reverse the string and the results are as follows:</p>
<ol>
<li>reverse_buffer 0.077ms</li>
<li>reverse_buffer_var 0.408ms</li>
<li>reverse_recur 8.17ms</li>
<li>reverse_tail_recur 10.76ms</li>
<li>reverse_loop 73.2ms</li>
</ol>
<p>So from this it is easy to see that the loop method is the slowest. It is also a good argument for using the JDK methods where available as using a StringBuffer and its reverse method was by far the quickest</p>
<h3>Update</h3>
<p>Found <a href="http://faisalferoz.wordpress.com/2007/12/24/loop-vs-systemarraycopy/">this</a> post which reiterates that using a native method is probably the best course of action.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/01/25/java-string-reverse-methods-analysed/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Palindrome: Java &amp; Ruby</title>
		<link>http://www.moose56.com/blog/2008/01/24/palindrome-java-ruby/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=palindrome-java-ruby</link>
		<comments>http://www.moose56.com/blog/2008/01/24/palindrome-java-ruby/#comments</comments>
		<pubDate>Thu, 24 Jan 2008 15:00:00 +0000</pubDate>
		<dc:creator>moose56</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://moose56.com/blog/2008/01/24/palindrome-java-ruby/</guid>
		<description><![CDATA[One thing that programming students often have to implement is a program to tell whether or not a string is a palindrome. In this post I flex my dusty Java and demonstrate a simple palindrome detector. Java First off just in case you are not sure, a palindrome is a string that reads the same [...]]]></description>
			<content:encoded><![CDATA[<p>One thing that programming students often have to implement is a program to tell whether or not a string is a palindrome. In this post I flex my dusty Java and demonstrate a simple palindrome detector.</p>
<p><span id="more-135"></span></p>
<h2>Java</h2>
<p>First off just in case you are not sure, a palindrome is a string that reads the same forwards as it does backwards. e.g madam</p>
<p>So to solve this I guess we need a method called pallindrome()</p>
<pre class="viewsource"><code class="java">
public static boolean isPalindrome (String word) {
    if (word.equalsIgnoreCase(reverse(word))) { return true; }
    else { return false; }
}
</code></pre>
<p>So here we have a method called isPalindrome that takes a string and returns true or false depending on the success of the if statement. The line that performs the test is:</p>
<pre class="viewsource"><code class="java">
word.equalsIgnoreCase(reverse(word))
</code></pre>
<p>This uses the Java String method equalsIgnoreCase to test if word is equal to the result of reverse(word). If true then it is a palindrome.</p>
<p>So what is missing from this code? the implementation of the reverse method. There are many ways to reverse a String, below is my first attempt</p>
<pre class="viewsource"><code class="java">
public static String reverse (String in) {
    String out = "";
    for (int i=0; i&lt;in.length(); i++) {
        out += String.valueOf(in.charAt((in.length()-1)-i));
    }
    return out;
}
</code></pre>
<p>This is a typical loop through the characters in a string in reverse and build up another string with these characters and then return this new string. All fine and good, then I googled a bit and found out that the Java StringBuffer object has a native reverse method so I can rewrite the method as follows:</p>
<pre class="viewsource"><code class="java">
public static String reverse (String in) {
    StringBuffer sb = new StringBuffer(in).reverse();
    return sb.toString();
}
</code></pre>
<p>As well as being fewer lines of code this is far more clear than a the for loop method.</p>
<h3>Things to take note of</h3>
<p>The reason I split the palindrome method and reverse method instead of having them as one was to improve the testability of the code. It also increases the chances of reuse as it is forceable that I may want the reverse method at a later date on it own without the palindrome stuff.</p>
<p>This is not a perfect implementation. The second to you stick more than one word into isPalindrome it will fall down because at the moment it will not ignore space characters so a palindrome such as &#8216;nurses run&#8217; will return false</p>
<p>It may not be totally perfect but I enjoyed the exorcise and feel it must be better than the version I came up with 6 years ago on my introduction to programming course.</p>
<h2>Ruby</h2>
<p>Yes yes, I know another Ruby version of perfectly good code, but the main reason I include it is that its really cool (well for me anyway). This is because the Ruby String object has a reverse method already and because of the open nature of Ruby classes you can add a palindrome method to Ruby&#8217;s String without any inheritance stuff. Take a look:</p>
<pre class="viewsource"><code class="ruby">
class String
 def palindrome?
   self == self.reverse
 end
end

"madam".palindrome? # returns true
</code></pre>
<p>I really like this method, but of course with great power comes great responsibility and open classes are not always a good idea.</p>
<h2>Update</h2>
<p>So reading more into this it appears that the Java string buffer method might be faster and more efficient than the loop method. The reason for this is that when Java converts the loop method into byte code it substitutes the string concatenation operator for a string buffer and uses the append method. It does this for every concat operation and uses the default buffer size of 16 characters.</p>
<p>Some other factors to take into consideration are that if a null string, empty string  or a single character are passed in. A null string will cause a NullPointerException so it is important that it is dealt with. If an empty or one character string is entered they should be returned strait away and no string buffer object created because they are already a reverse of them selves. This means a slight change to the method:</p>
<pre class="viewsource"><code class="java">
public static String reverse (String str) {
    if (str == null) {
        // kick out an error
        throw new NullPointerException( "reverse passed null String" );
    } else if (str.length() &lt;= 1) {
        // string is already revesed
       return str;
    }
    // use the StringBuffer to reverse str
    return new StringBuffer(str).reverse().toString();
}
</code></pre>
<p>Here are some good resources on this topic. I really love the way that you can google something and it turns up a load of stuff that can really help in how you approach a problem and give advice on the merits of different solutions. It really helps improve you.</p>
<ul>
<li><a href="http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html">StringBuffer versus String</a></li>
<li><a href="http://www.rgagnon.com/javadetails/java-0129.html">Optimizing string operations</a></li>
<li><a href="http://lists.ibiblio.org/pipermail/dev-dpml/2005q1/000657.html">NullPointerExceptions</a></li>
<li><a href="http://stephan.reposita.org/archives/2007/11/09/java-interview-questions-write-a-string-reverser-and-use-recursion/">A great blog on reversing strings with java</a></li>
</ul>
<p>Lastly I tried a few different Java methods for reversing a String. You can find the results <a href="http://moose56.com/blog/2008/01/25/java-string-reverse-methods-analysed">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.moose56.com/blog/2008/01/24/palindrome-java-ruby/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

