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);
}
}
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.
Related Questions
What will be the output of the following code snippet when combined with suitable declarations and run?
StringBuffer city = new StringBuffer("Madras"); StringBuffer string = new StringBuffer( ); string.append(new String(city)); string.insert(0, "Central "); String.out.println(string);
What will be the output for the following program segment?
String s = new String ("abc"); System.out.println(s.toUpperCase( ));
Write a program to extract a portion of a character string and print the extracted string. Assume that m characters are extracted, starting with the nth character.
Write a program to do the following :
(a) To output the question "Who is the inventor of Java" ?
(b) To accept an answer.
(c) To print out "Good" and then stop, if the answer is correct.
(d) To output the message "try again", if the answer is wrong.
(e) To display the correct answer when the answer is wrong even at the third attempt and stop.