When in a Method

Java - Methods


A Coffee method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for case, the system actually executes several statements in society to display a bulletin on the console.

Now you will learn how to create your ain methods with or without return values, invoke a method with or without parameters, and use method abstraction in the program design.

Creating Method

Considering the following example to explain the syntax of a method −

Syntax

public static int methodName(int a, int b) {    // body }        

Hither,

  • public static − modifier

  • int − return type

  • methodName − proper noun of the method

  • a, b − formal parameters

  • int a, int b − list of parameters

Method definition consists of a method header and a method body. The same is shown in the following syntax −

Syntax

modifier returnType nameOfMethod (Parameter List) {    // method body }        

The syntax shown above includes −

  • modifier − It defines the access type of the method and it is optional to use.

  • returnType − Method may return a value.

  • nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.

  • Parameter List − The list of parameters, it is the type, gild, and number of parameters of a method. These are optional, method may contain zero parameters.

  • method trunk − The method body defines what the method does with the statements.

Example

Hither is the source code of the in a higher place defined method called min(). This method takes two parameters num1 and num2 and returns the maximum between the two −

/** the snippet returns the minimum betwixt two numbers */  public static int minFunction(int n1, int n2) {    int min;    if (n1 > n2)       min = n2;    else       min = n1;     return min;  }        

Method Calling

For using a method, it should be called. There are two ways in which a method is called i.due east., method returns a value or returning nada (no return value).

The procedure of method calling is unproblematic. When a programme invokes a method, the program command gets transferred to the called method. This chosen method and so returns control to the caller in two conditions, when −

  • the return statement is executed.
  • it reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Lets consider an example −

Arrangement.out.println("This is tutorialspoint.com!");        

The method returning value tin be understood by the post-obit case −

int result = sum(6, 9);        

Post-obit is the example to demonstrate how to define a method and how to call it −

Example

public course ExampleMinNumber {        public static void chief(String[] args) {       int a = 11;       int b = half dozen;       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 −

Output

Minimum value = 6        

The void Keyword

The void keyword allows u.s.a. to create methods which do not render a value. Here, in the following example we're because 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 in the following example.

Example

public class ExampleVoid {     public static void main(Cord[] args) {       methodRankPoints(255.7);    }     public static void methodRankPoints(double points) {       if (points >= 202.v) {          Arrangement.out.println("Rank:A1");       }else if (points >= 122.4) {          Arrangement.out.println("Rank:A2");       }else {          System.out.println("Rank:A3");       }    } }        

This will produce the following result −

Output

Rank:A1        

Passing Parameters by Value

While working nether calling process, arguments is to be passed. These should be in the same gild as their respective parameters in the method specification. Parameters can be passed by value or past reference.

Passing Parameters by Value means calling a method with a parameter. Through this, the argument value is passed to the parameter.

Example

The following program shows an case of passing parameter by value. The values of the arguments remains the same even after the method invocation.

public form 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 bandy method       swapFunction(a, b);       Organisation.out.println("\n**Now, Earlier and Later on swapping values will exist same here**:");       Organization.out.println("After swapping, a = " + a + " and b is " + b);    }     public static void swapFunction(int a, int b) {       Organization.out.println("Before swapping(Inside), a = " + a + " b = " + b);              // Swap n1 with n2       int c = a;       a = b;       b = c;       Organisation.out.println("After swapping(Within), a = " + a + " b = " + b);    } }        

This will produce the post-obit event −

Output

Before swapping, a = 30 and b = 45 Before swapping(Inside), a = 30 b = 45 Subsequently swapping(Inside), a = 45 b = 30  **At present, Before and After swapping values will be aforementioned hither**: Later swapping, a = 30 and b is 45        

Method Overloading

When a class has two or more than methods past the aforementioned proper noun simply unlike parameters, information technology is known as method overloading. It is unlike from overriding. In overriding, a method has the same method name, type, number of parameters, etc.

Let's consider the case discussed earlier for finding minimum numbers of integer type. If, let'south say we want to find the 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.

The following instance explains the same −

Instance

public course ExampleOverloading {     public static void main(String[] args) {       int a = xi;       int b = 6;       double c = 7.iii;       double d = 9.4;       int result1 = minFunction(a, b);              // same office name with unlike parameters       double result2 = minFunction(c, d);       Organisation.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 −

Output

Minimum Value = 6 Minimum Value = 7.iii        

Overloading methods makes program readable. Here, two methods are given by the same proper noun only with different parameters. The minimum number from integer and double types is the result.

Using Command-Line Arguments

Sometimes you volition desire to laissez passer some information into a program when yous run it. This is accomplished by passing command-line arguments to main( ).

A command-line argument is the information that directly follows the programme's proper name on the command line when it is executed. To access the command-line arguments within a Java program is quite easy. They are stored as strings in the String assortment passed to main( ).

Example

The following programme displays all of the command-line arguments that it is chosen with −

public class CommandLine {     public static void main(String args[]) {        for(int i = 0; i<args.length; i++) {          Organisation.out.println("args[" + i + "]: " +  args[i]);       }    } }        

Try executing this program every bit shown here −

$java CommandLine this is a control line 200 -100        

This will produce the post-obit result −

Output

args[0]: this args[1]: is args[2]: a args[iii]: command args[4]: line args[5]: 200 args[half-dozen]: -100        

The this keyword

this is a keyword in Java which is used as a reference to the object of the current course, with in an instance method or a constructor. Using this yous tin refer the members of a class such every bit constructors, variables and methods.

Note − The keyword this is used only inside instance methods or constructors

This

In general, the keyword this is used to −

  • Differentiate the instance variables from local variables if they have same names, inside a constructor or a method.

class Student {    int age;       Educatee(int age) {       this.age = age;	    } }        
  • Call one type of constructor (parametrized constructor or default) from other in a course. It is known as explicit constructor invocation.

grade Student {    int age    Pupil() {       this(20);    }        Educatee(int age) {       this.age = age;	    } }        

Example

Here is an instance that uses this keyword to access the members of a course. Re-create and paste the following program in a file with the proper name, This_Example.java.

public class This_Example {    // Example variable num    int num = x; 	    This_Example() {       Arrangement.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() {       Arrangement.out.println("Hi Welcome to Tutorialspoint");    }           public void impress() {       // Local variable num       int num = twenty;              // 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 course       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(thirty);              // Invoking the print method again       obj2.print();     } }        

This will produce the following result −

Output

This is an instance program on keyword this  value of local variable num is : xx value of instance variable num is : 10 Howdy Welcome to Tutorialspoint This is an example plan on keyword this  value of local variable num is : xx value of instance variable num is : xxx Hi Welcome to Tutorialspoint        

Variable Arguments(var-args)

JDK one.5 enables you lot to pass a variable number of arguments of the same type to a method. The parameter in the method is declared equally 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 exist the last parameter. Any regular parameters must precede it.

Instance

public class VarargsDemo {     public static void master(String args[]) {       // Call method with variable args   	   printMax(34, 3, 3, 2, 56.5);       printMax(new double[]{i, 2, 3});    }     public static void printMax( double... numbers) {       if (numbers.length == 0) {          Arrangement.out.println("No statement passed");          return;       }        double result = numbers[0];        for (int i = ane; i <  numbers.length; i++)       if (numbers[i] >  outcome)       upshot = numbers[i];       System.out.println("The max value is " + result);    } }        

This will produce the following result −

Output

The max value is 56.5 The max value is iii.0        

The finalize( ) Method

It is possible to define a method that volition exist called just earlier an object's final devastation by the garbage collector. This method is chosen finalize( ), and it tin can be used to ensure that an object terminates cleanly.

For example, you might utilize finalize( ) to brand sure that an open up file owned by that object is airtight.

To add a finalizer to a grade, you just define the finalize( ) method. The Java runtime calls that method whenever information technology is near to recycle an object of that class.

Inside the finalize( ) method, y'all will specify those actions that must be performed before an object is destroyed.

The finalize( ) method has this general course −

protected void finalize( ) {    // finalization lawmaking here }        

Here, the keyword protected is a specifier that prevents access to finalize( ) past code divers outside its class.

This ways that you lot cannot know when or even if finalize( ) volition exist executed. For case, if your programme ends before garbage collection occurs, finalize( ) will not execute.

Useful Video Courses


Java Date and Time Online Training

Video

Java Servlet Online Training

Video

JavaScript Online Training

Video

Java Essential Training

Video

Java Essentials Online Training

Video

riverathemay.blogspot.com

Source: https://www.tutorialspoint.com/java/java_methods.htm

0 Response to "When in a Method"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel