Multiple choice technology programming languages

What will be the ouput of the following code snippet? StringBuffer myBuffer = new StringBuffer("Java Programming"); myBuffer.setLength(12); System.out.println(myBuffer);

  1. Java Programming

  2. Compile time error

  3. Throws exception

  4. Java Program

Reveal answer Fill a bubble to check yourself
D Correct answer
Explanation

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.

AI explanation

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.