Core Java -MethodNow you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design. Method definition consists of a method declaration and a method signature. Syntax: Accessmodifier modifier returnType nameOfMethod (Parameter List) { // method body }The syntax shown above includes: public static int methName(int a, int b) { // body }Here, Eg: Here is the source code of the above defined method called max(). This method takes two parameters num1 and num2 and returns the maximum between the two: public static int max(int n1, int n2) { int max; if (n1 > n2) max = n2; else max = n1; return max; } Method Invoking(Calling): For using a method, it should be called. There are two ways in which a method is called i.e. method returns a value (or) returning nothing (no return value). The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when: Eg: System.out.println("This is tesdbacademy");The method returning value can be understood by the following eg: int result = sum(6, 9);Eg: public class ExampleMinNumber{ public static void main(String[] args) { int a = 11; int b = 6; int c = minFunction(a, b); System.out.println("Minimum Value : " + c); } // returns the minimum of two numbers public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } }Output : Minimum value : 6 void Keyword : The void keyword allows us to create methods which do not return a value. Here, in the following eg we're going to consider a void method methodRankPoints. This method is a void method which does not return any value. Call to a void method must be a statement (i.e.) methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown below. Eg: public class ExampleVoid { public static void methodRankPoints(double points) { if (points >= 450) { System.out.println("Rank : A1"); } else if (points <= 300) System.out.println("Rank : A2"); else System.out.println("Rank : A3"); } public static void main(String[] args) { methodRankPoints(500); } }Output : Rank : A1 Passing Parameters by Value : While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference. Passing Parameters by Value means calling a method with a parameter. Through this the argument value is passed to the parameter. Eg: public class swappingExample { public static void swapping(int a, int b) { System.out.println("Before swapping(Inside), a = " + a + " b = " + b); // Swap n1 with n2 int c = a; a = b; b = c; System.out.println("After swapping(Inside), a = " + a + " b = " + b); } public static void main(String[] args) { int a = 10; int b = 15; System.out.println("Before swapping, a = " + a + " and b = " + b); // Invoke the swap method swapping(a, b); System.out.println("\n**Now, Before and After swapping values will be same here**:"); System.out.println("After swapping, a = " + a + " and b is " + b); } }Output : Before swapping, a = 10 and b = 15 Before swapping(Inside), a = 10 b = 15 After swapping(Inside), a = 15 b = 10 **Now, Before and After swapping values will be same here**: After swapping, a = 10 and b is 15 Method Overloading : When a class has two or more methods by same name but different parameters, it is known as method overloading. It is different from overriding. In overriding a method has same method name, type, number of parameters etc. Let's consider the eg shown before for finding minimum numbers of integer type. If, lets say we want to find minimum number of double type. Then the concept of Overloading will be introduced to create two or more methods with the same name but different parameters. Eg: public class ExampleOverloading{ // for integer public static int integermethod(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } // for double public static double doublemethod(double n1, double n2) { double min; if (n1 > n2) min = n2; else min = n1; return min; } public static void main(String[] args) { int a = 11; int b = 6; double c = 7.3; double d = 9.4; int result1 = integermethod(a, b); // same function name with different parameters double result2 = doublemethod(c, d); System.out.println("Minimum Value of result 1 : " + result1); System.out.println("Minimum Value of result 2 : " + result2); } }Output : Minimum Value of result 1 : 6 Minimum Value of result 2 : 7.3 Note : Overloading methods makes program readable. Here, two methods are given same name but with different parameters. The minimum number from integer and double types is the result. Constructors : A constructor initializes an object when it is created. It has the same name as its class and is similar to a method. However, constructors have no explicit return type. Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to perform any other startup procedures required to create a fully formed object. All classes have constructors, whether you define one or not, because Java automatically provides a default constructor that initializes all member variables to zero. However, once you define your own constructor, the default constructor is no longer used. Eg: // A simple constructor. class MyClass{ int x; //Constructor MyClass(){ x =10; } }You would call constructor to initialize objects as follows: public class ConsDemo{ public static void main(String args[]){ MyClass t1 =new MyClass(); MyClass t2 =new MyClass(); System.out.println(t1.x +" "+ t2.x); } }Note : Most often, you will need a constructor that accepts one or more parameters. Parameters are added to a constructor in the same way that they are added to a method, just declare them inside the parentheses after the constructor's name. Eg: public class MyClass{ int x; //Constructor MyClass(int i ){ x = i; } public static void main(String args[]){ MyClass t1 =new MyClass(10); MyClass t2 =new MyClass(20); System.out.println("Value of constructor : "+ t1.x); System.out.println("Value of constructor : "+ t2.x); } }Output : Value of constructor : 10 Value of constructor : 20 Variable Arguments(var-args) : JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows: typeName... parameterNameIn the method declaration, you specify the type followed by an ellipsis (...) Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precedence it. Eg: public class VarargsDemo{ public static void printMax(double... numbers){ if(numbers.length ==0){ System.out.println("No argument passed"); return; } double result = numbers[0]; for(int i =1; i < numbers.length; i++) if(numbers[i]> result) result = numbers[i]; System.out.println("The max value is "+ result); } public static void main(String args[]){ // Invoke method with variable args printMax(50,10,5,2,15.5); printMax(new double[]{5,10,20}); } }Output : The max value is 50.0 The max value is 20.0 finalize( ) Method : It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly. For eg, you might use finalize( ) to make sure that an open file owned by that object is closed. To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed. The finalize( ) method has this general form: Eg: protected void finalize(){ // finalization code here }Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class. This means that you cannot know whenever even finalize( ) will be executed. For eg, if your program ends before garbage collection occurs, finalize( ) will not execute. ☛ Join to Learn from Experts: Advanced Java Training in Chennai by TesDBAcademy
« Previous
Next Topic »
(Core Java - Operators)
|