#Override
public String toString() {
int currentSpeed = getSpeed();
int currentGear = getGear();
StringBuffer sb = new StringBuffer("Transmission (speed = ");
sb = sb.append(currentSpeed).append(", gear = ").append(currentGear).append(")");
return sb.toString();
}
I'm confused how to convert the StringBuffer object I created back to a string format.
Since I'm calling toString() method to convert it back, I'm not sure if this will trigger the build in toString() method or else be a recursive call to the function itself?
Related
I am writing a short Java script to where I have a name in String as a variable. I want to write get method to get initials and return them for later use. That method works well when printing out the initials, but not when wanting to return that value.
//method for getting initials of the name
public String getInitials() {
String words[] = competitorName.split(" ");
for(String word : words) {
return word.charAt(0) + " ";
}
}
It shows me that the method must return a result of type String but that should already be it. And does not work even when I am adding toString methods (then it writes that it is already String)
You almost got it! Just use StringBuilder and return result
public String getInitials() {
String words[] = competitorName.split(" ");
StringBuilder builder = new StringBuilder();
for(String word : words) {
builder.append(word.charAt(0));
}
return builder.toString();
}
I understand that the purpose of StringBuilder (usually) is to avoid creating objects over and over in Java when iterating over strings, especially in a loop.
I'm wondering if it's worth it to use it in a recursive function that returns a string. In other words, which of the following is more efficient?
public String recursive(int n) {
String retStr = "s";
if (n==0) {
return retStr;
}
else {
return retStr + recursive(n-1);
}
}
or
public String recursive(int n) {
String retStr = "s";
StringBuilder sb = new StringBuilder();
if (n==0) {
return retStr;
}
else {
return sb.append(retStr).append(recursive(n-1)).toString();
}
}
If I had to guess, the first one seems less complex, because either way you have to create a new object, be it a String or a StringBuilder, every time, but I could be wrong.
You can add StringBuilder to recursive method:
public String recursive(int n, StringBuilder sb) {
String retStr = "s";
if (n==0) {
return retStr;
}
else {
return sb.append(retStr).append(recursive(n-1, sb)).toString();
}
}
and call it
recursive(100, new StringBuilder());
if you are using java 8,
Since variables are in scope I think there is no need for StringBuilder.
In summary, Java 8 seems not to introduce new optimizations for String
concatenation with the + operator. It means that using StringBuilder
manually is still required for specific cases where the compiler or
the JIT is not applying magic tricks. For instance, when lot of
substrings are concatenated to a String variable defined outside the
scope of a loop.
See more in pellegrino
and dzone
User7294900's idea to pass the StringBuilder is fine, but he is adding much too much.
public String recursive (int n, StringBuilder sb) {
String retStr = "s";
if (n==0) {
return sb.toString ();
}
else {
return recursive (n-1, sb.append (retStr));
}
}
And - you should look this up, I'm unsure - doesn't the StringBuilder take hints, how big it will grow?
recursive (100, new StringBuilder (101));
Not able to print the toString method, would like to be able to print the accessor and am not sure what the issue is. Am I not storing the array as an instance properly? I'd like to access the array in future methods so it is important for it to be stored as an instance.
public class j {
private double[] s;
public j() throws FileNotFoundException {
File in = new File("file.txt");
Scanner inScanFile = new Scanner(in);
int lines = inScanFile.nextInt();
s = new double[lines];
}
public double getXintercept(){
return s[2];
}
public String toString() {
double c = getXintercept();
System.out.println(c);
String descrip = "";
descrip = "kiki" + c; //want this to display and it won't
return descrip;
}
}
Create the object of this class in main method and then print the object using
System.out.println(yourobject);
Below is my toString() method in which I am trying to invoke another toString() from a different class called Tree. I am trying to return each part of an ArrayList and format it into my toString() from my Tree class, then put it all into the "result" String.
So far, all my method does is go through the list and return nothing. How do I make it so it essentially puts the entire list into the result string, under the format of my toString() from my Tree class?
public String toString(){
String result;
int i = 0;
while(i < listOfTrees.size()){
listOfTrees.get(i);
i++;
}
Use a StringBuilder :
public String toString(){
StringBuilder result = new StringBuilder();
int i = 0;
while(i < listOfTrees.size()){
result.append(listOfTrees.get(i) + " "); // this would use the toString
// method of the type contained
// in this List
i++;
}
return result.toString();
}
You need to use a StringBuilder. Get each String append it to the builder and then return the final String produced by it
public String toString(){
StringBuilder str= new StringBuilder();
for(int i = 0; i < listOfTrees.size(); i++){
str.append(listOfTrees.get(i));
}
return str.toString();
}
The other way to do it is to initialize result with an empty String literal to start with and then use the + operator to add other Strings to it, but this is awfully inefficient as Strings are immutable and each time you add a String that way, you create a whole new object.
I am working with a program in which I need to use a method call to return a String from an int array. This is what I have of the method so far (I am required to use a method with this header and parameters)
public String toString()
{
for (int i=0;i<NUM_POCKETS;i++)
{
this.getPocketCount(i);
}
}
I basically need the loop to go through all of my "pockets" (array items) and return the stored values into a String to be returned.
I could be missing something very obvious, but for the life of me I do not understand how this information would be stored and returned to the Driver as a String. I know the loop logic is there, but how do I store each increment of i into a String as the loop progresses?
Thanks in advance for any help!
"I am working with a program in which I need to use a method call to return a String from an int array."
If this isn't a homework problem, you can simply use Arrays.toString(int[] array).
String myString = Arrays.toString(myIntArray);
Otherwise, maybe you can do something like this:
String getStringFromIntArray(int[] array) {
StringBuilder builder = new StringBuilder();
for (int num : array)
builder.append(num)
return builder.toString();
}
Try looking into the StringBuilder class. The specification for Java 6 is here.
http://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
You would need a StringBuilder object and just append the value to the object using the .append() function.
as long as this.getPocketCount(i); gives you the value of the array on position i:
public String toString() {
String returnstring= ""; //init empty string
for (int i = 0; i < NUM_POCKETS; i++) {
returnstring += this.getPocketCount(i)+" "; //append(concat) to string
}
returnstring = returnstring.substring(0, returnstring.length()-1); //remove the last " "
return returnstring; //return string
}
the + sign appends the next string
"Hello"+" "+"World" becomes "Hello World"
Edit:
public String toString() {
String returnstring= ""; //init empty string
for (int i = 0; i < NUM_POCKETS-1; i++) { //-1 to place last later
returnstring += this.getPocketCount(i)+" "; //append to string
}
returnstring += this.getPocketCount(NUM_POCKETS-1) //append the last value
return returnstring; //return string
}
Assuming you specifically want to build your String from within the loop, you could use a StringBuilder. It is more verbose than the one-liner offered by Arrays.toString(), but you asked for it:
e.g.
public String toString() {
StringBuilder sb = new StringBuilder(NUM_POCKETS);
for (int i = 0; i < NUM_POCKETS; i++) {
sb.append(this.getPocketCount(i));
}
return sb.toString();
}
Using a StringBuilder within a loop is faster than performing concatenation of each individual element. See: when to use StringBuilder in java