0

This is a block of code in one of my program. if i directly assign sb1= str2 i am getting an error. so i am creating two StringBuffer objects.

Is there any possibility to achieve below requirement using only one StringBuffer Object.

   String str1, str2;
    Scanner scanObj = new Scanner(System.in);
    str1 = scanObj.next();
    StringBuffer sb1 = new StringBuffer(str1);
    sb1.reverse();
    str1 = sb1.toString();
    char[] input1 = str1.toCharArray();
    str2 = scanObj.next();
    StringBuffer sb2 = new StringBuffer(str2);
    sb2.reverse();
    str2 = sb2.toString();
    char[] input2 = str2.toCharArray();
1
  • 3
    Unless you need thread safety, you should use StringBuilder. It was introduced in Java 5 in 2004 and is preferred to StringBuffer. Commented Jun 14, 2012 at 11:45

3 Answers 3

1

use sb.setLength(0) and then add the new string back in. This should keep the same memory allocation.

Sign up to request clarification or add additional context in comments.

Comments

0

You can write

Scanner scanObj = new Scanner(System.in);
char[] input1 = new StringBuilder(scanObj.next()).reverse().toString().toCharArray();
char[] input2 = new StringBuilder(scanObj.next()).reverse().toString().toCharArray();

You can reuse a StringBuilder by using setLength(0) and append() but it would be more complex.

2 Comments

More complex how? Your approach could cause the memory to be re-allocated.
@Thom if you were worries about memory allocations you would just use a loop over a char[] and not have any StringBuilder. Given the program is not likely to worry about anything less than a micro-second, code simplicty is more likely to be important.
0

You can not assign StringBuffer directly to String because there are different objects. This should help you:

String yourStr = "some value";
StringBuffer buffer = new String(yourStr);
StringBuffer other = buffer;

You can put any String value into the StringBuffer object constructor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.