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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Linux VS Window

README? But Why?

The Ultimate guide to Flutter Integration Testing

Saving and Loading in Unity part 2

rk-boot/v2: A clean way of prometheus monitoring in Golang

Implementing background upload queue with Swift

android gif

Design Pattern Proxy, in a nutshell

What are the Scrum Master’s Roles and Responsibilities?

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
Code Factory

Code Factory

More from Medium

DST In Programs and How To Handle It In Java

Not so soft skills

TechnoSpective (Technical Retrospective)

Impostor syndrome: How to fix it.