Wednesday 28 August 2013

Methods

Basically  methods are used for the reusability of the code....once you write the code and calls it again and again..method always present outside the main method.
simple program for methods...

output:
main begin
welcome to java tutorial
main end

  execution of the program starts from the main method.first it print "main begin" then it finds the calling statement to print method the cursor goes to print method after printing it backs to main method and prints next statement of main "main end"

this method doesn't contain any return type so we use "void" as a return type.
void means no return value.

if the return type is void then the return statement is optional.
if the return type is other then the void then return statement must be present as a last statement in the method.
Return should be the last statement in the method otherwise it will give Compile time error.
                                   
                                           
output:-

in the above program 2 statement of main method it prints the sop function and returns the value in "i".





the println function also print both statement of print method ....

Parameters:-

                                              


in this we pass a parameter to print method.while calling the method from main we must pass similar argument as we pass in method.

if we perform any operation in the method then the resultant value will not be reflected in the another method.
the change in the value of local variable in one methods doesn't visible in other methods.Arguments of method local to that method.if we declare any variable inside the method then the scope of the variable limited to that method we can not access it outside the method.

Example:-




change in print method doesn't visible in main method.

Examples:

show changes which perform in the main method.

Example



if we declare variable as a global then changes in any method visible to all methods.

Example:-




change in the value of x visible in all methods.


No comments :

Post a Comment