Methods in Java
A method is a block of code or a collection of statements or a set of code
grouped to perform a certain task or operation. It is used to achieve the
reusability of code. We write a method once and use it many times. We do
not need to write code again and again. It also provides easy modification
and readability of code, just by adding or removing a chunk of code. The
method is executed only when we call or invoke it.
The most important method in Java is the main() method
Why Methods?
o Reusability: Methods provide code reusability. Once a method is
defined, it can be called multiple times from various parts of the
program.
o Modularity: Methods help break down complex problems into smaller,
manageable pieces.
o Maintainability: With methods, updating and debugging code
becomes easier since changes in one part of the program do not
necessarily impact other parts.
o Abstraction: Methods provide a way to encapsulate implementation
details, exposing only the necessary parts to the users.
Naming a Method
While defining a method, remember that the method name must be a verb
and start with a lowercase letter. If the method name has more than two
words, the first name must be a verb followed by an adjective or noun. In the
multi-word method name, the first letter of each word must be in uppercase
except the first word. For example:
Single-Word Method Name: sum(), area()
Multi-Word Method Name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method in
the same class; it is known as method overloading.
Method Declaration
The method declaration provides information about method attributes, such
as visibility, return type, name, and arguments. It has six components that
are known as method header, as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of
the method declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the
method. It specifies the visibility of the method. Java provides four types of
access specifiers:
o public: The method is accessible to all classes when we use the public
specifier in our application.
o private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.
o protected: When we use a protected access specifier, the method is
accessible within the same package or subclasses in a different
package.
o default: When we do not use any access specifier in the method
declaration, Java uses the default access specifier by default. It is
visible only from the same package.
Return Type: Return type is a data type that the method returns. It may
have a primitive data type, object, collection, void, etc. If the method does
not return anything, we use the void keyword.
Method Name: It is a unique name that is used to define the name of a
method. It must correspond to the functionality of the method. Suppose, if
we are creating a method for subtraction of two numbers, the method name
must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and
enclosed in a pair of parentheses. It contains the data type and variable
name. If the method has no parameter, leave the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the
actions to be performed. It is enclosed within a pair of curly braces.
The method body is enclosed in curly braces {} and contains the statements
that define the functionality or working of the method. For example, consider
the following code snippet.
public class Example {
// Method definition
public int add(int a, int b) {
int sum = a + b; // Method body
return sum; // Return statement
}
}
Types of Methods
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
The methods that are already defined in the Java class libraries are known
as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by
calling them in the program at any point.
For example, [Link](), [Link](), [Link](),
[Link](), [Link](), etc, are predefined methods.
When we call any of the predefined methods in our program, a series of code
related to the corresponding method runs in the background.
Example: Predefined Method
public class Main {
public static void main(String[] args) {
// pow() is an in-built function defined in the Math class
[Link]("2 raised to the power of 5 is: " + [Link](2, 5));
}
}
Output:
2 raised to the power of 5 is: 32.0
User-Defined Method
The method written by the user or programmer is known as a user-
defined method. These methods can be modified or customized according
to the requirements.
How to Call or Invoke a User-defined Method?
In Java, calling or invoking a method depends on whether the method is
static or non-static.
If the method is static, we can call it directly using the class name or from
within the same class. Note that we need to create an object for calling static
methods.
static void display() {
// code
}
[Link](); // no need to create an object
If the method is non-static, we must create an object of the class and use it
to call the method.
Note: We will get a compile-time error if we try to call a non-static
method from a static context without an object because non-static
methods belong to instances, not the class itself.
Empolyee emp = new Empolyee();
[Link](); // method called using object reference
Example: User-Defined Method
public class Main {
// Static method
static void greet() {
[Link]("Hello from the static method!");
}
// Non-static method
void farewell() {
[Link]("Goodbye from a non-static method!");
}
public static void main(String args[]) {
Main obj = new Main();
[Link](); //calling non-static method
[Link](); //calling static method
}
}
Output:
Goodbye from a non-static method!
Hello from the static method!
Method Overloading in Java
Method overloading in Java is the feature that enables defining several
methods in a class having the same name but with different parameters lists.
These algorithms may vary with regard to the number or type of parameters.
When a method is called, Java decides which version of it to execute
depending on the arguments given. If we have to perform only one
operation, having the same name of the methods increases the readability of
the program.
Suppose you have to perform the addition of the given numbers, but there
can be any number of arguments if you write the method such as a(int,int)
for two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behavior of
the method because its name differs. Here's an explanation with real-life
examples:
Math Operations:
In a math class, you might have multiple methods for adding numbers, each
accepting a different number of arguments:
public class MathOperations {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b, double c) {
return a + b + c;
}
}
Here, the add method is overloaded to handle both adding two integers and
adding three doubles.
String Manipulation:
In a utility class for string manipulation, you might have overloaded methods
for concatenating strings:
public class StringUtils {
public String concatenate(String str1, String str2) {
return str1 + str2;
}
public String concatenate(String str1, String str2, String str3) {
return str1 + str2 + str3;
}
}
These methods enable concatenating two or three strings together based on
the number of arguments passed.
Different ways to overload a method in Java
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In Java, Method Overloading is not possible by changing the return
type of the method only.
1) Method Overloading: By changing no. of arguments
Method overloading in Java allows defining multiple methods with the same
name but different parameter lists. One common form of overloading is
changing the number of arguments in the method signature. In this example,
we have created two methods, the first add() method performs addition of
two numbers, and the second add method performs addition of three
numbers.
In this example, we are creating static methods so that we don't need to
create instance for calling methods.
Example
// Class Adder contains overloaded methods to add integers
class Adder {
// Method to add two integers
static int add(int a, int b) {
return a + b;
}
// Method to add three integers
static int add(int a, int b, int c) {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
// Calling the add method with two integers
[Link]([Link](11, 11)); // Output: 22
// Calling the add method with three integers
[Link]([Link](11, 11, 11)); // Output: 33
}
}
Output:
22
33
2) Method Overloading: By changing data type of
arguments
Method overloading in Java also allows changing the data type of arguments
in the method signature. Here's an example demonstrating method
overloading based on the data type of arguments: In this example, we have
created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double
arguments.
Example
// Class Adder contains overloaded methods to add numbers
class Adder {
// Method to add two integers
static int add(int a, int b) {
return a + b;
}
// Method to add two doubles
static double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
// Calling the add method with two integers
[Link]([Link](11, 11)); // Output: 22
// Calling the add method with two doubles
[Link]([Link](12.3, 12.6)); // Output: 24.9
}
}
Output:
22
24.9
Java Math Class
The [Link] class contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and
trigonometric functions.
Math Class Declaration
Following is the declaration for [Link] class −
public final class Math
extends Object
Java Math Class Fields
Following are the fields for [Link] class −
static double E − This is the double value that is closer than any
other to e, the base of the natural logarithms.
static double PI − This is the double value that is closer than any
other to pi, the ratio of the circumference of a circle to its diameter.
Java Math Class Methods
Sr.N
o
Method & Description
static double abs(double a)
1
This method returns the absolute value of a double value.
static float abs(float a)
2
This method returns the absolute value of a float value.
static int abs(int a)
3
This method returns the absolute value of an int value.
static long abs(long a)
4
This method returns the absolute value of a long value.
static double acos(double a)
5 This method returns the arc cosine of a value; the returned angle is
in the range 0.0 through pi.
static double asin(double a)
6 This method returns the arc sine of a value; the returned angle is in
the range -pi/2 through pi/2.
static double atan(double a)
7 This method returns the arc tangent of a value; the returned angle is
in the range -pi/2 through pi/2.
static double atan2(double y, double x)
8 This method returns the angle theta from the conversion of
rectangular coordinates (x, y) to polar coordinates (r, theta).
static double cbrt(double a)
9
This method returns the cube root of a double value.
static double ceil(double a)
This method returns the smallest (closest to negative infinity)
10
double value that is greater than or equal to the argument and is
equal to a mathematical integer.
static double copySign(double magnitude, double sign)
11 This method returns the first floating-point argument with the sign
of the second floating-point argument.
static float copySign(float magnitude, float sign)
12 This method returns the first floating-point argument with the sign
of the second floating-point argument.
13 static double cos(double a)
This method returns the trigonometric cosine of an angle.
static double cosh(double x)
14
This method returns the hyperbolic cosine of a double value.
static double exp(double a)
15 This method returns Euler's number e raised to the power of a
double value.
static double expm1(double x)
16
This method returns ex -1.
static double floor(double a)
This method returns the largest (closest to positive infinity) double
17
value that is less than or equal to the argument and is equal to a
mathematical integer.
static int getExponent(double d)
18 This method returns the unbiased exponent used in the
representation of a double.
static int getExponent(float f)
19 This method returns the unbiased exponent used in the
representation of a float.
static double hypot(double x, double y)
20 This method returns sqrt(x 2 +y2) without intermediate overflow or
underflow.
static double IEEEremainder(double f1, double f2)
21 This method computes the remainder operation on two arguments
as prescribed by the IEEE 754 standard.
static double log(double a)
22 This method returns the natural logarithm (base e) of a double
value.
static double log10(double a)
23
This method returns the base 10 logarithm of a double value.
static double log1p(double x)
24 This method returns the natural logarithm of the sum of the
argument and 1.
static double max(double a, double b)
25
This method returns the greater of two double values.
static float max(float a, float b)
26
This method returns the greater of two float values.
static int max(int a, int b)
27
This method returns the greater of two int values.
static long max(long a, long b)
28
This method returns the greater of two long values.
static double min(double a, double b)
29
This method returns the smaller of two double values.
static float min(float a, float b)
30
This method returns the smaller of two float values.
static int min(int a, int b)
31
This method returns the smaller of two int values.
static long min(long a, long b)
32
This method returns the smaller of two long values.
static double nextAfter(double start, double direction)
33 This method returns the floating-point number adjacent to the first
argument in the direction of the second argument.
static float nextAfter(float start, double direction)
34 This method returns the floating-point number adjacent to the first
argument in the direction of the second argument.
static double nextUp(double d)
35 This method returns the floating-point value adjacent to d in the
direction of positive infinity.
static float nextUp(float f)
36 This method returns the floating-point value adjacent to f in the
direction of positive infinity.
static double pow(double a, double b)
37 This method returns the value of the first argument raised to the
power of the second argument.
static double random()
38 This method returns a double value with a positive sign, greater
than or equal to 0.0 and less than 1.0.
39 static double rint(double a)
This method returns the double value that is closest in value to the
argument and is equal to a mathematical integer.
static long round(double a)
40
This method returns the closest long to the argument.
static int round(float a)
41
This method returns the closest int to the argument.
static double scalb(double d, int scaleFactor)
This method returns d × 2scaleFactor rounded as if performed by a single
42
correctly rounded floating-point multiply to a member of the double
value set.
static float scalb(float f, int scaleFactor)
This method return f × 2scaleFactor rounded as if performed by a single
43
correctly rounded floating-point multiply to a member of the float
value set.
static double signum(double d)
This method returns the signum function of the argument; zero if
44
the argument is zero, 1.0 if the argument is greater than zero, -1.0 if
the argument is less than zero.
static float signum(float f)
This method returns the signum function of the argument; zero if
45
the argument is zero, 1.0f if the argument is greater than zero, -1.0f
if the argument is less than zero.
static double sin(double a)
46
This method returns the hyperbolic sine of a double value.
static double sinh(double x)
47
This method Returns the hyperbolic sine of a double value.
static double sqrt(double a)
48 This method returns the correctly rounded positive square root of a
double value.
static double tan(double a)
49
This method returns the trigonometric tangent of an angle.r
static double tanh(double x)
50
This method returns the hyperbolic tangent of a double value.
static double toDegrees(double angrad)
51 This method converts an angle measured in radians to an
approximately equivalent angle measured in degrees.
static double toRadians(double angdeg)
52 This method converts an angle measured in degrees to an
approximately equivalent angle measured in radians.
static double ulp(double d)
53
This method returns the size of an ulp of the argument.
static double ulp(float f)
54
This method returns the size of an ulp of the argument.
Methods Inherited
This class inherits methods from the following classes −
[Link]
Java Math Class Example
The following example shows the usage of some important methods
provided by Math class.
package [Link];
public class MathDemo {
public static void main(String[] args) {
// get two double numbers
double x = 60984.1;
double y = -497.99;
// get the natural logarithm for x
[Link]("[Link](" + x + ")=" + [Link](x));
// get the natural logarithm for y
[Link]("[Link](" + y + ")=" + [Link](y));
// get the max value
[Link]("[Link](" + x + ", y" + ")=" + [Link](x,y));
// get the min value
[Link]("[Link](" + x + ", y" + ")=" + [Link](x,y));
}
}
Output
[Link](60984.1)=11.018368453441132
[Link](-497.99)=NaN
[Link](60984.1, y)=60984.1
[Link](60984.1, y)=-497.99
Arrays
An array is typically a grouping of elements of the same kind that are stored
in a single, contiguous block of memory.
Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous memory
location. It is a data structure where we store similar elements. We can store
only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the
0th index, 2nd element is stored on 1st index and so on.
Types of Array in java
There are two types of array.
o Single Dimensional Array
o Multidimensional Array
Single-Dimensional Array in Java
A single-dimensional array in Java is a linear collection of elements of the
same data type. It is declared and instantiated using the following syntax:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.
Example
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
public class Main{
public static void main(String args[]){
//declaration and instantiation of an array
int a[]=new int[5];
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++){//length is the property of array
[Link](a[i]);
}
}
}
Output:
10
20
70
40
50
Declaration, Instantiation and Initialization of
Java Array
In Java, you can declare, instantiate, and initialize an array in a single line, as
demonstrated below:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let's see the simple example to print this array.
Example
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
public class Main{
public static void main(String args[]){
//declaration, instantiation and initialization of an array
int a[]={33,3,4,5};
//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}
}
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop
prints the array elements one by one. It holds an array element in a variable,
then executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
Example
//Java Program to print the array elements using for-each loop
public class Main{
public static void main(String args[]){
//declaration and initialization of an array
int arr[]={33,3,4,5};
//traversal of an array using for-each loop
for(int i:arr)
[Link](i);
}
}
Output:
33
3
4
5
Passing Array to a Method in Java
We can pass the Java array to the method so that we can reuse the same
logic on any array. When we pass an array to a method in Java, we are
essentially passing a reference to the array. It means that the method will
have access to the same array data as the calling code, and any
modifications made to the array within the method will affect the original
array.
Example
//Java Program to demonstrate the way of passing an array to method.
public class Main{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<[Link];i++)
if(min>arr[i])
min=arr[i];
[Link](min);
}
public static void main(String args[]){
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}
Output:
3
Explanation
This Java program demonstrates the concept of passing an array to a
method. The min method takes an integer array arr as a parameter and finds
the minimum element in the array using a simple iterative loop. In the main
method, an integer array a is declared and initialized with values {33, 3, 4,
5}, and then the min method is called with this array as an argument. The
min method iterates through the array to find the minimum element and
prints it to the console.
Anonymous Array in Java
Java's anonymous arrays eliminate the requirement for separate declarations
of array variables by enabling developers to build and initialize arrays
directly within method calls or other expressions. When working with
temporary arrays that are just needed for a single job and don't need a
persistent reference within the program, this is quite helpful.
Java supports the feature of an anonymous array, so we do not need to
declare the array while passing an array to the method.
Example
//Java Program to demonstrate the way of passing an anonymous array to m
ethod
public class Main{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<[Link];i++)
[Link](arr[i]);
}
public static void main(String args[]){
printArray(new int[]{10,22,44,66});//passing anonymous array to method
}
}
Output:
10
22
44
66
Explanation
In this example, the printArray method takes an integer array as a parameter
and prints each element of the array. In the main method, an anonymous
array {10, 20, 30} is directly passed as an argument to the printArray
method. This concise syntax demonstrates the usage of anonymous arrays in
Java, allowing for more streamlined code without the need for intermediate
variable declarations.
Returning Array from the Method
In Java, methods are not limited to returning simple data types or objects;
they can also return arrays. This feature allows for more flexibility in method
design and enables developers to encapsulate complex logic for generating
arrays within methods.
Example
//Java Program to return an array from the method
public class Main{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<[Link];i++)
[Link](arr[i]);
}
}
Output:
10
30
50
90
60
Explanation
The example demonstrates how to return an array from a method in Java
and subsequently use the returned array in the calling code. By
encapsulating array creation and initialization logic within the get method,
the code becomes more modular and reusable.
ArrayIndexOutOfBoundsException
In Java, the ArrayIndexOutOfBoundsException is a runtime exception thrown
by the Java Virtual Machine (JVM) when attempting to access an invalid index
of an array. This exception occurs if the index is negative, equal to the size
of the array, or greater than the size of the array while traversing the array.
[Link]
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=[Link];i++){
[Link](arr[i]);
}
}}
Output:
Exception in thread "main"
[Link]: 4
at [Link]([Link])
50
60
70
80
Multidimensional Array in Java
A multidimensional array in Java is an array of arrays where each element
can be an array itself. It is useful for storing data in row and column format.
Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in Java
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in Java
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
public class Main {
public static void main(String args[]) {
int arr[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; // 3x3 matrix
// Printing the 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](arr[i][j] + " ");
}
[Link]();
}
}
}
Output:
1 2 3
4 5 6
7 8 9
Explanation
This Java program initializes and prints a 2D array, representing a 3x3
matrix. Initially, a 2D array named arr is declared and initialized with values
using array initializer syntax. The array consists of three rows, each
containing three columns. The program then iterates through each row and
column of the array using nested loops. Within the loops, it prints the value
of each element, separated by a space. After printing all the elements of a
row, a newline character is printed to move to the next line. This process
continues until all elements of the array are printed. As a result, the program
outputs the 3x3 matrix with each element displayed in its respective row and
column.
These examples demonstrate the declaration, instantiation, initialization, and
traversal of both single-dimensional and multidimensional arrays in Java.