Link

Puzzle (What’s my class?)

Consider the following example.

package demo;

public class App {
  public static void main( String[] args ) {
    String name = App.class.getName().replaceAll( ".", "/" ) + ".class";
    System.out.println( name );
  }
}

What will the above code prints?

////////.class

This example was taken from PUZZLE 20: WHAT’S MY CLASS? in Java™ Puzzlers: Traps, Pitfalls, and Corner Cases.

The problem is that String.replaceAll() takes a regular expression as its first parameter, not a literal sequence of characters. (Regular expressions were added to the Java platform in release 1.4.) The regular expression "." matches any single character, and so every character of the class name is replaced by a slash, producing the output we saw.