Results 1 to 2 of 2
  1. #1
    Codeless is offline Member
    Join Date
    Nov 2010
    Rep Power

    Default How does this very simple code work?

    This is a simple recursion program which reverses the order of characters in a word

    Java Code:
    public class Main 
    public static String reverse(String str)
    	if (str.equals(""))
    		return "";
    		char first = str.charAt(0);
    		String part = str.substring(1);
    		return reverse(part)+ first ;
    public static void main (String[] args)
    my question is waht happens here
    Java Code:
    return reverse(part)+ first ;
    because to me it looks like it should print the word in the same order, the value of "first" is c, then the next time through it becomes a... so why does it print tac? and not cat?

  2. #2
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Ljubljana, Slovenia
    Rep Power


    because you append the first character to the end of the string sequence.
    Ever seen a dog chase its tail? Now that's an infinite loop.

Similar Threads

  1. Simple file reader won't work in eclipse
    By BoomPony in forum New To Java
    Replies: 3
    Last Post: 11-27-2010, 05:16 PM
  2. Will this code work
    By rajat16 in forum XML
    Replies: 3
    Last Post: 09-24-2010, 11:52 AM
  3. Replies: 4
    Last Post: 08-23-2010, 03:19 AM
  4. My Simple Array Does Not Work!
    By Simplev_v in forum New To Java
    Replies: 16
    Last Post: 09-07-2009, 02:43 PM
  5. Simple animation won't work
    By nolsen01 in forum New To Java
    Replies: 4
    Last Post: 07-08-2009, 11:36 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts