Return a String in Java

Rashmi Patidar Dec 21, 2022 Jul 24, 2021
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 Patidar avatar Rashmi Patidar avatar

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.


Related Article - Java String