Udemy logo

java methodsWhile writing a program, sometimes we need to perform a certain set of instruction or execute certain functionality repeatedly and instead of writing the set of statements frequently we generalize this statement by setting them in a function or method. Every programming language uses the methodology of methods to make the code simple, easy and robust.

Functions are of Two Types

Learn Java from scratch with a tutorial at Udemy.com

Creating the Method:

General Syntax

 

modifier returnType nameOfMethod(Parameter List)

{

// method body

}

Learn more about Java programming with a tutorial at Udemy.com

Syntax:

public static intfuncName((argument 1, argument 2)
{
//body
}

Example

class Demo
{
public static in myFirst(int n, int m)
{
System.out.println(“I am inside the Function”);
int max;
if(n>m)
{
max=n;
}
else
{
max=m;
}
return max;
}}

Note the “static”  keyword is used, but it’s optional. Declaring a function static means  that it can be directly called inside the class without creating class objects.

Things to Note

Get to know more about Java programming with a tutorial at Udemy.com

Method Calling

To use a defined function, it must be called. When the method is called, the control jumps to the functions and its execution starts until the return statement or closing curly braces are not found.

import java.util.*;
import java.lang.*;
import java.io.*;
class Demo
{
// Main method
public static void main(String[] args) {
int a = 4;
int b = 6;
//Function calls
int c = sumFunction(a, b);
display(c);
}
//  Returns the sum of the Two numbers
public static intsumFunction(int n, int m)
{
int sum=0;
sum= n+m;
return sum;
}
public static void Display(int sum)
{
System.out(“This function prints the variable”);
System.out.println("The Sum is = " + sum);
}
}

Output

The Sum is = 10

There are two functions present in this example. One function calculates the sum of the two arguments passed to it and returns the result. The display function only prints the result on the console and does not return any value.

The “Main” method is present in every program. It is a compulsory function and is declared  static always. Main method is the starting point of execution of the program. All the function calls are made from “main” method.

There are two ways of passing the value to the function:

Method Overloading

When a class has two or more methods with the same name but different number of arguments, it is known as method overloading. In such cases the compiler decides which function has to be called, on the basis of arguments passed.

Example

class DemoOverloading{
public static void main(String[] args) {
int a = 10;
int b = 5;
double c = 7.5;
double d = 3.4;
int result1 = maxFunction(a, b);
// Same functions but different parameter types
double result2 = maxFunction(c, d);
System.out.println("Maximum Value = " + result1);
System.out.println("Maximum Value = " + result2);
}
// function with integer parameters
public static intsumFunction(int n1, int n2) {
int max;
if (n1 > n2)
max = n1;
else
max = n2;
return max;
}
// function with double parameters
public static double sumFunction(double n1, double n2) {
double max;
if (n1 > n2)
max = n1;
else
max = n3;
return max;
}
}

Output

Maximum Value = 10

Maximum Value = 7.5

When the integer value is passed as an argument then “sumFunction(int n1, int n2)” is called, but when a double value is passed then “sumFunction(double n1, double n2)” is called.

Constructors

Constructors are special methods that have the exact same name as the class. They are called automatically when the object of the class is created. They are used to initialize the values. Every class has an object in Java by default and thus the constructor method is present in the program even if we do not create it. We can overload the constructor for our specific purposes.

Example

class MyClass {
int x;
// the Constructor
MyClass(inti )
{
x = i;
}
public static void main(String args[])
{
// Objects are created
MyClass t3 = new MyClass( 10 );
MyClass t4 = new MyClass( 20 );
System.out.println(t3.x + " " + t4.x);
}
}

Output

10 20

When the objects are called, the constructors are automatically called with value being passed as argument to them.

Variable Arguments

We can pass the variable argument to the same function. We need to specify the function by an ellipis(…). Only one variable can be specified of variable length and should be the last parameter.

Example:

class Demo {
public static void main(String args[])
{
// Calling method with variable arguments
printMin(34, 1, 5, 6, 45.6);
printMin(new double[]{5, 45.6, 3});
}
public static void printMin( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (inti = 1; i<numbers.length; i++)
if (numbers[i] <  result)
result = numbers[i];
System.out.println("The min value is " + result);
}
}

Output:

The min value is 1

The min value is 3

The variable value passed is stored as an array in the variable defined in the function definition. For instance, “numbers” variable in the above example is stored as an array and the value can simply be accessed as done in the case of arrays.

Page Last Updated: May 2014

Top courses in Java

Java Tutorial for Beginners
Navin Reddy
4.5 (546)
Complete Java SE 8 Developer Bootcamp - OCA Prep Included
Intertech Training, Jeff Jensen
4.6 (9,178)
Highest Rated
Java 8 New Features In Simple Way
DURGASOFT DURGA
4.7 (13,823)
Complete Core Java In Simple Way
DURGASOFT NAGOOR BABU
4.7 (745)
Java Interview Help
Bharath Thippireddy
4.6 (1,189)
Design Patterns in Java
Dmitri Nesteruk
4.4 (7,949)
Java Programming for Complete Beginners
in28Minutes Official
4.5 (39,027)
Oracle Java Certification - Pass the Associate 1Z0-808 Exam.
Tim Buchalka's Learn Programming Academy, Goran Lochert
4.5 (5,391)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 1
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.4 (3,655)
Bestseller
Learn Selenium with Java, Cucumber + Live Project
Pavan Kumar
4.6 (4,316)
Bestseller
Java SE 11 Developer 1Z0-819 OCP Course - Part 2
Tim Buchalka, Tim Buchalka's Learn Programming Academy
4.2 (994)

More Java Courses

Java students also learn

Empower your team. Lead the industry.

Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.

Request a demo