Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pattern() vs toString() in Pattern class

What is the difference between the pattern() method and the toString() method in the Pattern class?

The doc says:

public String pattern()

Returns the regular expression from which this pattern was compiled.

public String toString()

Returns the string representation of this pattern. This is the regular expression from which this pattern was compiled.

Even their implementation returns the same result:

import java.util.regex.*;

class Test {
  public static void main(String[] args) {
    Pattern p = Pattern.compile("[a-zA-Z]+\\.?");
    String s = p.pattern();
    String d = p.toString();
    System.out.println(s);
    System.out.println(d);
  }
}

I see no difference, so why are there two methods? Or am I missing something?

like image 721
Surender Thakran Avatar asked May 27 '12 11:05

Surender Thakran


1 Answers

Because each class has a toString() method which was inherited from Object. The toString() method is supposed to return a string which represents the object the best way it can, if it is even possible to create some kind of string representation. The name toString() is pretty vague, so they added a method pattern() which is more straightforward.

And because they wanted toString() to return something clever they used the pattern of the regex, which is a good string representation for the Pattern class.

like image 146
Martijn Courteaux Avatar answered Nov 15 '22 18:11

Martijn Courteaux