Methods In Java – Types, Class, Main, Parameters, and Examples

In this tutorial, we will talk about What Is Methods In Java. This is a continuation of the previous topic, entitled Regular Expression. This topic will cover all the important methods that will help you on your way to becoming a Java developer.

The Methods In Java is a code block that executes only when invoked. You can pass parameters, or data, to a method. Methods needed to carry out certain activities are also known as functions.

What Is Methods In Java

A Methods In Java is a collection of statements or a block of code organized together to conduct a certain task or operation. It is used to achieve code reusability.

What Are The Four Types Of Methods In Java

What is Java Constructor? | Types o...
What is Java Constructor? | Types of Java Constructor | TECHLISTIC.COM

The following are the 4 types of Methods In Java listed below.

  • Public – It can be used in all of your application classes.
  • Protected – It’s accessible in the class where it’s defined and in any classes that inherit from that class.
  • Private – It can only be accessed from within the class where it is defined.
  • Default – It is declared or defined without any kind of change. It can be accessed from the same class and package that define its class.

What Are Methods In Java Class

The Method In Java gives information about and access to a single method on a class or interface. The reflected method can be a class method or an instance method (including an abstract method).

What Is Methods In Java With Example

A Methods In Java is a set of Java statements that work on some data and may or may not return a result.

The following are simple examples of Methods In Java

// sample created by Glenn
public MyClasses{

    public void writeText(String text) {
        System.out.print(text);   //prints the text parameter to System.out.
    }
}

What Is The Main Method In Java

The Main Method In Java is static, which means that you don’t have to create any instances before you use it. void: Some programming languages return 0 or 1 to show that the main method has finished successfully. The main function of Java is void, which means that it doesn’t return anything when it’s done.

How Methods Are Declared In Java

A Methods In Java can be declared only by the needs the method’s return type, name, a pair of parentheses (), and a body between braces ().

What Are Java Method Parameters

The Parameter In Java is a value that can be passed to a method. The parameter can then be used by the method as if it were a local variable with the value of the variable provided to it by the calling method.

Can We Have 2 Main Methods In Java

We can can have more than one main method, but only if they use the concept of overloading. There should be only one main method with a parameter of “string[] arg.”

Method and Function Are Same In Java

A Method and Function In Java are the same thing with different terms. In object-oriented programming, a procedure or function is called a method. A function is a group of reusable code that can be called from anywhere in your program. This takes away the need to write the same code over and over again.


Without further ado, I will further explain the Methods In Java with some basic examples in order for you to easily understand the topic.

A Java method is a group of statements that work together to perform an operation. When you call the System.out.println() method, for example, the system executes several statements to show a message on the console.

Creating Method In Java

Consider the following example to explain the syntax in Creating a Method In Java.

Syntax

public static int methodName(int g, int l) {
// body
// samle created by glenn
}

further explanation of example syntax for Creating Method In Java listed below.

  • public staticmodifier
  • int – return type
  • methodName – name given into the method
  • g , l – formal parameters
  • int g, int l – list of parameters

A method definition is made up of a header and a body. The same is shown in the syntax below:

Syntax

modifier returnType nameOfMethod (Parameter List) {
// method body
// sample created by Glenn
}

The syntax shown above includes the following listed below.

  • modifier – It describes the method’s access type and its use is optional.
  • returnType – Method in Java that return a value.
  • nameOfMethod – This is the name of the method. The method name and the list of parameters are what make up the method signature.
  • parameter list – The list of parameters is a method’s type, order, and number of parameters. These are optional, and a method can have zero parameters.
  • method body – The method body describes what the method does with the statements.

Example Program In Creating Method In Java

The following Java source code below is for the method called min() that was described above. This method takes two numbers, num1 and num2, as input and returns the larger of the two.

/** the snippet returns the minimum between two numbers */
// sample created by Glenn

public static int minFunction(int g1, int g2) {
   int min;
   if (g1 > g2)
      min = g2;
   else
      min = g1;

   return min; 
}

Method Calling In Java

To call a Java method, write the name of the method, followed by two parentheses () and a semicolon. Calling a method is a simple process. When a program calls a method, the control of the program moves to the method that was called.

Method Calling In Java is an easy thing to do. When a program calls a method, the control of the program moves to the method that was called. This called method then gives control back to the person who called it in one of two ways.

The following listed below are two ways to call the method.

  • return statement is executed
  • reach the method ending closing brace

When a method returns void, it is treated as a call to a statement. Lets consider an example below.

System.out.println(“PIES (Provide IT and Educational Solution!)”);

The method return value can be understood by looking at the following example.

int result = total(2, 6);

The following example below is a demonstration to define a method and how to call it.

Example Program for Calling a Method In Java

// program created by Glenn
public class ExampleMinNumber {
   
   public static void main(String[] args) {
      int a = 21;
      int b = 16;
      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 lead to the following result.

Output

Minimum Value = 16

In order for you to test your Java code provided in this lesson, you must test the code in your code editor. But if you wish to run this code online, we also have an online compiler in Java for you to test your java code for free.

We also provide a Java Online Compiler for every code below. Just scroll down so that you can easily test or execute the source code.

Void Keyword In Java

The Void Keyword In Java they allow us create methods that don’t return a value. Here, in the following example, we’ll look at a void method called methodRankPoints. This method is a “void” method, which means it does not return any value. Calling a void method must be a statement, like methodRankPoints(255.7);. It is a Java statement that ends with a semicolon, as shown in the following example below.

Example Program Void Keyword Program In Java

// program created by Glenn
public class ExampleVoid {

   public static void main(String[] args) {
      methodRankPoints(357.7);
   }

   public static void methodRankPoints(double points) {
      if (points >= 302.5) {
         System.out.println("You Are Rank : A1");
      }else if (points >= 222.4) {
         System.out.println("You Are Rank : A2");
      }else {
         System.out.println("You Are Rank : A3");
      }
   }
}

This will lead to the following result.

Output

You Are Rank : A1

Passing Parameters By Value In Java

Arguments need to be passed while working under the calling process. These should be in the same order as their corresponding parameters in the method specification. You can pass parameters either by value or by reference.

Calling a method with a parameter is called “passing parameters by value.” By doing this, the value of the argument is sent to the parameter.

Example Program In Passing Parameters By Value In Java

The following program below shows an example of passing parameters by value. The values of the arguments stay the same even after the method is called.

// program created by Glenn
public class swappingExample {

   public static void main(String[] args) {
      int a = 50;
      int b = 75;
      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 lead to the following result.

Output
Before swapping, a = 50 and b = 75
Before swapping(Inside), a = 50 b = 75
After swapping(Inside), a = 75 b = 50

**Now, Before and After swapping values will be same here**:
After swapping, a = 50 and b is 75

Method Overloading In Java

The Method Overloading In Java these is two or more methods with different parameters can have the same name (different number of parameters, different types of parameters, or both). These methods are called overloaded, and the way they work is called method overloading.

Let’s look at the example we talked about earlier for finding minimum integer numbers. Let’s say we want to find the fewest number of double-type characters. Then, the idea of overloading will be explained, which lets you make two or more methods with the same name but different parameters.

The following program below explains it in more detail.

Example Program Using Method Overloading In Java

// program created by Glenn
public class ExampleOverloading {

   public static void main(String[] args) {
      int a = 21;
      int b = 26;
      double c = 8.3;
      double d = 11.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 g1, int g2) {
      int min;
      if (g1 > g2)
         min = g2;
      else
         min = g1;

      return min; 
   }
   
   // for double
   public static double minFunction(double g1, double g2) {
     double min;
      if (g1 > g2)
         min = g2;
      else
         min = g1;

      return min; 
   }
}

This will lead to the following result.

Output

Minimum Value = 21
Minimum Value = 8.3

The Method Overloading In Java makes programs easier to read. In this case, two methods with the same name but different parameters are used. The result is the fewest number of integer and double types.

Using Command-Line Arguments In Java

You may want to give a program some information when you run it. This is done by passing command-line arguments to main( ).

A Command-Line Argument In Java is the information that comes right after the program’s name on the command line when it is run. It’s easy to get to the command-line arguments inside a Java program. They are saved as strings in the String array passed to main( ).

Example Program Using Command-Line Arguments In Java

The following program below shows all of the Command-Line Arguments In Java.

// program created by Glenn
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 to execute this program shown below.

$java CommandLine this is a command line 400 -200

This will lead to the following result.

Output

args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 400
args[6]: -200

this Keyword In Java

A this is a Java keyword that is used to refer to the object of the current class in a constructor or an instance method. With this, you can talk about the parts of a class, like constructors, variables, and methods.

Notethis keyword in Java can only be used in instance methods or constructors.

this keyword in Java
this keyword in Java

The following below is a list of this keywords that can be used.

  • In a constructor or method, if the names of the instance variables and the local variables are the same, you need to tell them apart.
class Faculty {
   int age;   
   Faculty(int age) {
      this.age = age;	
   }
}
  • Call one type of constructor (parameterized or default) from another in a class. It’s called explicit constructor invocation.
class Faculty {
   int age
   Student() {
      this(26);
   }
   
   Faculty(int age) {
      this.age = age;	
   }
}

Example Program Using this Keyword In Java

// program created by Glenn
public class This_Example {
   // Instance variable num
   int num = 20;
    
   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 This is Glenn Magada Azuelo from itsourcecode.com");
   }
      
   public void print() {
      // Local variable num
      int num = 30;
      
      // 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(40);
      
      // Invoking the print method again
      obj2.print(); 
   }
}

This will lead to the following result.

Output

This is an example program on keyword this
value of local variable num is : 30
value of instance variable num is : 20
Hi This is Glenn Magada Azuelo from itsourcecode.com
This is an example program on keyword this
value of local variable num is : 30
value of instance variable num is : 40
Hi This is Glenn Magada Azuelo from itsourcecode.com

Variable Arguments In Java

The Variable Arguments (Var-args) in Java is a method that can take a variable number of arguments.

This is how the parameter in the method is declared.

typeName… parameterName

In the method declaration, you list the type, then put an ellipsis after it (…). A method can only have one variable-length parameter, and this parameter must be the last one. Any regular parameters must precede it.

Example Program using Variable Arguments In Java

// program created by Glenn
public class VarargsDemo {

   public static void main(String args[]) {
      // Call method with variable args  
       printMax(44, 43, 53, 22, 66.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 lead to the following result.

Output

The max value is 66.5
The max value is 3.0

finalize() Method In Java

The finalize() method in Java is used to free up all the resources an object is using before the Garbage Collector deletes or destroys it.

You can define a method that will be called right before the garbage collector destroys an object for good. This method is called finalize(), and it can be used to make sure an object ends properly.

For example, you might use finalize() to close a file that belongs to that object but is still open.

To add a finalizer to a class, you just have to define the finalize() method. The Java runtime calls that method whenever it wants to reuse an object of that class.

Inside the finalize() method, you tell the computer what actions must be taken before an object is destroyed.

The following is basic syntax of finalize() method.

protected void finalize( ) {
// finalization code here
// sample created by Glenn
}

Here, the keyword protected is a specifier that stops code defined outside the class from accessing the finalize() function.

This means that you don’t know when or if finalize() will be run. For example, if your program ends before garbage collection happens, finalize() won’t run.

Summary

In summary, you have learned about Methods In Java. This tutorial has covered the following topics: What Is Methods In Java, What Are The Four Types Of Methods In Java, What Are Methods In Java Class, What Is Methods In Java With Example, What Is The Main Method In Java, How Methods Are Declared In Java, What Are Java Method Parameters, Can We Have 2 Main Methods In Java, Method and Function Are Same In Java, Creating Method In Java, Method Calling In Java, Void Keyword In Java, Passing Parameters By Value In Java, Method Overloading In Java, Using Command-Line Arguments In Java, this Keyword In Java, Variable Arguments In Java, and finalize() Method In Java. I use NetBeans IDE to test all the source code given in the lesson.

I hope this lesson has helped you learn what is Methods In Java and how to use them.

What’s Next

The next section talks about Files and I/O programming. At the end of the session, you’ll know what Files and I/O all about in Java.


Leave a Comment