0% found this document useful (0 votes)
2 views

W3_Methodss

The document provides an overview of functions (methods) in Java, explaining their purpose, declaration, calling, and types, including predefined and user-defined methods. It covers method overloading, passing parameters, and the benefits of using functions such as reusability, neat code, modularization, and easy debugging. Additionally, it includes examples of various method types and a problem statement related to finding divisors and counting prime numbers.

Uploaded by

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

W3_Methodss

The document provides an overview of functions (methods) in Java, explaining their purpose, declaration, calling, and types, including predefined and user-defined methods. It covers method overloading, passing parameters, and the benefits of using functions such as reusability, neat code, modularization, and easy debugging. Additionally, it includes examples of various method types and a problem statement related to finding divisors and counting prime numbers.

Uploaded by

manichinniah94
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Function in Java

A function is a collection of statements or a block of code that is used to perform some


specific task. It is used to reuse the code without retyping the code. We can write the
function once and use it many times. We don’t need to write the code again and again. The
function is executed only when we call it. In Java, a function is also called a method.

Method Declaration in Java: The method declaration in Java provides information about the
method attributes, such as method name, method return type, method visibility, method
parameters, and the method body. Let’s look at the example of the method declaration:

public int max(int x, int y) {


// Method body
}
Here:
public: the public is a modifier.
int: int is a return type of method that means it returns an int value.
max: max is the name of the method.
int a, int b: int a, and int b is the list of parameters.

Example of Method Declaration: In this example, we declare a method that accepts two
parameters and returns a maximum of two numbers. Let’s look at the example:

public int max(int x, int y) {


if(x > y)
return x;
else
return y;
}

Method Calling in Java: Once we declare a method, we need to call this method to perform
some specific task. When we call a method, the program control transfers to the called
method. Let’s look at the example.

public class Example {

// Function to return a maximum of two numbers


public static int max(int x, int y) {
if(x > y)
return x;
else
return y;
}

// Driver Method
public static void main(String arg[]) {
int a = 10;
int b = 20;
// Method Calling
int maximum = max(a, b);
System.out.println(maximum);
}
}

How does function calling works?

Consider the following code where there is a function called findsum which calculates and
returns the sum of two numbers.

class Solution {
public static int findSum(int a, int b) {
int sum = a + b;
return sum;
}

public static void main(String args[]) {


int a = 10;
int b = 20;
int c = findSum(a, b);
System.out.println(c);
}
}

The function being called is called callee (here it is the findsum function) and the function
that calls the callee is called the caller (here, the main function is the caller). When a
function is called, program control goes to the entry point of the function. The entry point is
where the function is defined. So focus now shifts to the callee and the caller function goes
paused.

For Example: In the above code entry point of the function findSum() is at line number 3. So
when at line number 9 the function call occurs, the control goes to line number 3, then after
the statements in the function findSum() are executed, the program control returns to line
9.

Why do we need function?

1. Reusability: Once a function is defined, it can be used repeatedly. You can call the
function as many times as needed, which saves work. Consider that you are required
to find out the area of the circle. Now either you can apply the formula every time to
get the circle area or make a function to find the area of the circle and invoke the
function whenever needed.
2. Neat code: A code created with a function is easy to read and dry run. You don’t
need to type the same statements repeatedly; instead, you can invoke the function
whenever needed.
3. Modularisation: Functions help in modularizing code. Modularisation means dividing
the code into small modules, each performing a specific task. Functions allow doing
so as they are the program’s tiny fragments designed to perform the specified task.
4. Easy Debugging: It is easy to find and correct the error in a function compared to raw
code without a function, where you must correct the error everywhere the specific
task of the function is performed.

Types of Methods in Java


In Java, there are two types of methods:
1. Predefined Method
2. User-defined Method

Predefined Method
Predefined methods are the methods that are already defined in the Java class libraries. It's
also known as the built-in method or the standard library method. At any point in our
program, we can use predefined methods explicitly. Some predefined methods in Java are
sqrt(), max(), min(), round(), etc. These are defined inside the Math class. Some predefined
methods of String class are: length(), toUpperCase(), toLowerCase(), equals(), etc. Let’s look
at some examples using predefined methods.

Example 1: Find the maximum of two numbers using the built-in method.

public class MaxOfTwoNumbers {


public static void main(String args[]) {
// Maximum of two numbers using Math.max()
int maximum = Math.max(100, 30);
System.out.println(maximum);
}
}
Output:

100

Example 2: Find the minimum of two numbers using the built-in method.
public class MinOfTwoNumbers {
public static void main(String args[]) {
// Minimum of two numbers using Math.min()
int minimum = Math.min(100, 30);
System.out.println(minimum);
}
}

Output:
30

Example 3: Find the square root of a number using the built-in method.
public class SqrtOfNumber {
public static void main(String args[]) {

// Finding the square root of a number using Math.sqrt()


double sqrt = Math.sqrt(144);
System.out.println(sqrt);
}
}

Output:
12.0

Example 4: Find string length using the built-in method.


public class FindStringLength {
public static void main(String args[]) {
String str = "Coding Java";
// Printing string length using length()
System.out.println(str.length());
}
}
Output:
11

Example 5: Convert the string into the upper case using the built-in method.
public class UpperCaseString {
public static void main(String args[]) {
String str = "Coding Java";
// Printing upper case string using toUpperCase()
System.out.println(str.toUpperCase());
}
}
Output:
CODING JAVA
User-defined Method

The method written by the user or programmer is called the user-defined method. We can
modify these methods based on our requirements. Let’s discuss the user-defined method
with all four combinations of arguments and return type.

1. No argument(s) passed and no return value


When a function has no arguments, it doesn’t receive any data from the calling method.
Similarly, when it doesn’t return a value, the calling method doesn’t receive any data from
the called method.

Syntax:
Function declaration : void function();
Function call : function();
Function definition : void function()
{
Statements;
}

Example: In this example, we have created a method checkEvenOdd() and we don’t pass any
parameters to it. We simply write the code to check whether a number is even or odd as the
body of the function. If the number is even, we simply print “Even Number”, else we print
“Odd Number” and doesn’t return any value.

public class Solution {


// Function to check a number
// is even or odd
public static void checkEvenOdd() {
// Number to be checked
int num = 24;
if(num % 2 == 0) {
System.out.println("Even Number");
}
else {
System.out.println("Odd Number");
}
}

public static void main(String args[]) {


// Method Calling
checkEvenOdd();
}
}

Output:
Even Number

2. No arguments passed but return a value


There could be a requirement in our program where we may need to design a method that
takes no argument(s) but returns a value to the calling method.

Syntax:
Function declaration : int function();
Function call : function();
Function definition : int function()
{
Statements;
return x;
}

Example:
public class Solution {
// Function to return the
// sum of two numbers
public static int sumOfTwoNumbers() {
int a = 10;
int b = 20;
int sum = a + b;
return sum;
}

public static void main(String args[]) {


// No arguments passed in the method
int sum = sumOfTwoNumbers();
System.out.println(sum);
}
}

Output:
30

3. Arguments passed but don't return a value


In this example, we have created a method to check whether a number is even or odd. This
method doesn’t return any value but when we call this function we need to pass
argument(s) to it.

Syntax:
Function declaration : int function(int x);
Function call : function(x);
Function definition : int function(x)
{
Statements;
}

Example:
public class Solution {
// Method to check a number is even or odd
public static void findEvenodd(int num) {
if(num % 2 == 0) {
System.out.println("Even Number");
}

else {
System.out.println("Odd Number");
}
}

// Driver Method
public static void main(String args[]) {
int num = 24;
// argument passed in the method
findEvenodd(num);
}
}

Output:
Even Number

4. Arguments passed and do return a value


In this example, we have created a method that returns the sum of the two numbers and
accepts argument(s).

Syntax:
Function declaration : int function(int x);
Function call : function(x);
Function definition : int function(x)
{
Statements;
return x;
}

Example:
public class Solution {
// Function to return the sum of two numbers
public static int sumOfTwoNumbers(int num1, int num2) {
int sum = num1 + num2;
// Return sum
return sum;
}
public static void main(String args[]) {
int a = 10;
int b = 20;
// Method calling with arguments
System.out.println(sumOfTwoNumbers(a, b));
}
}

Output:
30

Passing Parameters to Methods

Pass by value in java:


The formal parameters are allocated to a new memory when the parameters are passed to
a function using the pass-by-value method. The value of these parameters is the same as
the value of the actual parameters. Changes in formal parameters would not represent
changes in individual parameters because they are assigned to the new memory.

Example:
public class Solution {
public static void increase(int x, int y) {
x++;
y = y + 2;
// x and y are formal parameters
System.out.println(x + ":" + y);
}

public static void main(String args[]) {


int a = 20;
int b = 10;
increase(a, b);
// a and b are actual parameters
System.out.println(a + ":" + b);
}
}

Output:
21:12
20:10

Changes in x and y values are not reflected in a and b in the above code because x and y are
formal parameters and are local to function increment; thus, any changes in their values
here will not impact variables a and b within the key function.
Method Overloading

Method overloading in Java is when a class has multiple methods of the same name but
different parameters. The main advantage of the method overloading is to increase the
readability of the program. Method overloading is related to compile-time polymorphism.
You will learn more about this in OOPs as well.

Ways to overload a method: There are two ways to overload a method in java
1. By changing the number of arguments.
2. By changing the data type.

Method overloading with changing the number of arguments.

In this example, we have created two methods; the first add() method performs the
addition of the two numbers, and the second add() method performs the addition of the
three numbers. Let’s look at the example.

public class Solution {

// Function with two parameters


public static int add(int num1, int num2) {
return num1 + num2;
}

// Function with three parameters


public static int add(int num1, int num2, int num3) {
return num1 + num2 + num3;
}

public static void main(String args[]) {

// Method calling by passing arguments


int sumOfTwoNumbers = Solution.add(10, 20);
int sumOfThreeNumbers = Solution.add(10, 20, 30);

System.out.println(sumOfTwoNumbers);
System.out.println(sumOfThreeNumbers);
}

Output:
30
60

Method overloading with changing the data type of arguments.


In this example, we have created two add() methods with different data types. The first
add() method takes two integer arguments and the second add() takes two double
arguments.

public class Solution {


// Function with two integer parameters
public static int add(int num1, int num2) {
return num1 + num2;
}
// Function with two double parameters
public static double add(double num1, double num2) {
return num1 + num2;
}

public static void main(String args[]) {

// Method calling by passing arguments


int sumOfTwoNumbers = Solution.add(10, 20);
double sumOfThreeNumbers = Solution.add(10.5, 20.5);

System.out.println(sumOfTwoNumbers);
System.out.println(sumOfThreeNumbers);
}

Output:

30
31.0

Problem statement
Given an integer ‘N’, your task is to write a program that returns all the divisors of ‘N’ in
ascending order.
Write a program to count the number of 1's in the binary representation of an integer.
Write a program to find the total number of a primes number in a given interval.
Given two integers S and E, count all primes between S and E.

You might also like