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:
- Without using a return statement
- Using a return statement
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.
Syntax
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:
Output
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:
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:
sMethod();
}
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.
Syntax
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:
return "The String is returned by using Return Statement";
}
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:
String s= sMethod();
System.out.println(s);
}
Output
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.