stringbuilder remove the last character code example

Example 1: how to delete last char from stringbuilder

if(sb.length() > 0){
    sb.deleteCharAt(sb.length() - 1);
}

Example 2: stringBuilder delete last character

public class StringBuilderRemoveLastCharacterExample {
 
    public static void main(String[] args) {
        
        //creates an empty StringBuilder object
        StringBuilder sbld = new StringBuilder();
        
        int[] numbers = {1, 2, 3, 4, 5};
        
        for(int number : numbers){
            sbld.append(number).append(",");
        }
        
        System.out.println("StringBuilder contains: " + sbld);
        
        /*
         * To remove last character from StringBuilder, use
         * the deleteCharAt method
         */
        
        //always make sure to check the length to avoid exception
        if( sbld.length() > 0 )
            sbld.deleteCharAt( sbld.length() - 1 );
        
        System.out.println("StringBuilder contains: " + sbld);
    }
}

Tags:

Java Example