Methods provides functionality or behaviour of an object.
Syntax: [modifiers] <returnType> <methodName> (<params>) { //Method implementation. }
Types of Methods:
- Instance methods
- Static methods
Instance Methods
- Methods defined inside the class without using the static modifier are called as Instance methods.
Static Methods
- Methods defined inside the class with using static modifier are called as Static methods.
Ex: class Hello{ void m1(){ //INSTANCE METHOD } static void m2(){ //STATIC METHOD` } } class Test{ Hello h = new Hello(); h.m1(); //VALID h.m2(); //VALID Hello.m1(); //INVALID Hello.m2(); //VALID Hello h = null; h.m1(); //INVALID h.m2(); //VALID }
- Instance methods must be invoked with the reference variable which contains the object.
- Static methods can be invoked in 3 ways:
- With Class Name
- With the reference variable which contains null
- With the reference variable which contains Object.
Methods Return Type
- Method can return a result in 2 ways:
- Using the result inside the method.
- Returning the result to the caller method.
- If you want to return the result to the caller of the method, then the return type (data type) needs to be specified.
- When you don't want to return the result of a method to the caller of the method, then you must specify return type as void.
Example 1:
class Lab11{ public static void main(String args[]){ Manager mg = new Manager(); mg.setAge(-12); } } class Manager{ int age=18; void setAge(int age){ if(age<18) return; this.age = age; } } /* Though the return type of the method is void, empty return statements are allowed in the methods with void as return type. */
Example 2:
class Lab12{ public static void main(String args[]){ Manager mg = new Manager(); mg.setAge(-12); } } class Manager{ int age=18; void setAge(int age){ if(age<18) return 0; //You are not allowed to return anything when the return type mentioned in the method is void. this.age = age; } } /* Lab12.java:12: error: incompatible types: unexpected return value return 0; ^ 1 error */Example 3:
class Lab12{ public static void main(String args[]){ Manager mg = new Manager(); int a = mg.show(10); System.out.println(a); System.out.println(mg.show(10)); //if a method returns something, it can be directly executed from SOP } } class Manager{ int show(int x){ return x+1; } } } /* output: 11 11 */
Example 4:
class Lab14{ public static void main(String args[]){ Manager mg = new Manager(); mg.show(10); //returned value will be discarded System.out.println("done"); } } class Manager{ int show(int x){ return x+1; } } /* output: done */
Example 5:
If the method return type is specified in the method declaration, then you cannot use an empty return statement (as good as not returning anything. Only the control is transferred back to the caller). The return statement should return the datatype.class Lab16{ public static void main(String args[]){ Manager mg = new Manager(); mg.show(10); //returned value will be discarded System.out.println("done"); } } class Manager{ int show(int x){ System.out.println("show()"); return; } } /* Lab16.java:12: error: incompatible types: missing return value return; ^ 1 error */
Example 6:
class Lab17{ public static void main(String args[]){ Manager mg = new Manager(); mg.show(10); //returned value will be discarded System.out.println("done"); } } class Manager{ int show(int x){ System.out.println("show()"); return 12L; } } /* The return type expected is int, but a long type is returned. This needs explicit casting C.T.E Lab17.java:12: error: incompatible types: possible lossy conversion from long to int return 12L; ^ 1 error */
Example 7:
class Lab18{ public static void main(String args[]){ Manager mg = new Manager(); mg.show(10); //returned value will be discarded System.out.println("done"); } } class Manager{ int show(int x){ System.out.println("show()"); return 'A'; } } /* Here the datatype of the returned value is char is implicitly converted to an int. Output: show() done */
Example 8:
class Lab19{ public static void main(String args[]){ Manager mg = new Manager(); mg.show(10); //returned value will be discarded System.out.println("done"); } } class Manager{ long show(int x){ System.out.println("show()"); return x+1; } } /* Here the datatype of the returned value is int, what is expected is long int is implicitly converted to long. Output: show() done */
Example 9:
class Lab20{ public static void main(String args[]){ Manager mg = new Manager(); System.out.println(mg.show(10)); System.out.println("done"); } } class Manager{ boolean show(int x){ System.out.println("show()"); return false; return false; } } /* C.T.E cannot have more than 1 return statement inside a block Lab20.java:13: error: unreachable statement return false; ^ 1 error */
Example 10:
class Lab23{ public static void main(String args[]){ Manager mg = new Manager(); System.out.println(mg.isDigit('A')); System.out.println(mg.isDigit('8')); } } class Manager{ boolean isDigit(char ch){ System.out.println("isDigit(): "+ch); if(ch >=48 && ch<=57){ return true; }else{ return false; } } } /* isDigit(): A false isDigit(): 8 true */
Method Parameters
There are two types of argument:- Formal Argument
- Actual Argument
class Hello{ void show(int a, int b){ //Formal arguments ... } }Actual Argument: Arguments specified with the method call are called as Actual Arguments.
Hello h = new Hello(); h.show(10,20); //Actual arguments
Example 11:
class Lab29{ public static void main(String args[]){ Hello h = new Hello(); h.show((65)); } } class Hello{ void show(char x){ System.out.println("show(char)"); } } /* Lab29.java:4: error: incompatible types: possible lossy conversion from int to char h.show((65)); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error */
Example 12:
class Lab28{ public static void main(String args[]){ Hello h = new Hello(); h.show((byte)12); } } class Hello{ void show(byte x){ System.out.println("show(byte)"); } } /* show(byte) */
Method Overloading
- You can write multiple methods inside the class with the same name by changing the parameters. This process is called METHOD OVERLOADING.
- When you are overloading methods, the following rules must be followed:
- Method name must be same.
- Method parameter must be changed in terms of
- Number of parameters
- Datatype of parameters
- Order of parameters
- Overloading can be achieved even if the return type doesn't match, .
- Overloading can be achieved even if the access level is different, .
- Overloading can be achieved even if one overloaded method is marked "static" or "abstract".
Example 12:
class Lab35{ public static void main(String args[]){ Hello h = new Hello(); String a = h.add(99,"BNG"); System.out.println(a); String b = h.add("BNG",99); System.out.println(b); } } class Hello{ String add(int a, String b){ System.out.println("add(int, int)"); return a+b; } String add(String a, int b){ System.out.println("add(String, int)"); return a+b; } } /* add(int, int) 99BNG add(String, int) BNG99 */
Example 13:
class Lab39{ public static void main(String args[]){ Hello h = new Hello(); byte b = 20; h.add(b,b); } } class Hello{ void add(byte a, int b){ System.out.println("add(byte a, int b)"); } void add(int a, byte b){ System.out.println("add(int a, byte b)"); } } /* C.T.E Lab39.java:5: error: reference to add is ambiguous h.add(b,b); ^ both method add(byte,int) in Hello and method add(int,byte) in Hello match 1 error*/
Example 14:
class Lab41{ public static void main(String args[]){ Hello h = new Hello(); h.show('A','B'); } } class Hello{ void show(int a, char b){ System.out.println("show(int,char)"); } void show(long a, char b){ System.out.println("show(long,char)"); } } /* output: show(int,char) */
Example 15:
class Lab41{ public static void main(String args[]){ Hello h = new Hello(); h.show('A','B'); } } class Hello{ void show(int a, char b){ System.out.println("show(int,char)"); } void show(long a, char b){ System.out.println("show(long,char)"); } } /* output: show(int,char) */
Example 16:
class Lab42{ public static void main(String args[]){ Hello h = new Hello(); h.show('A','B'); } } class Hello{ void show(int a, int b){ System.out.println("show(int,int)"); } void show(long a, long b){ System.out.println("show(long,long)"); } } /* show(int,int) */
Example 17:
class Lab43{ public static void main(String args[]){ Hello h = new Hello(); h.show('A','B'); } } class Hello{ void show(int a, int b){ System.out.println("show(int,int)"); } void show(long a, char b){ System.out.println("show(long,char)"); } } /* Lab43.java:4: error: reference to show is ambiguous h.show('A','B'); ^ both method show(int,int) in Hello and method show(long,char) in Hello match 1 error */
Example 18:
class Lab44{ public static void main(String args[]){ Hello h = new Hello(); h.show(null); h.show("BNG"); h.show(h); } } class Hello{ void show(String str){ System.out.println("show(String)"); } void show(Object str){ System.out.println("show(Object)"); } } /* output: show(String) show(String) show(Object) */
Example 19:
class Lab45{ public static void main(String args[]){ Hello h = new Hello(); h.show(null); } } class Hello{ void show(String str){ System.out.println("show(String)"); } void show(Hello str){ System.out.println("show(Hello)"); } } /* Lab45.java:4: error: reference to show is ambiguous h.show(null); ^ both method show(String) in Hello and method show(Hello) in Hello match 1 error */
Example 20:
class Lab49{ public static void main(String args[]){ //System.out.println(10); println(int) method is executed. //System.out.println(10L); println(long) method is executed. System.out.println(10,20); } } /* C.T.E Lab49.java:3: error: no suitable method found for println(int,int) System.out.println(10,20); ^ method PrintStream.println() is not applicable (actual and formal argument lists differ in length) method PrintStream.println(boolean) is not applicable (actual and formal argument lists differ in length) method PrintStream.println(char) is not applicable (actual and formal argument lists differ in length) method PrintStream.println(int) is not applicable (actual and formal argument lists differ in length) method PrintStream.println(long) is not applicable (actual and formal argument lists differ in length) method PrintStream.println(float) is not applicable (actual and formal argument lists differ in length) method PrintStream.println(double) is not applicable (actual and formal argument lists differ in length) method PrintStream.println(char[]) is not applicable (actual and formal argument lists differ in length) method PrintStream.println(String) is not applicable (actual and formal argument lists differ in length) method PrintStream.println(Object) is not applicable (actual and formal argument lists differ in length) 1 error */
Example 21:
class Lab52{ public static void main(String args[]){ System.out.println(null); } } /* Lab52.java:3: error: reference to println is ambiguous System.out.println(null); ^ both method println(char[]) in PrintStream and method println(String) in PrintStream match 1 error */
Call by Value / Call by Reference
Call by Value:
When you invoke a method by passing primitive data types then it is called as CALL BY VALUE. In this case, any change happening inside the called method will not be reflected in the caller method.
Call by Reference
When you invoke a method by passing reference data type then it is called as CALL BY REFERENCE.
a. Any modifications done to the property of the object inside the called method will be reflected to the caller method.
b. If the reference itself is modified then modifications happened inside the called method will not be reflected to caller method.
Example 22:
Call by Valueclass Lab53 { public static void main(String[] args) { int a = 99; Hello h = new Hello(); System.out.println("main begin :"+a); h.m1(a); System.out.println("main ends :"+a); } } class Hello { void m1(int a){ System.out.println("m1 begin: "+a); a=a+10; System.out.println("m1 ends : "+a); } } /* Ouput: main begins :99 m1 begins :99 m1 ends : 109 main ends: 99 */
Example 23:
Call by Referenceclass Lab54 { public static void main(String[] args) { Hai hai = new Hai(); hai.a = 99; Hello hello = new Hello(); System.out.println("main begins: "+hai.a); hello.m1(hai); System.out.println("main ends: "+hai.a); } } class Hello { void m1(Hai hai){ System.out.println("m1 begins: "+hai.a); hai.a=hai.a+10; System.out.println("m1 ends: "+hai.a); } } class Hai { int a; } /* output: main begins: 99 m1 begins :99 m1 ends: 109 main ends: 109 */
Example that demonstrates swapping variables using static/instance overloaded methods
public class SwapMe{ int var1; int var2; SwapMe(int var1, int var2){ this.var1 = var1; this.var2 = var2; } void swapByRef(){ System.out.println("Calling swapByRef() - instance method : "); int temp = this.var1; this.var1 = this.var2; this.var2 = temp; System.out.println("var1 - "+this.var1+"\t var2 - "+this.var2); } static void swapByRef(SwapMe t1){ System.out.println("Calling swapByRef() - static method : "); int temp = t1.var1; t1.var1 = t1.var2; t1.var2 = temp; System.out.println("var1 - "+t1.var1+"\t var2 - "+t1.var2); } void show(){ System.out.println("var1 - "+this.var1+"\t var2 - "+this.var2); } public static void main(String[] args) { SwapMe t1 = new SwapMe(1, 2); System.out.println("Before Swapping:"); t1.show(); System.out.println("----------------------------------------"); System.out.println("After Swapping using instance method"); t1.swapByRef(); System.out.println("----------------------------------------"); System.out.println("After Swapping using static method"); SwapMe.swapByRef(t1); } }
Summary:
- Instance and static members can be accessed from instance methods.
- Only static members can be accessed from static methods.
- When return type is void, then:
- You should not specify return statement.
- You can specify empty return statement.
- When return type NOT is void, then:
- You must specify return statement.
- You should not specify EMPTY RETURN statement.
- Return values must be same or compatible to the return type.
- Actual arguments and formal arguments must be
- Same in terms of number of arguments.
- Same or compatible in terms of type of arguments.
- Same in terms of order of arguments.
No comments:
Post a Comment