-13

Can anyone please tell me how I can use if-else condition with StringBuffer to check if it is empty?

I am expecting something like this

if (Stringbuffer is empty){ 
    // some condition 
}
else {
   // some other condition
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Aman Shukla
  • 53
  • 1
  • 1
  • 3

2 Answers2

22

StringBuffer.length():

[returns] the length of the sequence of characters currently represented by this object

so you can use the fact that StringBuffer.length() returns zero (or not) to check if the buffer is empty (or not).


Note that you should probably be using StringBuilder instead of StringBuffer. From the Javadoc of StringBuffer:

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0
StringBuffer buffer = null;

if(buffer == null || buffer.length() == 0){
     // some condition 
}else{
     // some other condition 
}
SkrewEverything
  • 2,393
  • 1
  • 19
  • 50
  • 1
    At least with Java 16, you don't need to check if the StringBuffer == null, that will always be false, even if the buffer is empty. Just doing `if(buffer.length() == 0){` is enough. – K. Frank Jun 07 '21 at 02:58