Class name as return type in Java

You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value and cannot contain a return statement. Any method that is not declared void must contain a return statement.

Let's look at the isEmpty method in the Stack class:

public boolean isEmpty() {
    if (items.size() == 0) {
        return true;
    } else {
        return false;
    }
}
The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean. The declared return type for the isEmpty method is boolean, and the implementation of the method returns the boolean value true or false, depending on the outcome of a test.

The isEmpty method returns a primitive type. A method can return a reference type. For example, Stack declares the pop method that returns the Object reference type:

public Object pop() {
    if (top == 0) {
        throw new EmptyStackException();
    }
    Object obj = items[--top];
    items[top]=null;
    return obj;
}
When a method uses a class name as its return type, such as pop does, the class of the type of the returned object must be either a subclass of or the exact class of the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number, which is in turn a subclass of Object, as illustrated in the following figure.

Class name as return type in Java

Now suppose that you have a method declared to return a Number:
public Number returnANumber() {
    ...
}
The returnANumber method can return an ImaginaryNumber but not an Object. ImaginaryNumber is a Number because it's a subclass of Number. However, an Object is not necessarily a Number — it could be a String or another type.

You also can use interface names as return types. In this case, the object returned must implement the specified interface.

Java Return Statement

Return type in Java | We know that a method is a function declared inside a class that contains a group of statements.

It is used to perform certain tasks or processing of data in the program to yield the expected results.

A method can accept data from outside and can also return the results. To return the result, a return statement is used inside a method to come out of it to the calling method.

In Java, return is a keyword that is used to exit from the method only with or without returning a value. Every method is declared with a return type in java and it is mandatory for Java methods.

Return type may be a primitive data type like int, float, double, a reference type, or void type which represents “return nothing”. i.e, they don’t give anything back.

When a method is called, the method may return a value to the caller method.

Let’s take an example program to understand the concept of java return type better.

Here, we will write a program to return the square of a number from a method. Look at the following source code.

Program source code 1:

public class Test 
{
 int square(int num){
   return num * num; // return a square value.
 }
public static void main(String[] args) 
{
// Create an obejct of class Test.
  Test t = new Test();
  
// Call the method using object reference variable. Since the return type of this method is int, we will store it using a variable of type int.  
   int squareOfNumber = t.square(20); 
 
// Displaying the result.    
   System.out.println("Square of 20: " +squareOfNumber);
  }
}
Output:
      Square of 20: 400

Explanation: Look at the below figure and understand the explanation that will help you to understand better.

Class name as return type in Java

a. In this example program, we have created a method named square(). This method accepts an integer value and calculates the square of it.

After calculating square of value, square() method returns that value to the main() method that is the calling method.

b. Inside the main() method, we are calling square() method using object reference variable t and passing 20 to it as follows: t.square(20);.

c. To get the result returned from the square() method, we have taken a variable “squareOfNumber” of type int as follows: int squareOfNumber = t.square(20);.

d. int before a method name specifies the type of value returned by the method.

e. After method name, we wrote int num as a parameter that receives an integer value into the method. We are passing a value 20 to the method at the time of calling from main method.

f. Now to calculate the square value and return it, we have used return statement (return num * num;) inside the square() method.

Thus, a return statement in java is used to return a value from a method. It can return only one value at a time. When a return statement is used inside the method, the flow of execution comes out of it and goes back to the caller method.

Types of Methods Declaration based on Return type in Java


1. Method with void type:

For example:

void m1() {
       - - - - - 
       - - - - - 
 }

Here, the void represents “return nothing”. A return type void is used when there is no return value.

2. Methods with return type and value

If a method is having int, double, float, etc other than void, we must return a value compatible with the declared return type by using the return statement.

If you are not returning any value, it will generate an error message like ” missing return statements “.  Let’s take some examples related to it.

1. int m1() {
      - - - - - - 
      return 10;
  }
2. int m2() {
      return 20;
      - - - -  - 
  }

Code 2 is an invalid code because, inside the method, the return statement must be the last statement of method.

How to return primitive values like int, float, double?


Let’s take an example program where we will return primitive values like int, float, and char to methods m1(), m2(), and m3() respectively.

Program source code 2: 

public class Sample 
{ 
// Declare a method with return type int. 
  int m1()
  { 
   System.out.println("m1 method"); 
// If you declare a method to return a value, you must return a value of declared type. Since the return type of m1() method is an integer. So, we will have to return an integer value. 
      return 20; 
} 
Similarly,
  float m2() 
  { 
    System.out.println("m2 method"); 
      return 20.5f; 
  } 
  static char m3()
  { 
    System.out.println("m3 method"); 
     return 'd'; 
  } 
public static void main(String[] args)
 { 
// Create an object of the class named Sample. 
    Sample s = new Sample();
 
// Call m1() method using reference variable s. Since s.m1() is returning an integer value, we will store value by using a variable x with a data type int. 
      int x = s.m1(); 
// Now print the return value. 
    System.out.println("Return value of m1()= " +x); 
Similarly,
    float y = s.m2();
    System.out.println("Return value of m2()= " +y); 

// Call static method using the class name. Since m3() method returns character, we will store a character using a variable ch with type char. 
    char ch = Sample.m3(); 
    System.out.println("Return value of m3()= " +ch); 
  } 
 }
Output:
       m1 method 
       Return value of m1()= 20 
       m2 method 
       Return value of m2()= 20.5 
       m3 method 
       Return value of m3()= d

In this example program, methods m1(), m2(), and m3() are returning primitive value to the main method that is calling method.

But at the project level, generally, we do not return primitive value. At the real-time project level, we return an object as returning value.

How to return class object in Java?


In the realtime project, we return different class objects as returning values. You must remember that Java cares about type. In other words, you cannot return a Student when the return type is declared as an Employee.

For example:

Employee m1()
{
// Create the Employee class's object.
   Employee emp = new Employee();
    return emp;
  }

Here, m1() method’s return type is Employee.

Let’s take an example program based on this concept.

Consider a project in which there are three modules like Student, Employee, and School in an application. We will create a class for each module.

We will declare m1() and m2() methods with return type Student and Employee class respectively in the school class. See the coding given below.

Program source code 3:

public class Student
{
  - - - - - - - 
} 
public class Employee 
{ 
   - - - - - - -
 } 
public class School 
{ 
// Declare a method with return type Student class. 
  Student m1()
  { 
   System.out.println("m1 method"); 
   Student st = new Student(); // Line 1
// Return the object reference variable named st as a value. 
    return st; // Line 2

// We can replace line 1 and line 2 code by using a single line of code. 
      return new Student(); // This line of code is generally used in the project level. 
 } 
// Similarly, declare another method with return type Employee class. 
  Employee m2()
  { 
    System.out.println("m2 method"); 
    Employee emp = new Employee(); // Line 3 
     return emp; // Line 4 
  // return new Employee(); // For line 3 and 4. 
    } 
// Declare static method with return type String. 
   static String m3()
   { 
     System.out.println("Shubh"); 
     return "Shubh"; 
   } 
public static void main(String[] args) 
{ 
// Create an object of class School. 
   School sc = new School(); 
// Call m1() method using reference variable sc and store returning value by using a variable s. 
     Student s = sc.m1(); 
     System.out.println(s); 
     Employee e = sc.m2(); 
     System.out.println(e); 
     String str=School.m3(); 
     System.out.println(str); 
   }
 }
Output:
       m1 method 
       [email protected] 
       m2 method 
       [email protected] 
       Shubh 
       Shubh

How to return current or same class object in Java?


In the last example program, we have returned different class objects but we can also return the current class object at the project level. Let’s understand this concept with the help of an example.

class Student
{
  Student m1() {  // Here, Student represents current class.
   - - - - -
First approach:
   Student st = new Student();
     return st;

Second approach:
     return this;
  }
}

Ways to return current/same class object

There are two ways to return the current or same class object.

1. If the method’s return type is a current class, you create an object of the class and return object reference variable.

2. You can also return a value direct using “this” keyword which represents the current class object. But at the project level, it is always recommended to use the second approach.

Let’s take an example program where we will use both approaches to return the same class object.

Program source code 4:

public class College 
{ 
// Declare a method with return type College class. 
  College collegeName()
  { 
   System.out.println("IIT-ISM is the best Engineering college in India."); 
// Create an object of the class. 
    College cg = new College(); // using first approach. 
     return cg; 
 // return new College(); 
 } 
College estYear()
{ 
  System.out.println("IIT-ISM was established in 1926. ");
   return this; // using 2nd approach. 
} 
public static void main(String[] args) 
{ 
// Create an object of class. 
   College c = new College(); 
    College cName = c.collegeName(); 
   System.out.println(cName); 
   College eYear = c.estYear(); 
   System.out.println(eYear); 
   } 
 }
Output:
       IIT-ISM is the best Engineering college in India. 
       [email protected] 
       IIT-ISM was established in 1926. 
       [email protected]

How to return a variable in Java programming?


Let us consider an example to return a variable.

int m1(int a) {
    - - - -
   return a;
 }

Here, we have declared an m1() method with return type int and parameter a. Since m1() method’s return type is an integer. So, we must return an int value. Therefore, we will return ‘a’ as a value of int type.

Generally, there are three cases for returning a variable in Java.

Case 1:

Assume int a = 200; // instance variable.
   int m1(int a) {  // Here, parameter 'a' is a local variable.
        - - - - -
     return a; 
  }

The above code contains both instance and local variables. In this case, the first priority will always go to the local variable and will return ‘a’ as a value.

Case 2:

int a = 20;
int m2( ) { // No local variable here.
     - - - - 
    return a;
 }

In this case, it will return the instance value due to no local variable.

Case 3:

int a = 30;
 int m3(int a) {
     - - - -- 
   return this.a;
 }

It will return instance variable due to using ‘this’ keyword. So, remember these three very important cases for the project level.

Let’s implement these three cases in the programs one by one.

Program source code 5:

public class VarReturn 
{ 
// Declare an int instance variable and assign it with value 100. The value 100 goes into a variable named x. 
   int x = 100; 
// Declare a method with an int parameter named x where x will behave like a local variable.
   int m1(int x)
   { 
     System.out.println("m1 method"); 
      return x; // return local variable. 
   } 
public static void main(String[] args) 
 { 
// Create an object of class VarReturn. 
   VarReturn vr = new VarReturn();

// Call m1() method with passing an integer value 20 and store returning integer value using variable named 'a'. 
     int a = vr.m1(20); 
     System.out.println("Method return value = " +a); 
   } 
}
Output:
       m1 method 
       Method return value = 20

Program source code 6:

public class InsReturn { 
// Declare instance variable of type int and assign it with value 100. The value 100 goes into variable named y. 
   int y = 100; 
// Declare a method with no parameter. 
  int m1()
  { 
    System.out.println("m1 method"); 
    return y; // return instance variable. 
  } 
public static void main(String[] args) 
 { 
    InsReturn ir = new InsReturn(); 
// Call m1() method and store returning integer value using a variable named 'a'. 
     int a = ir.m1(); 
     System.out.println("Method return value = " +a); 
  } 
 }
Output:
      m1 method 
      Method return value = 100

Program source code 7:

public class InstReturn 
{ 
 int x=100;  
 int m1(int x)
 { 
   System.out.println("m1 method"); 
   return this.x; // return instance variable. 
  } 
public static void main(String[] args) 
 { 
   InstReturn itr = new InstReturn(); 
// Call m1() method, passing integer value 20 and store returning integer value using a variable. 
    int a = itr.m1(20); 
    System.out.println("Method return value = " +a);
  } 
}
Output: 
      m1 method 
      Method return value = 1003.

3. Method with return type and without value:

For example:

int m3() {
    - - - - 
  return c;
}

A method is able to return a value but holding the value is optional. So, it is always recommended to hold the return value.

Let’s create a program where we will declare a method with return type but without value.

Program source code 8:

public class Addition 
{ 
public int add()
{ 
 int a = 100; 
 int b = 200; 
 int c = a + b; 
  return c; 
} 
public static void main(String[] args) 
 { 
   Addition ad = new Addition(); 
    int x = ad.add(); 
   System.out.println(x); 
  } 
}
Output: 
        300

Can we declare return statement inside main method in Java?


If we write a return statement inside the main method, the entire program or application will be terminated and the next statement after return statement will not be executed in the program.

Let’s take a program and see what happens?

Program source code 9:

public class Test 
{
public static void main(String[] args) 
{
 int a = 10;
 System.out.println("Before return statement");
 if(a == 10)
	return; // Here, it will terminate the appication program. 
 System.out.println("After return statement");
  }
}
Output:
      Before return statement

In this example program, we can also write System.exit(0); at the place of return statement to terminate the program. Here, exit(0) is a static method defined by class System. Therefore, it can be called by using class name.


Hope that this tutorial has covered all the variety of example programs based on return type in Java. If this tutorial is useful, please share it on social networking sites for your friends.
Thanks for reading!!!
Next ⇒ Constructor in Java

⇐ Prev Next ⇒

Can a class name be a return type?

When a method uses a class name as its return type, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.

What does classname return?

It returns the Class object that represents the specified class name. This is used if you need to get the Class object. This roughly corresponds to . getClass() which returns the Class object that corresponds to the object instance.

Can we give any class name in Java?

Core Java bootcamp program with Hands on practice You shouldn't use predefined or existing class names as the name of the current class. You shouldn't use any Java keywords as class name (with the same case). The First letter of the class name should be capital and remaining letters should be small (mixed case).

What is class name .class in Java?

Java provides a class with name Class in java. lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects.