Java — Practice Question & Explanation | Code Factory

Code Factory
2 min readMay 18, 2020

--

Index Page : Link

Donate : Link

Example 1 :

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

Example 2 :

String str = "   ";
str.trim();
System.out.println(str.equals("") + " : " + str.isEmpty()); // false : false

Example 3 :

String s = "Code Factory";
int len = s.trim().length();
System.out.println(len); // 12

Example 4 :

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");
}

Example 5 :

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

Example 6 :

- Which statement will empty the contents of a StringBuilder variable named sb?

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

Example 7 :

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"));
}
}

Options :

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

Note : String, StringBuffer, StringBuilder, Wrapper, Collection has toString() method overridden

--

--