Java return Statement
return statement
return statement can be used to return a value in a method definition. Method declaration or definition should indicate the return type in the first line - the method signature.
return data type mentioned in the method signature and value returned by return statement in the method block must be of the same type.
syntax
return; return <any primitive value > return <any object > return <null> return <method call that returns a value>
Java return statement - Examples
return need not return any value
void sayHello(){
System.out.println("Hello");
return;
}
return can return any int value
int getNumber(){
return 2;
}
return can return any float value
float payInterest{
return 2.0f;
}
return can return any String value
String getName(){
return "Jam";
}
return can return any char value
char isCorrect(){
return 'Y';
}
return can return any long value
long getLargeNumber(){
return 5003453l;
}
return can return any double value
double getPiValue()( return 3.14159265; )
return can return an array of values
int[] getNumbers()(
return {1,2,3,5,7,11};
)
return can return null
String get()( return null; )
return can return a value returned by a expression
float getPi()( return Math.PI*3; )
return can call a method that returns a value
int getLength(String name)( return name.length(); )
The value returned by any value can be assigned to a variable of appropriate data type
public class ReturnExample {
public static void main(String a[]){
String name="Jan";
int length = getLength(name);
float Pi= getPi();
int[] numbers = getNumbers();
System.out.println(""+ getLargeNumber());
}
}
Krivalar Tutorials 