Scientech Easy Return type in Java with Example | Basic & Project Level | Scientech Easy

Friday, September 14, 2018

Return type in Java with Example | Basic & Project Level

In this guide, we will learn Return type in Java with a practical examples and programs in an easy way and step by step so that you do not get any problem to learn this topic. So let's start.

What is a Return type in Java?

Return is a keyword which is used to exit from the method only with or without a value. Every method is declared with a return type and it is mandatory for Java methods. Return type may be a primitive type like int, float, double, a reference type, or void type which represents return nothing. That is they don't give anything back. When a method is called, the method may return a value to the caller.

Type of declaration of methods based on return type and arguments

1. Methods with void type:
Example: 
      void m1() {
          --- - - - 
          -- - - - 
       }
In this example, void represents "return nothing". You can see previous method chapter for the example and programs. 

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 ".
Example 1:
     int m1() {
       - - - - - - 
      - - - - - - 
      return 10;
    }
Example 2:
     int m2() {
      return 20;
       - - - -  - 
       - - - - - 
    }
This code is invalid code because inside the method, Return statement must be last statement of the method.
Let's see simple example programs.

How to return primitive value like integer, float, double?

Program source code 1: 
    package com.scientecheasy; public class Sample { // Declare the methods 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 return type of m1() method is integer. So you will have to return some 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 the object of the class named Sample. Sample s=new Sample(); // Call the m1 method using s reference. Since s.m1() is returning integer value. // So we will store integer value by using x variable. 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 the static method using the class name. Since m3() method return character. So we will store a character using ch variable. 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, methods are returning primitive value but in the project level, Generally, we do not return primitive value. In the real-time project level, we return an object as returning value.

How to return different class objects?

For example:
  Employee m1() {
   // Create the Employee class 's object.
        Employee emp=new Employee();
           return emp;
  } 
Here m1() method 's return type is Employee.

Always Remember: Java cares about type! That is you can not return a Student when the return type is declared as an Employee.
Let's see another example related to this concept.
Program source code 2: 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. Now we will create m1() and m2() methods with return type Student and Employee class respectively in the school class. See the coding given below.

    package com.scientecheasy; public class Student { - - - - - - - - } package com.scientecheasy; public class Employee { - - - - - - - - } package com.scientecheasy; public class School { // Declare a method with return type Student class. Student m1(){ System.out.println("m1 method"); // Create the object of the student class. Student st=new Student(); // (1) // Now return the object reference variable named st as a value. return st; // (2) // We can replace line 1 and line 2 code by using single 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(); // (3) return emp; // (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 the object of the class School. School sc=new School(); // Call the m1 method using sc reference variable and store the returning value by using s variable. Student s=sc.m1(); // Now Print the returning value. System.out.println(s); // Call the m2 method and store the returning value by using e variable. Employee e=sc.m2(); System.out.println(e); // Call the static method using class name and store it using an str variable. String str=School.m3(); System.out.println(str); } }
    Output: m1 method com.scintecheasy.Student@1db9742 m2 method com.scientecheasy.Employee@106d69c Shubh Shubh

How to return the current or same class object?

In the last example, we have declared and returned using the different classes like Student, Employee class in the project level but we can also return the current class object in the project level. 
For example:
  class Student {
     Student m1() { // Here student represents current class.
       - - - - -
       - - - - -
  First approach:
    Student st=new Student();
       return st;

  Second approach:
       return this;
  }
 }
            
There are two ways to return the current class object. 
1. If the method's return type is the current class, you create the object of the class and return the reference variable.
2. You can also return a value direct using "this" keyword which represents the current class object.
But in the project level, It is always recommended to use the second approach. Now let's take a simple example.

Program source code 3:
    package com.scientecheasy; public class College { // Declare a method with return type College class. College collegeName(){ System.out.println("IIT-ISM is the best Engneering college in India."); // Create the 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) { // Now Create the object of the 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. com.scientecheasy.College@1db9742 IIT-ISM was established in 1926. com.scientecheasy.College@106d69c

How to return a variable?

Consider an example to return a variable.
  int m1(int a) {
     - - - -
     - - - -
     return a;
  }
Here we 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. Now we will discuss three cases for returning a variable.
Case 1:
   Assume  int a=200; // instance variable.
        int m1(int a){ // local variable.
            - - - - -
            return a; // local
    }
The above code contains both instance and local variable. So in this case, first priority always goes to the local variable and it will return 'a' as a value.

Case 2:
Now   int a=20;
           int m2( ) { // No local variable here.
           - - - - 
           return a;
        }
In this case, it will return instance value due to no local variable.

Case 3:
          int a=30;
           int m3(int a) {
            - - - -- -
           return this.a;
          }
 In this code, it will return instance variable due to using 'this' keyword. So remember these three very important cases for project level.
Let's implement these three cases in the programs one by one.

Program source code 4:
    package com.scientecheasy; public class VarReturn { // Declare an int instance variable and assign it the value 100. The value 100 goes into the variable named x. int x=100; // Declare a method with an int parameter named x where x will behave like 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 the class VarReturn. VarReturn vr=new VarReturn(); // Now call the m1() method, passing the integer value 20 and store the 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 5: 
    package com.scientecheasy; public class InsReturn { // Declare an int instance variable and assign it the value 100. The value 100 goes into the 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) { // Create an object of the class InsReturn. InsReturn ir=new InsReturn(); // Now call the m1() method and store the 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 6:
    package com.scientecheasy; public class InstReturn { // Declare an int instance variable and assign it the value 100. The value 100 goes into the 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 this.x; // return instance variable. } public static void main(String[] args) { // Create an object of the class InstReturn. InstReturn itr=new InstReturn(); // Now call the m1() method, passing the integer value 20 and store the returning integer value using a variable. int a=itr.m1(20); System.out.println("Method return value= " +a); } }
    Output: m1 method Method return value= 100

3. Method with return type and without value:
Example:
      int m3() {
       - - - - 
       - - - - 
       return c;
     }
Method is able to return a value but holding the value is optional. So it is always recomended to hold the return value.
Let's take one simple example.
Program source code 7:
    package com.scientecheasy; 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
Final words:
I hope that this article has covered all the variety of practical examples and programs related to return type in Java. All example programs are very important for basic and project level. You follow all the important steps and practice them. 

                                                              


Next ➝ Java Constructor                                                              

Popular