Search code examples
javasynchronizedstringbuffer

Is it possible to Return a String then Clear it in the Same Method?


Like the tittle says i was wondering if you could lets say make a Getter and in the same method clear it before exiting the method.

Example:

public StringBuffer Answer = new StringBuffer();

public synchronized String getAnswer() {
        synchronized(Answer) {
            return Answer.toString();
            // Clear Anwser here?
        }
}

EDIT

Example 2: With Try and Finaly block:

public synchronized String getAnswer() {
        synchronized(Answer) {
            try{
                return Answer.toString();
            }finally{
                Answer.delete(0, Answer.length());
            }
        }
    }

Solution

  • Yes of course, simply create a temporary variable holding the string you want to return.

    public StringBuffer answer = new StringBuffer();
    
    public synchronized String getAnswer() {
            synchronized(answer) {
                String returnValue = answer.toString();
                answer.setLength(0); // clear the buffer.
                return returnValue;
            }
    }
    

    Notice that I changed Answer to answer. It is a common convention in most programming languages that variables start with a lowercase character.

    Also consider using a StringBuilder, it is not synchronized which makes it a bit faster than StringBuffer.