Solved

java challenge string builder

Posted on 2014-11-14
19
344 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 32

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 32

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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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 32

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 32

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
oracle 11g 23 51
Zip Folders Using Chilkat Routines 1 17
MySQL  on Tomcat 8 30
Tomcat: Unable to run tomcat service. 2 0
Windows Script Host (WSH) has been part of Windows since Windows NT4. Windows Script Host provides architecture for building dynamic scripts that consist of a core object model, scripting hosts, and scripting engines. The key components of Window…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
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.

863 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

24 Experts available now in Live!

Get 1:1 Help Now