A Java technique is a compilation of declarations that are grouped to carry out a process. When you call the System.out.println() method, for instance, the system really executes numerous statements to exhibit a message on the calm.
Now you will study how to make your own techniques with or with no return values, appeal to a technique with or without parameters, and apply technique abstraction in the program plan.
Considering the following example to explain the syntax of a method
public static int methodName(int a, int b) { // body }
Here,
Method definition comprises a technique header and a method body. The similar is shown in the subsequent syntax:
Syntax
modifier returnType nameOfMethod (Parameter List) { // method body }
The syntax shown above includes −
Here is the source code of the above-defined method called min(). This method takes two parameters num1 and num2 and returns the maximum between the two −
/** the snippet returns the minimum between two numbers */ public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; }
By utilizing a technique, it should be called. There are two methods in which a method is called i.e., method revisits a value or recurring nothing (no return value).
The procedure of technique calling is uncomplicated. When a program invokes a technique, the program manager gets transferred to the called technique. This called technique then returns manage to the caller in two states, when
The method returning void is considered a call to a statement. Let's consider an example −
System.out.println("This is tutorialspoint.com!");
The method returning value can be understood by the following example:
int result = sum(6, 9);
Following is the example to demonstrate how to define a method and how to call it
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; } }
This will produce the following result
Minimum value = 6
The void keyword authorizes us to generate methods, which do not go back a value. Here, in the subsequent example, we believe a void technique methodRankPoints. This method is a void method, which does not return any value. Call to avoid technique must be a statement i.e. methodRankPoints(255.7);. It is a Java statement, which ends with a semicolon as exposed in the following example.
public class ExampleVoid { public static void main(String[] args) { methodRankPoints(255.7); } public static void methodRankPoints(double points) { if (points >= 202.5) { System.out.println("Rank:A1"); }else if (points >= 122.4) { System.out.println("Rank:A2"); }else { System.out.println("Rank:A3"); } } }
This will produce the following result:
Rank:A1
As working under calling procedure, arguments are to be overtaken. These should be in the identical order as their parameters in the technical specification. Parameters can be bypassed by charge or by reference.
Short-lived Parameters by worth means calling a technique with a parameter. Through this, the quarrel value is bypassed to the parameter.
Example
The subsequent program illustrates an instance of a passing parameter by worth. The values of the arguments remain identical even after the process of invocation.
public class swappingExample { public static void main(String[] args) { int a = 30; int b = 45; System.out.println("Before swapping, a = " + a + " and b = " + b); // Invoke the swap method swapFunction(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); } public static void swapFunction(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); } }
This will produce the following result:
Before swapping, a = 30 and b = 45 Before swapping(Inside), a = 30 b = 45 After swapping(Inside), a = 45 b = 30 **Now, Before and After swapping values will be same here**: After swapping, a = 30 and b is 45
While a class has two or additional methods by the similar name but dissimilar parameters, it is recognized as technique overloading. It is dissimilar from overriding. In superseding, a process has the equivalent method name, type, number of parameters, etc.
Let us believe the instance discussed previously for discovering minimum numbers of figure type. If, let us say we desire to discover the minimum number of twice types. Then the idea of overloading will be set up to generate two or more techniques with similar names but dissimilar parameters.
The following example explains the same:
public class ExampleOverloading { public static void main(String[] args) { int a = 11; int b = 6; double c = 7.3; double d = 9.4; int result1 = minFunction(a, b); // same function name with different parameters double result2 = minFunction(c, d); System.out.println("Minimum Value = " + result1); System.out.println("Minimum Value = " + result2); } // for integer public static int minFunction(int n1, int n2) { int min; if (n1 > n2) min = n2; else min = n1; return min; } // for double public static double minFunction(double n1, double n2) { double min; if (n1 > n2) min = n2; else min = n1; return min; } }
This will produce the following result:
Minimum Value = 6 Minimum Value = 7.3
The overloading process makes the lineup readable. Here, two processes are given by identical names except with diverse parameters. The least number from integer and twofold types is the consequence.
In short times you will desire to bypass some information into an agenda when you sprint it. This is achieved by transient command-line arguments to main( ).
A command-line argument is a knowledge that straight chases the program's name on the command line when it is performed. To contact the command-line arguments within a Java program is rather easy. They are amassed as strings in the String array passed to main( ).
The following program displays all of the command-line arguments that it is called with −
public class CommandLine { public static void main(String args[]) { for(int i = 0; i<args.length; i++) { System.out.println("args[" + i + "]: " + args[i]); } } }
Try executing this program as shown here:
$java CommandLine this is a command line 200 -100
This will produce the following result
args[0]: this args[1]: is args[2]: a args[3]: command args[4]: line args[5]: 200 args[6]: -100
This is a keyword in Java, which is utilized as an orientation to the object of the present class, within a case method or a constructor. Utilizing this you can pass on the members of a group such as constructors, uneven, and methods.
Note − The keyword this is used only within instance methods or constructors
In general, the keyword this is used to −
class Student { int age; Student(int age) { this.age = age; } }
class Student { int age Student() { this(20); } Student(int age) { this.age = age; } }
Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, This_Example.java.
public class This_Example { // Instance variable num int num = 10; This_Example() { System.out.println("This is an example program on keyword this"); } This_Example(int num) { // Invoking the default constructor this(); // Assigning the local variable num to the instance variable num this.num = num; } public void greet() { System.out.println("Hi Welcome to Tutorialspoint"); } public void print() { // Local variable num int num = 20; // Printing the local variable System.out.println("value of local variable num is : "+num); // Printing the instance variable System.out.println("value of instance variable num is : "+this.num); // Invoking the greet method of a class this.greet(); } public static void main(String[] args) { // Instantiating the class This_Example obj1 = new This_Example(); // Invoking the print method obj1.print(); // Passing a new value to the num variable through parametrized constructor This_Example obj2 = new This_Example(30); // Invoking the print method again obj2.print(); } }
This will produce the following result
This is an example program on keyword this value of local variable num is : 20 value of instance variable num is : 10 Hi Welcome to Tutorialspoint This is an example program on keyword this value of local variable num is : 20 value of instance variable num is : 30 Hi Welcome to Tutorialspoint
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... parameterName
In 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. Any regular parameters must precede it.
public class VarargsDemo { public static void main(String args[]) { // Call method with variable args printMax(34, 3, 3, 2, 56.5); printMax(new double[]{1, 2, 3}); } 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); } }
This will produce the following result:
The max value is 56.5 The max value is 3.0
It is probable to describe a technique that will be called immediately before an object's concluding obliteration by the garbage collector. This technique is called finalize( ), and it can be utilized to make sure that an object terminates minimally.
For instance, you strength use finalize ( ) to confirm that an open file owned by that object is closed.
To add finalize to a class, you just describe finalize ( ) method. The Java runtime calls that technique whenever it is about to recycle an object of that class.
Inside finalize ( ) technique, you will identify those exploits that must be executed before an object is obliterated.
The finalize( ) method has this general form −
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 when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.
Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.