Solved

java challenge string builder

Posted on 2014-11-14
19
336 Views
Last Modified: 2014-12-05
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
0
Comment
Question by:gudii9
  • 7
  • 7
  • 4
  • +1
19 Comments
 
LVL 16

Assisted Solution

by:krakatoa
krakatoa earned 167 total points
ID: 40442513
Again, all you really need here is :

public String left2(String str) {
        return str.substring(2,str.length())+str.substring(0,2);
}

Open in new window

0
 
LVL 84

Expert Comment

by:ozo
ID: 40442539
Much like you did in http:Q_28562068.html
0
 
LVL 31

Accepted Solution

by:
awking00 earned 166 total points
ID: 40444448
While a String object is immutable (i.e. can not be changed), a StringBuilder object is not and can easily be created from and converted to a String object. As such, its application can be very useful for the manipulation of Strings. Take a look at this code - only two lines to return the correct string
      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();
      }
0
 
LVL 7

Author Comment

by:gudii9
ID: 40458895
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

0
 
LVL 84

Expert Comment

by:ozo
ID: 40458995
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);
     }
0
 
LVL 31

Expert Comment

by:awking00
ID: 40459495
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
0
 
LVL 7

Author Comment

by:gudii9
ID: 40467787
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)
0
 
LVL 84

Expert Comment

by:ozo
ID: 40468372
sb has changed.
str has not changed.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40469807
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
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 84

Expert Comment

by:ozo
ID: 40469820
return sb.toString();
   uses sb, and does not mention str
   if it  was
str=sb.toString();
   then str could have been replaced
0
 
LVL 31

Expert Comment

by:awking00
ID: 40470364
>>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.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40470415
String objects are immutable.  String references, however, are mutable.
Here, str is a reference and you can replace str with sb.toString().
0
 
LVL 31

Expert Comment

by:awking00
ID: 40470514
ozo,
I absolutely agree and shame on me for not recognizing that str is a reference in this case.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40470537
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.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40470544
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
0
 
LVL 84

Expert Comment

by:ozo
ID: 40472481
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.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40472718
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
0
 
LVL 7

Author Comment

by:gudii9
ID: 40482834
StringBuilder sb = new StringBuilder("abcd");

can you create string builder above as above? please advise
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 167 total points
ID: 40482893
Yes you can, as you can discover by trying it.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now