Page 1 of 1

About Question enthuware.ocajp.i.v8.2.1445 :

Posted: Wed Jan 11, 2017 11:13 am
by vlezz94
Hi Paul!

I have a little doubt in the following question:
Assuming that the following method will always be called with a phone number in the format ddd-ddd-dddd (where d stands for a digit), what can be inserted at //1 so that it will return a String containing "xxx-xxx-"+dddd, where dddd represents the same four digits in the original number?

Code: Select all

public static String hidePhone(String fullPhoneNumber){ 
  //1 Insert code here }
This option is marked as correct:

Code: Select all

return new StringBuilder("xxx-xxx-")+fullPhoneNumber.substring(8); 
Can I just assume that substring returns an String and that's why the hidePhone method it's accepting it?

Because at first I thought that it would throw an exception, because you can't pass an StringBuilder to a method that is asking for a String.

Re: About Question enthuware.ocajp.i.v8.2.1445 :

Posted: Wed Jan 11, 2017 12:02 pm
by admin
Yes, fullPhoneNumber.substring(8) returns a String. The + operator basically just converts the other object to String (using that object's toString method) if one operator is already a String.

HTH,
Paul.

Re: About Question enthuware.ocajp.i.v8.2.1445 :

Posted: Fri Dec 15, 2017 7:17 pm
by Rinkesh
Hi Paul,just a request that please try to add examples to explanation if possible for StringBuilder Methods!

Re: About Question enthuware.ocajp.i.v8.2.1445 :

Posted: Fri Dec 15, 2017 9:26 pm
by admin
Sure, will add more examples. But one example is already there in the option new StringBuilder("xxx-xxx-")+fullPhoneNumber.substring(8); Here the first operand is not a String and the second operand is a String. So the non-string operand is converted to String using its toString method and then concatenated with the string operand.

String concatenation is covered in other questions as well, where you will see many more examples.

Re: About Question enthuware.ocajp.i.v8.2.1445 :

Posted: Sun Jun 13, 2021 3:21 am
by baichen7788
Hi
Is CharSequence same as String ?

Re: About Question enthuware.ocajp.i.v8.2.1445 :

Posted: Sun Jun 13, 2021 7:48 am
by admin
No, CharSequence is not the same as String. CharSequence is an interface. String, StringBuilder, and StringBuffer implement it. Please see this:
https://docs.oracle.com/javase/8/docs/a ... uence.html