return Keyword in Java

In Java if a method wants to return anything then it makes use of return keyword. Let us see important points about it :

  • return keyword can be used return objects, primitive types and expression.
  • We need to specify return type in method signature.
  • It can also be used to return null keyword. In this case return type in method signature can of any object type.
  • If we return any mathematical expression then that expression will be calculated before returning the final value.

Let us look at an example code to understand :

class TestReturn
{
	int intReturn() 
	{
		int num;
		num=10;
		// returning primitive type variable
		return num;
	}
	
	String stringReturn1() 
	{
		String str;
		str="Tech4Humans";
		// returning String object
		return str;
	}
	
	String stringReturn2()
	{
		// returning directly the String
		return "Tech4Humans for Life";
	}
	
	ExampleClass objectReturn() 
	{
		ExampleClass obj = new ExampleClass();
		obj.num=10;
		// returning an object
		return obj;
	}
	
	int expressionReturn() 
	{
		int temp = 10;
		// returning an expression
		return temp*(temp+4);
	}
	
	ExampleClass returnNull() 
	{
		// returning null
		return null;
	}
	
	// returning nothing
	void returnNothing() 
	{
		System.out.println("I am returning nothing");
	}
}

class ExampleClass{
	int num;
}

public class ReturnKeyword 
{
	public static void main(String[] args) 
	{
		TestReturn obj = new TestReturn();
		System.out.println(obj.intReturn());
		System.out.println(obj.stringReturn1());
		System.out.println(obj.stringReturn2());
		System.out.println(obj.objectReturn());
		System.out.println(obj.expressionReturn());
		System.out.println(obj.returnNull());
		obj.returnNothing();
	}
}

Output

10
Tech4Humans
Tech4Humans for Life
ExampleClass@15db9742
140
null
I am returning nothing

Leave a Comment