Translation into Java

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

The base cases are:

1. equals( "", "" )     = true
2. equals( "", X )      = false if X is not the empty string
3. equals( X, "" )      = false if X is not the empty string
4. equals( x+X, y+Y )   = false if x != y

These are base cases because the result can be computed immediately.

Translation into Java

Of course there is an equals() method that is part of the class String. Let us forget this and write our own method. This should be merely a matter of translation:

  boolean equals( String strA, String strB )
  {
    // 1. equals( "", "" ) = true
    if       ( strA.length()  0 && strB.length()  0 )  
      return true;
      
    // 2. equals( "", X ) = false if X is not the empty string
    else if  ( strA.length()  0 && strB.length()  0 )  
      return false;
      
    // 3. equals( X, "" ) = false if X is not the empty string
    else if  ( strA.length()   0 && strB.length() 0 )  
      return false;
      
    // 4. equals( x+X, y+Y ) = false if x != y
    else if  ( strA.charAt(0)  strB.charAt(0) )         
      return false;
      
    // 5. equals( x+X, y+Y ) = true  if x == y and equals( X, Y )
    else
      return ( strA.substring(1), strB.substring(1) ); 
  }

To detect an empty string, check if the length is zero. Remember that an empty string is a string that contains no characters. The value null is something different.

The method call strA.substring(1) returns the substring that consists of character 1 and all characters that follow it in strA.

QUESTION 15:

Those blanks are made for filling.