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


Correct Option: D

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.

Find more quizzes: