[Go to site: main page, start]

0% found this document useful (0 votes)
14 views13 pages

Java Method

The document provides an overview of methods in Java, including their declaration, calling, and various concepts such as passing parameters, method overloading, and returning values. It explains the structure of method declarations, the significance of access modifiers, and how to pass parameters by value or reference. Additionally, it includes examples demonstrating method functionality, including passing objects and returning objects from methods.

Uploaded by

naresh paliwal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views13 pages

Java Method

The document provides an overview of methods in Java, including their declaration, calling, and various concepts such as passing parameters, method overloading, and returning values. It explains the structure of method declarations, the significance of access modifiers, and how to pass parameters by value or reference. Additionally, it includes examples demonstrating method functionality, including passing objects and returning objects from methods.

Uploaded by

naresh paliwal
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Methods in Java :

A method is a collection of statements that perform some specific task and return
the result to the caller. A method can perform some specific task without returning
anything. Methods allow us to reuse the code without retyping the code. In Java,
every method must be part of some class which is different from languages like C,
C++, and [Link] are time savers and help us to reuse the code without
retyping the code.

Method Declaration :
 Modifier-: Defines access type of the method i.e. from where it can be
accessed in your application. In Java, there 4 type of the access specifiers.
 public: accessible in all class in your application.
 protected: accessible within the class in which it is defined and in
its subclass(es)
 private: accessible only within the class in which it is defined.
 default (declared/defined without using any modifier) : accessible within
same class and package within which its class is defined.
 The return type : The data type of the value returned by the method or void if
does not return a value.
 Method Name : the rules for field names apply to method names as well, but
the convention is a little different.
 Parameter list : Comma separated list of the input parameters are defined,
preceded with their data type, within the enclosed parenthesis. If there are no
parameters, you must use empty parentheses ().
 Exception list : The exceptions you expect by the method can throw, you can
specify these exception(s).
 Method body : it is enclosed between braces. The code you need to be
executed to perform your intended operations.

Calling a method

The method needs to be called for using its functionality. There can be three
situations when a method is called:
A method returns to the code that invoked it when:
 It completes all the statements in the method
 It reaches a return statement
 Throws an exception
// Program to illustrate methods in java
import [Link].*;
class Addition {
int sum = 0;
public int addTwoInt(int a, int b){
// adding two integer value.
sum = a + b;
//returning summation of two values.
return sum;
}

class GFG {
public static void main (String[] args) {
// creating an instance of Addition class
Addition add = new Addition();

// calling addTwoInt() method to add two integer using instance created


// in above step.

int s = [Link](1,2);
[Link]("Sum of two integer values :"+ s);

}
}

Passing Parameters by Value


While working under calling process, arguments is to be passed. These should be
in the same order as their respective parameters in the method specification.
Parameters can be passed by value or by 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 example of passing parameter by value. The
values of the arguments remains the same even after the method invocation.
public class swappingExample {

public static void main(String[] args) {


int a = 30;
int b = 45;
[Link]("Before swapping, a = " + a + " and b = "
+ b);

// Invoke the swap method


swapFunction(a, b);
[Link]("\n**Now, Before and After swapping values
will be same here**:");
[Link]("After swapping, a = " + a + " and b is "
+ b);
}

public static void swapFunction(int a, int b) {


[Link]("Before swapping(Inside), a = " + a + " b
= " + b);

// Swap n1 with n2
int c = a;
a = b;
b = c;
[Link]("After swapping(Inside), a = " + a + " b =
" + b);
}
}
Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30

**Now, Before and After swapping values will be same here**:


After swapping, a = 30 and b is 45

Method Overloading
When a class has two or more methods by the same name but different
parameters, it is known as method overloading. It is different from overriding. In
overriding, a method has the same method name, type, number of parameters, etc.
Let’s consider the example discussed earlier for finding minimum numbers of
integer type. If, let’s 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 example explains the
same −
Example
public class ExampleOverloading {

public static void main(String[] args) {


int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);

// same function name with different parameters


double result2 = minFunction(c, d);
[Link]("Minimum Value = " + result1);
[Link]("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;
}
}
Output
Minimum Value = 6
Minimum Value = 7.3
Example: Return Value from Method

Let's take an example of a method returning a value.

class SquareMain {
public static void main(String[] args) {
int result;

// call the method and store returned value


result = square();
[Link]("Squared value of 10 is: " + result);
}

public static int square() {


// return statement
return 10 * 10;
}
}

Output:

Squared value of 10 is: 100


Example: Method Accepting Arguments and Returning Value

public class Main {

public static void main(String[] args) {


int result, n;

n = 3;
result = square(n);
[Link]("Square of 3 is: " + result);

n = 4;
result = square(n);
[Link]("Square of 4 is: " + result);
}

// method
static int square(int i) {
return i * i;
}
}

Output:

Squared value of 3 is: 9


Squared value of 4 is: 16

Passing arguments and returning a value from a method in Java


We can also pass more than one argument to the Java method by using commas.
For example,

public class Main {

// method definition
public static int getIntegerSum (int i, int j) {
return i + j;
}

// method definition
public static int multiplyInteger (int x, int y) {
return x * y;
}

public static void main(String[] args) {

// calling methods
[Link]("10 + 20 = " + getIntegerSum(10, 20));
[Link]("20 x 40 = " + multiplyInteger(20, 40));
}
}

Output:

10 + 20 = 30
20 x 40 = 800

Note: The data type of actual and formal arguments should match, i.e., the data
type of first actual argument should match the type of first formal argument.
Similarly, the type of second actual argument must match the type of second
formal argument and so on.
Java passing object as parameter:

Passing Object as Parameter :

class Rectangle {
int length;
int width;

Rectangle(int l, int b) {
length = l;
width = b;
}

void area(Rectangle r1) {


int areaOfRectangle = [Link] * [Link];
[Link]("Area of Rectangle : "
+ areaOfRectangle);
}
}

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
[Link](r1);
}
}

Output of the program :

Area of Rectangle : 200


Different Ways of Passing Object as Parameter :
Way 1 : By directly passing Object Name

void area(Rectangle r1) {


int areaOfRectangle = [Link] * [Link];
[Link]("Area of Rectangle : "
+ areaOfRectangle);
}

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle(10, 20);
[Link](r1);
}

Way 2 : By passing Instance Variables one by one

class Rectangle {
int length;
int width;

void area(int length, int width) {


int areaOfRectangle = length * width;
[Link]("Area of Rectangle : "
+ areaOfRectangle);
}
}

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
[Link] = 20;
[Link] = 10;

[Link]([Link], [Link]);
}
}

Actually this is not a way to pass the object to method. but this program will explain you how to pass
instance variables of particular object to calling method.

Way 3 : We can pass only public data of object to the Method.


Suppose we made width variable of a class private then we cannot update value in a main method
since it does not have permission to access it.

private int width;

after making width private –

class RectangleDemo {
public static void main(String args[]) {
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();

[Link] = 20;
[Link] = 10;

[Link]([Link], [Link]);
}
}
Java returning object

Returning the Object From Method


In Java Programming A method can return any type of data, including class types that you create.
For example, in the following program, the getRectangleObject( ) method returns an object.

Java Program : Returning the Object From Method

import [Link];
import [Link];
class Rectangle {
int length;
int breadth;

Rectangle(int l,int b) {
length = l;
breadth = b;
}

Rectangle getRectangleObject() {
Rectangle rect = new Rectangle(10,20);
return rect;
}
}
class RetOb {
public static void main(String args[]) {
Rectangle ob1 = new Rectangle(40,50);
Rectangle ob2;

ob2 = [Link]();
[Link]("[Link] : " + [Link]);
[Link]("[Link]: " + [Link]);
[Link]("[Link] : " + [Link]);
[Link]("[Link]: " + [Link]);

}
}

Output of the Program :

[Link] : 40
[Link]: 50
[Link] : 10
[Link]: 20

You might also like