{{announcement.body}}
{{announcement.title}}

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

DZone 's Guide to

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

Is char[ ], String, StringBuffer, or StringBuilder the best way to take and return String data in Java? Take a look at this comparison.

· Java Zone ·
Free Resource

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.

Java
 




x
35


 
1
import java.util.Scanner;
2
 
          
3
public class ReverseString {
4
 
          
5
  public static void main(String[] args) {
6
 
          
7
    // take input
8
    Scanner scan = new Scanner(System.in);
9
    System.out.print("Enter string: "); 
10
    String str = scan.nextLine();
11
 
          
12
    // reverse the string
13
    String reverseStr = reverseStringData(str);
14
 
          
15
    // display result string
16
    System.out.println( "Reverse String: " +
17
                           reverseStr);
18
  }
19
 
          
20
  public static String reverseStringData(String s) {
21
 
          
22
    String rev = new String();
23
 
          
24
    for(int i=s.length()-1; i>=0; i--){
25
      rev = rev + s.charAt(i);
26
 
          
27
      // On every iteration new string
28
      // object will be created
29
      System.out.println("Address of rev: "+
30
                  System.identityHashCode(rev));
31
    }
32
 
          
33
    return rev;
34
  }
35
}


Output:

Plain Text
 




xxxxxxxxxx
1


 
1
Enter string: Hello
2
Address of rev: 531885035
3
Address of rev: 1044036744
4
Address of rev: 1826771953
5
Address of rev: 1406718218
6
Address of rev: 245257410
7
Reverse String: olleH


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.

Java
 




xxxxxxxxxx
1
39


 
1
import java.util.Scanner;
2
 
          
3
public class ReverseString {
4
 
          
5
  public static void main(String[] args) {
6
 
          
7
    // take input
8
    Scanner scan = new Scanner(System.in);
9
    System.out.print("Enter string: ");
10
    String str = scan.nextLine();
11
 
          
12
    // The reverseStringData() takes StringBuilder
13
    // objects we need to convert
14
    // string into StringBuilder
15
    StringBuilder sb = new StringBuilder(str);
16
 
          
17
    // Now, the return type is also StringBuilder
18
    // So, create new StringBuilder class object to
19
    // receive the return value
20
    StringBuilder reversrSb = reverseStringData(sb);
21
 
          
22
    // find reverse
23
    String reverseStr = new String(reversrSb);
24
 
          
25
    // display result
26
    System.out.println("Reverse String: "+reverseStr);
27
  }
28
 
          
29
  public static StringBuilder reverseStringData(StringBuilder sb){
30
    StringBuilder rev = new StringBuilder("");
31
    for(int i=sb.length()-1; i>=0; i--){
32
      rev.append(sb.charAt(i));
33
 
          
34
      System.out.println("Address of rev: "+
35
                    System.identityHashCode(rev));
36
    }
37
    return rev;
38
  }
39
}


Output:

Plain Text
 




xxxxxxxxxx
1


 
1
Enter string: Hello
2
Address of rev: 980546781
3
Address of rev: 980546781
4
Address of rev: 980546781
5
Address of rev: 980546781
6
Address of rev: 980546781
7
Reverse String: olleH


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.

Java
 




xxxxxxxxxx
1
38


 
1
import java.util.Scanner;
2
 
          
3
public class ReverseString {
4
 
          
5
  public static void main(String[] args) {
6
 
          
7
    // take input    Scanner scan = new Scanner(System.in);
8
    System.out.print("Enter string: ");
9
    String str = scan.nextLine();
10
 
          
11
    // The reverseStringData() takes StringBuffer
12
    // object so converting string into StringBuffer
13
    StringBuffer sb = new StringBuffer(str);
14
 
          
15
    // Now, the return type is also StringBuffer
16
    // So, create new StringBuffer class object
17
    // to receive the return value
18
    StringBuffer reversrSb = reverseStringData(sb);
19
 
          
20
    // find reverse
21
    String reverseStr = new String(reversrSb);
22
 
          
23
    // display result
24
    System.out.println("Reverse String: "+reverseStr);
25
  }
26
 
          
27
  public static StringBuffer reverseStringData(StringBuffer sb){
28
 
          
29
    StringBuffer rev = new StringBuffer("");
30
    for(int i=sb.length()-1; i>=0; i--){
31
      rev.append(sb.charAt(i));
32
      System.out.println("Address of rev: " +
33
               System.identityHashCode(rev));
34
    }
35
    return rev;
36
  }
37
}
38
 
          


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:-

  • toString()
  • valueOf()
  • String(StringBuilder)

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

Java
 




xxxxxxxxxx
1
37


 
1
import java.util.Scanner;
2
 
          
3
public class ReverseString {
4
 
          
5
  public static void main(String[] args) {
6
 
          
7
    // take input
8
    Scanner scan = new Scanner(System.in);
9
    System.out.print("Enter string: ");
10
    String str = scan.nextLine();
11
 
          
12
    // find reverse
13
    String reverseStr = reverseStringData(str);
14
 
          
15
    // display result
16
    System.out.println("Reverse String: " +
17
                               reverseStr);
18
  }
19
  public static String reverseStringData(String sb){
20
 
          
21
    // Converting string class object to
22
    // StringBuilder class object
23
    StringBuilder rev = new StringBuilder("");
24
 
          
25
    // iterate loop
26
    for(int i=sb.length()-1; i>=0; i--){
27
      rev.append(sb.charAt(i));
28
      System.out.println("Address of rev: "+
29
                      System.identityHashCode(rev));
30
    }
31
 
          
32
    // converting stringBuilder class object
33
    //  to string class object
34
    // and returning it to caller method
35
    return rev.toString();
36
  }
37
}


Enter string: Hello

Plain Text
 




xxxxxxxxxx
1


 
1
Address of rev: 980546781
2
Address of rev: 980546781
3
Address of rev: 980546781
4
Address of rev: 980546781
5
Address of rev: 980546781
6
Reverse String: olleH


Topics:
char, java, java string, java string tutorial, java stringbuffer, java stringbuilder, java strings

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}