What is Java Methods
Methods in Java are 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
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 defines 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 are 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 of 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 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 is listed below.
- public static – modifier
- 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 returns 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 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. Let’s 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; } }
Output:
Minimum Value = 16
In order for you to test the 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.
You can test the above example here! ➡Java Online Compiler
Void Keyword in Java
The Void Keyword In Java they allow us to 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"); } } }
Output:
You Are Rank : A1
You can test the above example here! ➡Java Online Compiler
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); } }
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
You can test the above example here! ➡Java Online Compiler
Method Overloading in Java
The Method Overloading In Java there are 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; } }
Output:
Minimum Value = 21
Minimum Value = 8.3
You can test the above example here! ➡Java Online Compiler
The Method of 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
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
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.
Note – this keyword in Java can only be used in instance methods or constructors.
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(); } }
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
You can test the above example here! ➡Java Online Compiler
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); } }
Output:
The max value is 66.5
The max value is 3.0
You can test the above example here! ➡Java Online Compiler
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 the 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, this article provided an in-depth exploration of Java methods, covering various aspects such as the types of methods (Public, Protected, Private, Default), the main method, method declaration, parameters, and method overloading.
It also explained the process of creating, calling, and using methods in Java with detailed examples.
Also, we discuss the void keyword, passing parameters by value, command-line arguments, the ‘this’ keyword, variable arguments (var-args), and the finalize() method.
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 are all about in Java.
< PREVIOUS
NEXT >