Hi ,I am learning java ,and wondering why is this return in this method
Thanks

public void updateDisplay()
	{
		if (curIndex<0 || curIndex>=appObj.array.size())
		{
			display.setText("");
			return;
		}
		display.setText( appObj.array.get(curIndex).toString());
		
	}

It tests curIndex to see if it's valid as an index for appObj.array.
If it's not valid then the method sets the display to blank, after which it can't do any more so it returns directly to the caller.
If it's valid then it goers on to set the display based on the data.

In this particular case you could achieve the same result with an else:

if (curIndex<0 || curIndex>=appObj.array.size()) {
  display.setText("");
} else {
  display.setText( appObj.array.get(curIndex).toString();
}

but if there was a lot more processing to do then the first version is cleaner.

This is a simple example of a common pattern:

test to see if parameters are OK
if not - just return; // cannot continue
continue doing all the processing for this method with valid values.

commented: Great minds think alike... and so do ours... +11

The return exits the method at that point. It means that none of the rest of the method executes if that branch happens.

In this case, the effect is the same as

public void updateDisplay()
	{
		if (curIndex<0 || curIndex>=appObj.array.size())
		{
			display.setText("");
		}
 		else
		{
		display.setText( appObj.array.get(curIndex).toString());
		}
	}

Great answers from Jon and James.

It's just telling the code to return back to the calling function if you hit that chunk of code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.