KnowledgeBoat Logo

Computer Applications

Give the output of the following program :

class MainString
{
    public static void main(String[ ] args)
    {
        StringBuffer s = new StringBuffer("String"); 
        if((s.length( ) > 5) && 
        (s.append("Buffer").equals("X")))
        ;	// empty statement
        System.out.println(s);
    }
}

Java

Java String Handling

1 Like

Answer

StringBuffer

Working

The expression s.length( ) > 5 will result in true because the length of String s is 6 which is > 5.

In the expression s.append("Buffer".equals("X")), first the value of String s will be modified from String to StringBuffer and then it will be compared to "X". The result will be false as both the values are not equal.

Now, the condition of if statement can be solved as follows:

if((s.length( ) > 5) && (s.append("Buffer").equals("X")))
if(true && false)
if(false)

Thus, execution will move to the next statement following the if block — System.out.println(s); which will print StringBuffer on the screen.

Answered By

3 Likes


Related Questions