I have this code :
JTextArea textComp;
Highlighter hilite = textComp.getHighlighter();
if (word.toString().equals(pattern[i])) 
{
    hilite.addHighlight(posStart, (posEnd), myHighlighter);
    break;
}
word is a StringBuilder
Suppose the condition in if matches and hilite.addHighlight(posStart, (posEnd), myHighlighter); - this statement is going to execute.
Then the textComp contains 
int myVar
And I try to highlight like this
int myVar
At that time, posStart = 0 and posEnd = 3. But As I am entering something into the textArea the highlighter is extending itself to the end like this:
int myVar
Can anyone help me with this?
And if I make the statement:
hilite.addHighlight(posStart, (posEnd-1), myHighlighter);
Then with posStart=0, posEnd=3, then only 
*in*t myVar this happens. i.e "in" is highlighted but "t" is not!
EDIT The function:
Highlighter.HighlightPainter myHighlighter = new MyHighlightPainter(
                    Color.LIGHT_GRAY);
            try {
                Highlighter hilite = textComp.getHighlighter();
                Document doc = textComp.getDocument();
                String text = doc.getText(0, doc.getLength());
                String[] words = text.split(" ");
                                int posEnd, posStart = 0;
                while (text.length() > posStart) {
                    posEnd = posStart;
                    StringBuilder word = new StringBuilder();
                    while (posEnd < text.length() && text.charAt(posEnd) != ' ') {
                        word.append(text.charAt(posEnd++));
                    }
                    for (int i = 0; i < pattern.length; i++) {
                        if (word.toString().equals(pattern[i])) {
                            hilite.addHighlight(posStart, (posEnd-1), myHighlighter);
                            break;
                        }
                    }
                    posStart = posStart + posEnd + 1;
                }
            } catch (BadLocationException e) {
            }