Java-Set Length

Set Length

We shall use the setLength( ) method to explicitly set the length of an object of the StringBuffer class. If we set the length of a string in such a way that this length is less than the actual length of the string, then the characters stored after the new length will be lost. For example, in the following program, the new length of the StringBuffer str is set as ‘4’, all the characters stored after this position (i.e. PROGRAM ) will be lost. As a result, the output statement will display only the string “Java”.

Program

vcvcv

Program Source

public class Javaapp {
    
    public static void main(String[] args) {
        
        StringBuffer str = new StringBuffer();
        str.append("JAVA PROGRAM");
        str.setLength(4);
        System.out.println("str content : "+str);
    }
}

Leave a Comment