regionMatches() and intern() String Java

regionMatches() and intern() String Java


The String class is rich with abundant methods used in coding. One of the methods is overloaded regionMatches() used to find the existence of a few characters of one string in another.

Supported methods from String class.

  1. boolean regionMatches(int positionFirstString, String secondString, int positionSecondString, int num): Returns a boolean value of true if the region of first and second strings contain the same character sequence. It does case-sensitive matching.
  2. boolean regionMatches(boolean b, int positionFirstString, String secondString, int positionSecondString, int num): It is same as previous, but for a boolean flag. If b is true, the method does case-insensitive matching.

Following program uses regionMatches() method (of regionMatches() and intern()).

regionMatches() and intern()

Output screen of CompareRegion.java

boolean result = s1.regionMatches(7, s2, 5, 5);

paste is the 7th character in s1 and 5th character in s2. The last parameter is the number of characters to compare. It is 5, the length of paste.

Interning String Literals

Java's idea of storing string literals(values) is altogether different from C/C++. Java does a lot of efforts towards saving memory on the machine while Java program executes. The result of one such efforts is "interning". When a string literal is created, JVM keeps the literal in a pool. When another string requires the same literal, the JVM makes the string object to point to the same literal. This saves memory as all string objects point to one literal. For example, a string object creates first time a literal "world", the "world" is placed in a pool. Second time if another object requires the same literal, Java does interning by looking to the table of string literals available in the pool, if available, the reference of the "world" is returned. The ultimate affect is all objects points to the same "world". To check the interning, use == operator instead of equals() method.

The following program uses intern() method (of regionMatches() and intern()).

regionMatches() and intern()

Output screen of InternTest.java

str1 and str2 points the same location of "world", this we know earlier, and also we used logical equals operator to compare them. JVM calls intern() method on str1 and returns the reference of "world" to str2. This is what exactly happens internally. The JVM places the "world" in the pool and its reference is returned to str2 and str3; even when we called intern() method manually on str1.

Splitting A String

A string can be split into independent words in two ways – using StringTokenizer and split() method.

Leave a Reply

Your email address will not be published. Required fields are marked *