Solved

string multiple times

Posted on 2014-10-10
12
197 Views
Last Modified: 2014-10-12
Hi,

I am trying below challenge
http://codingbat.com/prob/p142270


I wrote code as below

public String stringTimes(String str, int n) {
  if(n>0){
 
  String str1=n*str;
  return str1;
  }
}


How to fix my code. Please advise
0
Comment
Question by:gudii9
12 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 40374011
String str1=n*str;

Open in new window

Makes no sense. What do you mean by it?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 300 total points
ID: 40374013
Try

public String stringTimes(String str, int n) {
   StringBuilder sb = new StringBuilder(str.length()*n);
   for(int i = 0;i<n;i++) {
      sb.append(str);
   }
   return sb.toString();
}

Open in new window

As i've mentioned to you many times before - avoid string concatenation
0
 
LVL 21

Expert Comment

by:Amitkumar Panchal
ID: 40374430
Agree with CEHJ. Provided one is the simplest way solve the challenge.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40374472
avoid string concatenation
Why?
What do you gain by doing StringBuilder concatenation instead?
0
 
LVL 26

Assisted Solution

by:dpearson
dpearson earned 200 total points
ID: 40374476
I think CEHJ is pointing out using StringBuilder would be better than concatenation like this:

public String stringTimes(String str, int n) {
   String result = "" ;
   for(int i = 0;i<n;i++) {
       result += str ;
   }
   return result ;
}

Open in new window


which is inefficient because "result += str" requires allocating a a new sting and copying over the old string each time (unless the compiler is kind enough to rewrite this for you).

Doug
0
 
LVL 84

Expert Comment

by:ozo
ID: 40374503
Is efficiency the point of this exercise?  
If so, how much efficiency gain is there?
If the compiler reallocates in powers of 2, both methods would be linear in n.
What kinds of n values would we be using this on, and how much extra time are we talking about for the different methods?
How important is it to optimize that time in this application?
If you are that concerned about efficiency, should you even be writing this in Java?
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 86

Expert Comment

by:CEHJ
ID: 40374537
Is efficiency the point of this exercise?  
The point of the exercise (one hopes) is to get better at programming. Getting better about programming is about doing things in the right, efficient way, not just about doing any old thing that works. If you don't understand why string concatenation can be inefficient, then inspect the bytecode
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 40374540
If you are that concerned about efficiency, should you even be writing this in Java?
It's exactly that kind of attitude that makes programmers who can't be bothered with efficiency think "I'm writing this in Java so i don't need to bother about memory or anything really, right?" Wrong.

Result? People saying "Java's just bloated and slow"
0
 
LVL 84

Expert Comment

by:ozo
ID: 40374686
I would not want to suggest that efficiency concern are unimportant.
I could want to suggest that efficiency concerns are balanced among many other programming concerns
and that one should be cognizant of what concerns are driving particular decisions.
A blanket statement to avoid string concatenation, without without building an understanding
of what trade offs one is making, and why and when those should be of concern,
does not seem to be an effective way to get better at programming, especially when one is just staring to absorb the elements of programming.
Judging from the kinds of questions that have been asked so far, to expect the asker of this question to be able to understand why string concatenation can be inefficient by inspecting the bytecode, at this stage in their learning, seems unrealistic.
0
 
LVL 7

Author Comment

by:gudii9
ID: 40375096
I would like to know how to see bytecode. I will start a new question on that as that is separate topic
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 40375536
Judging from the kinds of questions that have been asked so far, to expect the asker of this question to be able to understand why string concatenation can be inefficient by inspecting the bytecode, at this stage in their learning, seems unrealistic.
I know what you're getting at, but my rejoinder would be that if the theory and facts behind what happens in string concatenation are a little complex (and you could be right about that) then a policy of learning by rote and taking on trust (pro tem) the rule 'avoid string concatenation' is probably a good one.
0
 
LVL 84

Expert Comment

by:ozo
ID: 40375652
I can see the usefulness of shortcuts like rote learning for getting quick solutions to problems that may be difficult to work out more completely.
We all use shortcuts all the time.  While they may not be the best in all situations, they do enable us to use our finite cognitive capacity to deal with so many circumstances we face every day.

But my general take is that I prefer trying to build more skills for evaluating situations, which may allow one to develop ones own set of shortcut rules, which could then be better applied in situations where a fixed set of rote rules may not have appropriately anticipated.
When there is potential for problems to be complex, as programming problems, and optimization problems can be,
then a policy of preferring understanding over rote trust seems to me to be a good one.
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
groupSum6 challenge 6 76
Java. Convert method from recursion based to iteration based ( loop based ) 6 75
C# code editing and collaboration 3 98
varialbe initialization 11 30
How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

911 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

19 Experts available now in Live!

Get 1:1 Help Now