Avatar of gudii9
gudii9
Flag for United States of America asked on

java challenge string builder

Hi,

I am working on below coding challenge
http://codingbat.com/prob/p197720
i wrote as below


public String left2(String str) {
  StringBuilder sb1=new StringBuilder();
  StringBuilder sb2=new StringBuilder();
  StringBuilder sb3=new StringBuilder();
  String result=null;
   String str1=null;
    String str2=null;
  //for(int i=0;i<str.length();i++){
  if(str.length()>=2){
  str1=str.substring(0,2);
  str2=str.substring(2,str.length());
  
  result=str2+str1;
  }
  return result;
  
  
  
  
}

Open in new window


My test cases are passing.
i would like to know how can improve on my above code. How to use string builder in this case Please advise.Thanks in advance
JavaJava EEProgramming Languages-Other

Avatar of undefined
Last Comment
ozo

8/22/2022 - Mon
SOLUTION
krakatoa

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ozo

Much like you did in http:Q_28562068.html
ASKER CERTIFIED SOLUTION
awking00

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
gudii9

ASKER
While a String object is immutable (i.e. can not be changed), a StringBuilder object is not

I have not clearly understood this immutability. To me both below solutions seems same. Please advise which one to use in which case.

stringbuilder solution
      public static String left2(String str) {
            //create StringBuilder object from str
            StringBuilder sb = new StringBuilder(str);
            //return a String starting with the third character
            //after adding first 2 characters to the end
            return sb.append(sb.substring(0, 2)).substring(2).toString();
      }

Open in new window


string example
      public static String left2(String str) {
            //create StringBuilder object from str
            StringBuilder sb = new StringBuilder(str);
            //return a String starting with the third character
            //after adding first 2 characters to the end
            return sb.append(sb.substring(0, 2)).substring(2).toString();
      }

Open in new window

ozo

those are identical stringbuilder solutions
an equivalent string example might be
     public static String left2(String str) {
            return (str + str.substring(0, 2)).substring(2);
     }
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
awking00

To help you understand the immutability of String objects vs. StringBuilder objects, look at the following two pieces of code that accomplish the same thing. I have broken the code down into intermediate steps so you can see how the String object does not change, but the StringBuilder object does.

String example (using ozo's example)

String str = "abcde";
String newString = str + str.substring(0,2); ==> This is a new string equal to "abcdeab"
String result = newString.substring(2); ==> This is a new string equal to "cdeab"
System.out.println(str); ==> This will print "abcde" as the original String str did not (and can not) change

StringBuilder example

String str = "abcde";
StringBuilder sb = new StringBuilder(str); ==> at this point sb.toString produces "abcde"
sb.append(str.substring(0,2); ==> at this point sb.toString produces "abcdeab" (i.e. sb has changed)
sb.substring(2); ==> at this point sb.toString produces "cdeab" (i.e. sb has changed again)
return sb.toString ==> converts sb back to a new String
System.out.println(str); ==> This will print "abcde" as the original String str can not change
gudii9

ASKER
System.out.println(str); ==> This will print "abcde" as the original String str did not (and can not) change
in case of string str did not change as above


in case of string builder it changed in every step on sb right without need of creating new object.

But i wonder how it printed "abcde" in last step as below



return sb.toString ==> converts sb back to a new String
System.out.println(str); ==> This will print "abcde" as the original String str can not change




I thought it will print "cdeab"  as that is last operation on sb

sb.substring(2); ==> at this point sb.toString produces "cdeab" (i.e. sb has changed again)
ozo

sb has changed.
str has not changed.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
gudii9

ASKER
return sb.toString ==> converts sb back to a new String
System.out.println(str); ==> This will print "abcde" as the original String str can not change

above is not clear to me. How the changed sb did not reflect in str when we did sb.toString

please advise
ozo

return sb.toString();
   uses sb, and does not mention str
   if it  was
str=sb.toString();
   then str could have been replaced
awking00

>>above is not clear to me. How the changed sb did not reflect in str when we did sb.toString<<
I keep telling you a String object can NOT be changed. You can return sb.toString(), which is a new String, but you can not replace str with sb.toString() as it already has the value of "abcde" (or whatever is passed in as the String parameter) and always will.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ozo

String objects are immutable.  String references, however, are mutable.
Here, str is a reference and you can replace str with sb.toString().
awking00

ozo,
I absolutely agree and shame on me for not recognizing that str is a reference in this case.
gudii9

ASKER
To help you understand the immutability of String objects vs. StringBuilder objects, look at the following two pieces of code that accomplish the same thing. I have broken the code down into intermediate steps so you can see how the String object does not change, but the StringBuilder object does.

String example (using ozo's example)

String str = "abcde";
String newString = str + str.substring(0,2); ==> This is a new string equal to "abcdeab"
String result = newString.substring(2); ==> This is a new string equal to "cdeab"
System.out.println(str); ==> This will print "abcde" as the original String str did not (and can not) change

StringBuilder example

String str = "abcde";
StringBuilder sb = new StringBuilder(str); ==> at this point sb.toString produces "abcde"
sb.append(str.substring(0,2); ==> at this point sb.toString produces "abcdeab" (i.e. sb has changed)
sb.substring(2); ==> at this point sb.toString produces "cdeab" (i.e. sb has changed again)
return sb.toString ==> converts sb back to a new String
System.out.println(str); ==> This will print "abcde" as the original String str can not change

i am confused. Can you please make the necessary correction in above comment and re post so that i will read and re read to understand.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
gudii9

ASKER
what is meaning of string references are mutable?
I think i got what it mean mean by strings are immutable based on below statements
String str = "abcde";
String newString = str + str.substring(0,2); ==> This is a new string equal to "abcdeab"
String result = newString.substring(2); ==> This is a new string equal to "cdeab"
System.out.println(str); ==> This will print "abcde" as the original String str did not (and can not) change

so basically to change/modify/append string object only way is to create new sting reference objects like str, newStrign, result etc.

Please advise
ozo

When you say
String newString = str + str.substring(0,2);
the result is a placed in a new String object which is designated as newString

When you say
str = str + str.substring(0,2);
the result placed in a newly created String object which then replaces the previous str

When you say
sb.append(str.substring(0,2);
the previously existing StringBuilder object is altered and no new object is created.
gudii9

ASKER
When it replaces the previous str then previous str still remains hanging there right.
When you say sb.append......then it should be assigned to other sb eight.
Please advise
Your help has saved me hundreds of hours of internet surfing.
fblack61
gudii9

ASKER
StringBuilder sb = new StringBuilder("abcd");

can you create string builder above as above? please advise
SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.