Returning Value From the Method
Simple example of returing addition value
- We can specify return type of the method as “Primitive Data Type” or “Class name”.
- Return Type can be “Void” means it does not return any value.
- Method can return a value by using “return” keyword.
Example : Returning Value from the Method
class Rectangle { int length; int breadth; void setLength(int len) { length = len; } int getLength() { return length; } } class RectangleDemo { public static void main(String args[]) { Rectangle r1 = new Rectangle(); r1.setLength(20); int len = r1.getLength(); System.out.println("Length of Rectangle : " + len); } }
Output :
C:zubair>java RectangleDemo Length of Rectangle : 20
There are two important things to understand about returning values :
- The type of data returned by a method must be compatible with the return type specified by the method. For example, if the return type of some method is boolean, you could not return an integer.
boolean getLength() { int length = 10; return(length); }
- The variable receiving the value returned by a method (such as len, in this case) must also be compatible with the return type specified for the method.
int getLength() { return length; } boolean len = r1.getLength();
- Parameters should be passed in sequence and they must be accepted by method in the same sequence.
void setParameters(String str,int len) { ----- ----- ----- } r1.setParameters(12,"Zubair");
Instead it should be like –
void setParameters(int length,String str) { ----- ----- ----- }r1.setParameters(12,"Zubair");
Comments
Post a Comment