Multiple choice

What is the output of the following Java program?

class A { public StringBuilder f1() { StringBuilder b=new StringBuilder("This is Java Program"); b.replace(8, 12, "Example Java"); return b; } } public class Test { public static void main(String[] args) { A a=new A(); System.out.println(a.f1()); } }

  1. Example Java

  2. This is Program

  3. This is Example Java Program

  4. This is Example Java

  5. None of the above

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

 StringBuilder class an API compatible but no guarentee of synchronization. It creates a string mutable sequences of characters. Now b is the object of String Builder class which creates string as show below ||||||||||||||||||||||| |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| |Sequence of characters|T|h|i|s| |i|s| | |J|a|v|a| |P|r|o|g|r|a|m| |index|0|1|2|3|4|5|6|7|8|9|10|12|13|14|15|16|17|18|19|20|21|

b.replace(8, 12, "Example Java"); // which replaces given string built from start index 8 to end index 12 with "Example Java" without effecting the remaining indexes of the string.Hence characters of string from index 8 to 12 are replaced with "Example Java". Now the string looks as show below |||||||||||||||||||||||||||||| |---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---| |Sequence of characters|T|h|i|s| |i|s| |E|x|a|m|p|l|e| |J|a|v|a| |P|r|o|g|r|a|m| |index|0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|

Hence  "This is Example Java Program" is the output of the program.