What will be the ouput of the following code snippet? StringBuffer myBuffer = new StringBuffer("Java Programming"); myBuffer.setLength(12); System.out.println(myBuffer);
Reveal answer
Fill a bubble to check yourself
What will be the ouput of the following code snippet? StringBuffer myBuffer = new StringBuffer("Java Programming"); myBuffer.setLength(12); System.out.println(myBuffer);
Java Programming
Compile time error
Throws exception
Java Program
The setLength() method truncates the StringBuffer content to the specified length. "Java Programming" has 16 characters, but setLength(12) keeps only the first 12 characters: "Java Program". The remaining 4 characters "ming" are discarded.
To answer this question, let's go through each line of the code snippet:
StringBuffer myBuffer = new StringBuffer("Java Programming");
This line creates a StringBuffer object named myBuffer and initializes it with the string "Java Programming".
myBuffer.setLength(12);
This line sets the length of the myBuffer StringBuffer object to 12. This means that the StringBuffer will only contain the first 12 characters of the original string "Java Programming".
System.out.println(myBuffer);
This line prints the myBuffer StringBuffer object. Since the length of myBuffer was set to 12, it will only contain the first 12 characters of the original string "Java Programming".
Therefore, the output of the code snippet will be:
D. Java Program
The correct answer is D.