Java stringbuilder return string

How to Define Method to Take and Return String Data in Java

Join the DZone community and get the full member experience.

In Java, char[] , String , StringBuffer , and StringBuilder are used to store, take, and return string data. One question that may come to your mind is, «What is the best way for defining a method to take string data and return string data in Java?»

We have four ways to take and return string data:
1) char [] /byte []
2) String
3) StringBuilder
4) StringBuffer

The char[] is not a better option because it works on an array. Taking and returning string data using char[] is not a better option.

The second way is by using String class. The String class is immutable. On every modification, it creates a new object. In this way, we are creating many new objects which are not actually required for our program. So, it is not recommended to only work with the String class.

This Java program to reverse String shows that, for a small task that is for reversing “Hello” it creates five objects.

public class ReverseString 
 public static void main(String[] args) 
 Scanner scan = new Scanner(System.in);
 System.out.print("Enter string: "); 
 String reverseStr = reverseStringData(str);
 System.out.println( "Reverse String: " +
 public static String reverseStringData(String s) 
 // On every iteration new string
 System.out.println("Address of rev: "+
 System.identityHashCode(rev));
Address of rev: 1044036744
Address of rev: 1826771953
Address of rev: 1406718218

For big tasks, it will create so many string class objects, which actually aren’t needed in the program. In this way, we are wasting memory.

Using Only StringBuilder To Take and Return String Data

The third way is by using the StringBuilder class. The StringBuilder class is mutable. On every modification, it doesn’t create a new object, but it stores it in the same object. But the problem comes here: since we are using StringBuilder to take an argument, the caller method should pass the value in the StringBuilder form. Again, we are returning the string data using StringBuilder due to this the caller method should store returning value as StringBuilder .

The caller method developer needs to create a new StringBuilder object and convert the string data to StringBuilder just because, the called method taking argument is in StringBuilder form not in the String form. Similarly, they need to create a StringBuilder object just because the called method is returning the string data as StringBuilder .

public class ReverseString 
 public static void main(String[] args) 
 Scanner scan = new Scanner(System.in);
 System.out.print("Enter string: ");
 // The reverseStringData() takes StringBuilder
 // objects we need to convert
 // string into StringBuilder
 StringBuilder sb = new StringBuilder(str);
 // Now, the return type is also StringBuilder
 // So, create new StringBuilder class object to
 StringBuilder reversrSb = reverseStringData(sb);
 String reverseStr = new String(reversrSb);
 System.out.println("Reverse String: "+reverseStr);
 public static StringBuilder reverseStringData(StringBuilder sb)
 StringBuilder rev = new StringBuilder("");
 System.out.println("Address of rev: "+
 System.identityHashCode(rev));

It doesn’t create a new StringBuilder object, so no memory is wasted but inside the caller method we need to write some extra logics for converting the string to StringBuilder and later StringBuilder to a string. So, it is also not the recommended way. We should simplify this things.

Using Only StringBuffer to Take and Return String Data in Java

The fourth way is by using the StringBuffer class. The StringBuffer class is similar to the StringBuilder class. In implementation no different will be there. StringBuffer class is synchronized so it is better for a multi-thread model application, not for the single thread model application. The StringBuffer class also will create the only object as StringBuilder, but we need to write extra logic for converting StringBuffer to String and String to StringBuffer.

public class ReverseString 
 public static void main(String[] args) 
 // take input Scanner scan = new Scanner(System.in);
 System.out.print("Enter string: ");
 // The reverseStringData() takes StringBuffer
 // object so converting string into StringBuffer
 StringBuffer sb = new StringBuffer(str);
 // Now, the return type is also StringBuffer
 // So, create new StringBuffer class object
 // to receive the return value
 StringBuffer reversrSb = reverseStringData(sb);
 String reverseStr = new String(reversrSb);
 System.out.println("Reverse String: "+reverseStr);
 public static StringBuffer reverseStringData(StringBuffer sb)
 StringBuffer rev = new StringBuffer("");
 System.out.println("Address of rev: " +
 System.identityHashCode(rev));

Enter string: Hello
Address of rev: 980546781
Address of rev: 980546781
Address of rev: 980546781
Address of rev: 980546781
Address of rev: 980546781
Reverse String: olleH

This is also not recommended.

Then how We Should Write the Method?

We should take and return the argument as a string class object. In this way, in the caller method, we don’t need to write any additional logic in the caller method.

In the method, we should convert the String class object to the the StringBuilder class, process the logic on the StringBuilder class, and then convert the StringBuilder class object to string class object and return it.

Take argument as String class object => convert String class object to StringBuilder class object => process the business logic => convert the StringBuilder class object to String class object => return String class object.

For converting String to StringBuilder class there is only one way, by using the StringBuilder(String) constructor.

For converting StringBuilder to String class object there are three ways are there:-

Among these three ways, the first ways i.e. using the toString() method is better than the remaining two.

Источник

Class StringBuilder

A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

For example, if z refers to a string builder object whose current contents are » start «, then the method call z.append(«le») would cause the string builder to contain » startle «, whereas z.insert(4, «le») would alter the string builder to contain » starlet «.

In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .

Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Источник

Java StringBuilder toString() Method

The Java StringBuilder toString() method is used to retrieve a string representing the data in a StringBuilder object. A new String object is allocated and initialized to contain the character sequence currently represented by this object.

A String in Java is an object that stores a sequence of characters. It is represented by the java.lang.string. A string is a constant, which means that we cannot change the string value once it has been initialized.

The toString() method does not accept any parameter, and it does not throw any exception while converting an object to a string.

Syntax

Following is the syntax of the Java StringBuilder toString() method −

Parameters

Return Value

This method returns a string representation of this sequence of characters.

Example

If the StringBuilder class object does not contain the null value, the toString() method represents the object in a string format.

In the following program, we are instantiating the StringBuilder class with the value “TutorialsPoint”. Using the toString() method, we are trying to retrieve the string representation of the instantiated object.

package com.tutorialspoint.StringBuilder; import java.lang.*; public class Demo < public static void main(String[] args) < //instantiating the StringBuilder class StringBuilder sb = new StringBuilder("TutorialsPoint"); System.out.println("The given string: " + sb); //using the toString() method System.out.println("The string representation of an object: " + sb.toString()); >>

Output

On executing the above program, it will produce the following result −

The given string: TutorialsPoint The string representation of an object: TutorialsPoint

Example

In the following program, we are creating an object of the StringBuilder class with the value “HelloWorld”. Then, we append some value “India” to it. Using the toString() method, we are trying to retrieve the string representation of the object.

package com.tutorialspoint.StringBuilder; import java.lang.*; public class Demo < public static void main(String[] args) < //creating an object of the StringBuilder class StringBuilder sb = new StringBuilder("HelloWorld"); System.out.println("The given string: " + sb); //append some value to it using append() method. sb.append(" India."); //using the toString() method System.out.println("The string representation of an object: " + sb.toString()); >>

Output

Following is the output of the above program −

The given string: HelloWorld The string representation of an object: HelloWorld India.

Источник

Class StringBuilder

A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

For example, if z refers to a string builder object whose current contents are » start «, then the method call z.append(«le») would cause the string builder to contain » startle «, whereas z.insert(4, «le») would alter the string builder to contain » starlet «.

In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .

Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Источник

Читайте также:  Тип элемента массива java
Оцените статью