Java — Practice Question & Explanation | Code Factory

String s1 = "A";
s1 = s1.concat("B"); // s1 = AB
String s2 = "C";
s1 = s1.concat(s2); // s1 = ABC
s1.replace("C", "D"); // GC because no reference variable
s1 = s1.concat(s2); // s1 = ABCC
System.out.println(s1); // ABCC
String str = "   ";
str.trim();
System.out.println(str.equals("") + " : " + str.isEmpty()); // false : false
String s = "Code Factory";
int len = s.trim().length();
System.out.println(len); // 12
StringBuilder sb = new StringBuilder(5);
String s = "";
if(sb.equals(s)) {
System.out.println("Match1");
} else if(sb.toString().equals(s.toString())) {
System.out.println("Match2"); // ✓
} else {
System.out.println("No Match");
}
StringBuilder sb = new StringBuilder("Code");
String str1 = sb.toString();
// Insert code here
System.out.println(str1 == str2);
1. String str2 = str1; ✓
2. String str2 = new String(str1); X
3. String str2 = sb1.toString(); X
4. String str2 = "Code"; X
1. sb.deleteAll()              X no such method
2. sb.delete(0, sb.size) X no such method
3. sb.delete(0, sb.length()) ✓
4. sb.removeAll() X no such method
class MyString {
String msg;
public MyString(String msg) {
this.msg = msg;
}
}
public class StringBufferTest {
public static void main(String... args) {
System.out.println("Hello " + new StringBuilder("World"));
System.out.println("Hello " + new MyString("World"));
}
}
A.   ✓
Hello World
Hello com.example.string.MyString@<hashcode>
B. X
Hello World
Hello World
C. X
Hello java.lang.StringBuilder@<hashcode>
Hello com.example.string.MyString@<hashcode>
D. X
Compilation Fails

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store