- How to Define Method to Take and Return String Data in Java
- Using Only StringBuilder To Take and Return String Data
- Using Only StringBuffer to Take and Return String Data in Java
- Then how We Should Write the Method?
- How to Return a String in Java
- How to Return a String in Java?
- Method 1: Return a String in Java Without Using return Statement
- Example 1: Return a String Using System.out.println() Method
- Example 2: Return a String Using Static Java Method
- Method 2: Return a String in Java Using return Statement
- Conclusion
- About the author
- Farah Batool
- Return a String in Java
- Related Article — Java 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.
How to Return a String in Java
A String is a group of characters used to store text data. In Java, methods are declared with their return types like int, double, String, and so on. More specifically, a string can be returned with or without a return statement, depending on your program requirements.
This post will illustrate how to return Java strings.
How to Return a String in Java?
There are two ways to return a String in Java:
We will now check out both of the mentioned methods one by one!
Method 1: Return a String in Java Without Using return Statement
The simplest way to return a string without the return statement is using the “System.out.println()” method. This Java method is utilized for printing the passed argument on the console.
Here, “s” represents the string that will be returned to the console.
See the examples below to have a better understanding of the concept.
Example 1: Return a String Using System.out.println() Method
First of all, create a string named “s” having the following value:
Then, we will return the created string using the “System.out.println()” method:
Example 2: Return a String Using Static Java Method
Here, first, we will create a static void function that utilizes the “System.out.println()” method:
static void sMethod ( ) {
System. out . println ( «The String is returned without Return Statement» ) ;
}
Now, we will call the “sMethod()” in main() to print the specified string on the screen:
The given output indicates that we have successfully returned a string using a static method:
Now, let’s head towards the second method!
Method 2: Return a String in Java Using return Statement
Another way to return a string is by using a “return” statement at the end of the method. When a programmer writes a program, the compiler examines the return type. If the return type is set as “String”, then the added string will be returned.
Here, the “return” keyword represents the added return statement that will return the String specified in the double quotes.
Example
In this example, we will create a String type static method that returns the following string:
Next, we will call our “sMethod()” in main() method, store the returned value in “s” variable, and print it on console using the “System.out.println()” method:
public static void main ( String [ ] args ) {
String s = sMethod ( ) ;
System. out . println ( s ) ;
}
We compiled all the simplest methods related to returning a String in Java.
Conclusion
There are two methods to return a String in Java: the “System.out.println()” method or the “return” statement. The System.out.println() method can be utilized simply in the main() method or in any user-defined static method. However, to use the return statement, you have to create a method with a “String” return type and specify the required string with the “return” keyword within the method definition. This post illustrated the methods to return a Java String.
About the author
Farah Batool
I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.
Return a String in Java
In Java, the prototype of a method must contain a return type always based on the data type specified in the declaration.
Below is the code block to explain the function of returning a string.
public class Main public static void main(String[] args) String s = doSomething(); System.out.println("Print the value from the function: " + s); > private static String doSomething() return "Hi,I am in doSomething Function"; > >
In the driver class above, there is a private function that returns a String value. The prototype of the doSomething method is also present above.
First, it has an access modifier private that tells the scope or the visibility of a function. A public or protected keyword defines visibility other than private .
The static keyword is optional; it means that the method is called without creating the driver class instance. So, the main function is always static that can be called directly without the name of the driver class.
The next value is the return type of the method; it states that the primitive data types, user-defined classes, or generic instances can be returned.
In our case, the string is the return type of the method. The compiler checks for the return type when the coder writes the program. It throws a compile-time error if the return type does not match the prototype given.
Next to it is the method’s name; it can be any name other than the pre-fixed keywords present in Java. The function name follows the set of the parameters passed.
The code block above has no parameters in the () parenthesis. But depending on our needs, we can give one or a set of parameters. Within the curly braces <> , defining the beginning and the end of the function is what’s often called a block .
There can be multiple statements present in the function block. The return statement must be the last. As the return type is a string, the return keyword is preceded with the String value present in » » double quotations.
The output of the code block is printed below.
Print the value from the function: Hi, I am in doSomething Function.
Rashmi is a professional Software Developer with hands on over varied tech stack. She has been working on Java, Springboot, Microservices, Typescript, MySQL, Graphql and more. She loves to spread knowledge via her writings. She is keen taking up new things and adopt in her career.