0% found this document useful (0 votes)
10 views23 pages

Java Method Overloading Examples

The document provides various Java programs demonstrating method overloading, including calculating areas of shapes, performing arithmetic operations, and checking properties of numbers. It includes multiple examples with different methods for calculating areas of rectangles and squares, as well as methods for printing patterns and checking lead and Niven numbers. Each program is accompanied by code snippets and explanations of their functionality.

Uploaded by

abhraneel2201
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)
10 views23 pages

Java Method Overloading Examples

The document provides various Java programs demonstrating method overloading, including calculating areas of shapes, performing arithmetic operations, and checking properties of numbers. It includes multiple examples with different methods for calculating areas of rectangles and squares, as well as methods for printing patterns and checking lead and Niven numbers. Each program is accompanied by code snippets and explanations of their functionality.

Uploaded by

abhraneel2201
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

PROGRAMS ON FUNCTION/METHOD

OVERLOADING

1) Program to calculate the area of a rectangle and


square using method overloading:

Ans: public class Rectangle


{
public double calculateArea(double length,
double width)
{
return length * width;
}

public int calculateArea(int side)


{
return side * side;
}
}

Output:

Topic: Method Overloading Programs Prepared by Ashwini Y.


Topic: Method Overloading Programs Prepared by Ashwini Y.
******************************************************************

OR
public class Rectangle
{
void calculateArea(double length, double width)
{
double area1= length * width;
[Link]("Area 1: "+area1);
}

void calculateArea(int side)


{
double area2= side * side;

Topic: Method Overloading Programs Prepared by Ashwini Y.


[Link]("Area 2: "+area2);
}
}
*****************************************************
Or
import [Link].*;

public class Rectangle


{
Scanner sc=new Scanner([Link]);

void calculateArea(double length, double width)


{
length=[Link]();
width=[Link]();
double area1= length * width;
[Link]("Area 1: "+area1);
}

void calculateArea(int side)


{
side=[Link]();
double area2= side * side;

Topic: Method Overloading Programs Prepared by Ashwini Y.


[Link]("Area 2: "+area2);
}
}
*****************************************************
Or
import [Link].*;

public class Rectangle


{
Scanner sc=new Scanner([Link]);

double calculateArea(double length, double width)


{
return length * width;
}

int calculateArea(int side)


{
return side * side;
}

public static void main(String args[])


{
Rectangle r = new Rectangle();

Topic: Method Overloading Programs Prepared by Ashwini Y.


double area1 = [Link](4.5,2.5);
[Link]("Area of rectangle: " + area1);

int area2 = [Link](5);


[Link]("Area of square: " + area2);
}
}
*****************************************************
Programs:

1)​ WAP using method overloading for the following:

void print(int a, int b): To swap 2 numbers using a


third variable.

void print(): To print


*
**
***
****
*****
*****************************************************

Topic: Method Overloading Programs Prepared by Ashwini Y.


2)​ WAP using method overloading for the
following:
void calculate(double a,double b): To calculate:
(a2+b2)/2ab
void calculate(): To print
1
23
456
7 8 9 10
**********************************************************

Topic: Method Overloading Programs Prepared by Ashwini Y.


Ans:
public class SeriesCalculator
{
void series(int x, int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum += [Link](x, i);
}
[Link]("Sum of the series x^1 + x^2 + ... + x^" +
n + " is: " + sum);
}

void series(int p)
{
for (int i = 1; i < p; i++)
{
int term = i * i * i - 1;
[Link](term + " ");
}
[Link]();
}

void series()
{
double sum = 0;
for (int i = 2; i <= 10; i++)

Topic: Method Overloading Programs Prepared by Ashwini Y.


{
sum += 1.0 / i;
}
[Link]("Sum of the series 1/2 + 1/3 + ... + 1/10
is: " + sum);
}
}
**********************************************************

Ans:
public class P2

Topic: Method Overloading Programs Prepared by Ashwini Y.


{
void print()
{
for(int i = 1; i <= 5; i++)
{
for(int j = 1; j <= 4; j++)
{
[Link](i + " ");
}
[Link]();
}
}

public void print(int n)


{
int digit = 0;
int evenSum = 0;
int oddSum = 0;

while( n != 0)
{
digit = n % 10;
if (digit % 2 == 0)
{
evenSum += digit;
}
else
{

Topic: Method Overloading Programs Prepared by Ashwini Y.


oddSum += digit;
}

n = n / 10;
}

if(evenSum == oddSum)
{
[Link]("Lead number");
}
else
{
[Link]("Not a lead number");
}
}
}
**********************************************************

Topic: Method Overloading Programs Prepared by Ashwini Y.


Ans:
public class P3
{
void display()
{
for(int i = 1; i <= 5; i++)

Topic: Method Overloading Programs Prepared by Ashwini Y.


{
for(int j = 1; j <= i; j++)
{
[Link](j + " ");
}
[Link]();
}
}

void display(int n)
{
while( n != 0)
{
double digit = n % 10;
[Link]([Link](digit));
n = n / 10;
}
}
}
**********************************************************
Q) WAP to define a class “compute” to overload the
method “print” as follows:

Topic: Method Overloading Programs Prepared by Ashwini Y.


void print(): to print the following pattern using
nested loop:
*
*#
*#*
*#*#
*#*#*
void print(int number): to accept a number and check
whether the number is a lead number.
A lead number is the one whose sum of even digits is equal
to the sum of odd digits.
e.g. 3669
odd digits sum = 3 + 9 = 12
even digits sum = 6 + 6 = 12
3669 is a lead number.

Ans: import [Link].*;


public class compute
{
void print()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{

Topic: Method Overloading Programs Prepared by Ashwini Y.


if(j%2==0)
{
[Link]("#");
}
else
{
[Link]("*");
}
}
[Link]("");
}
}
void print(int number)
{
Scanner sc = new Scanner([Link]);

[Link]("Enter a number: ");


number = [Link]();

int evenSum = 0;
int oddSum = 0;
int tempNumber = number;

// Calculate the sum of even and odd digits


while (tempNumber > 0)
{
int digit = tempNumber % 10;

if (digit % 2 == 0)
{

Topic: Method Overloading Programs Prepared by Ashwini Y.


evenSum += digit;
}
else
{
oddSum += digit;
}

tempNumber /= 10;
}

// Check if the sums are equal


if (evenSum == oddSum)
{
[Link](number + " is a lead number.");
}
else
{
[Link](number + " is not a lead number.");
}

}
}
—---------------------------------------------------------------------------------
Q) WAP to define a class “calculate” to overload the
method “display” as follows:
void display(): to print the following pattern using
nested loop:
1
22
Topic: Method Overloading Programs Prepared by Ashwini Y.
333
4444
55555
void display(int n): Check and display whether it is a
Niven number or not.
(A number is said to be Niven which is divisible by the
sum of its digits).
Example: Sample Input 126
Sum of its digits = 1 + 2 + 6 = 9
and 126 is divisible by 9.
Ans: import [Link].*;
public class calculate
{
void display()
{
for (int i=1;i<=5;i++)
{
for (int j=1;j<=i;j++)
{
[Link](i+" ");
}
[Link]("");
}
}
void display(int n)
{
Scanner sc = new Scanner([Link]);

Topic: Method Overloading Programs Prepared by Ashwini Y.


[Link]("Enter a number: ");
n = [Link]();

// Calculate the sum of the digits


int sumOfDigits = 0;
int tempNumber = n;

while (tempNumber > 0)


{
sumOfDigits += tempNumber % 10;
tempNumber /= 10;
}

if (n % sumOfDigits == 0)
{
[Link](n + " is a Niven number.");
}
else
{
[Link](n + " is not a Niven number.");
}

}
}

—--------------------------------------------------------------------
SOME OTHER PROGRAMS ON METHOD OVERLOADING:

Topic: Method Overloading Programs Prepared by Ashwini Y.


1) Program to calculate the area of a rectangle using method
overloading:
Ans: public class Rectangle
{
public double calculateArea(double length, double width)
{
return length * width;
}

public int calculateArea(int side)


{
return side * side;
}

public static void main(String[] args)


{
Rectangle rect = new Rectangle();

double area1 = [Link](4.5, 2.5);


[Link]("Area of rectangle: " + area1);

int area2 = [Link](5);


[Link]("Area of square: " + area2);
}
}

2) Program to perform addition using method overloading:


Ans: public class Addition
{

Topic: Method Overloading Programs Prepared by Ashwini Y.


public int add(int a, int b)
{
return a + b;
}

public double add(double a, double b)


{
return a + b;
}

public static void main(String[] args)


{
Addition ob = new Addition();

int sum1 = [Link](5, 7);


[Link]("Sum of integers: " + sum1);

double sum2 = [Link](3.14, 2.86);


[Link]("Sum of doubles: " + sum2);
}
}

3) Program to concatenate strings using method overloading:


Ans: public class StringConcatenation
{
public String concatenate(String str1, String str2)
{
return str1 + str2;
}

Topic: Method Overloading Programs Prepared by Ashwini Y.


public String concatenate(String str1, String str2, String str3)
{
return str1 + str2 + str3;
}

public static void main(String[] args)


{
StringConcatenation ob = new StringConcatenation();

String result1 = [Link]("Hello, ", "World!");


[Link](result1);

String result2 = [Link]("Java", " is", " awesome!");


[Link](result2);
}
}

4) Program to find the maximum of two numbers using method


overloading:
Ans: public class MaximumFinder
{
public int getMax(int a, int b)
{
return [Link](a, b);
}

public double getMax(double a, double b)


{
return [Link](a, b);
}

Topic: Method Overloading Programs Prepared by Ashwini Y.


public static void main(String[] args)
{
MaximumFinder ob = new MaximumFinder();

int max1 = [Link](5, 7);


[Link]("Maximum of integers: " + max1);

double max2 = [Link](3.14, 2.86);


[Link]("Maximum of doubles: " + max2);
}
}

5) Program to calculate the volume of shapes using method


overloading:
Ans: public class ShapeVolumeCalculator
{
public double calculateVolume(double radius)
{
return (4/3.0) * [Link] * radius * radius * radius;
}

public double calculateVolume(double length, double width,


double height)
{
return length * width * height;
}

public static void main(String[] args)


{

Topic: Method Overloading Programs Prepared by Ashwini Y.


ShapeVolumeCalculator ob = new ShapeVolumeCalculator();

double volume1 = [Link](3.5);


[Link]("Volume of sphere: " + volume1);

double volume2 = [Link](4.5, 2.5, 3.0);


[Link]("Volume of rectangular prism: "+ volume2);
}
}

******************************************************************************

Topic: Method Overloading Programs Prepared by Ashwini Y.

Common questions

Powered by AI

Method overloading improves code organization and readability by allowing similar operations to be grouped under the same method name, differentiated by parameters. For example, in calculating areas, the methods `calculateArea(double length, double width)` and `calculateArea(int side)` are used for rectangles and squares, respectively. This allows for intuitive operation invocation based on input types and arguments, reducing the need for developer memory overhead to recall different method names for similar tasks. Moreover, in pattern printing, the overloaded `print()` method handles both pattern output and numeric characteristics, centralizing function taxonomy within the class definition .

The program differentiates between overloaded methods by their parameter lists. In the context of printing patterns, there is a `print()` method without parameters and a `print(int number)` method with a single integer parameter. The `print()` method is designed to output a specific pattern using nested loops, while the `print(int number)` method evaluates whether the given integer is a lead number, checking if the sum of its even digits equals the sum of its odd digits. This differentiation allows for versatile functionality using the same method name, distinguished by the input types and their numbers .

A 'Niven number' is identified as a number divisible by the sum of its digits. The method `display(int n)` is overloaded to perform this check. It calculates the sum of the number's digits, then verifies divisibility by this sum. Method overloading supports this function by employing the `display` method in different contexts; one overload prints a pattern, another checks for a Niven number, without requiring different method names, thus allowing for easy reading and an organized presentation of related operations .

The program calculates the volume of different shapes by overloading the `calculateVolume` method with different parameter lists. For a sphere, the method `calculateVolume(double radius)` is used, which computes volume using the formula `(4/3) * π * radius^3`. For a rectangular prism, `calculateVolume(double length, double width, double height)` is used, which multiplies the three dimensions. This design choice is effective because it encapsulates related functionality within a single method name, each tailored to its specific geometric context, thereby enhancing code modularity and simplifying method invocation based on argument type and count .

The program utilizes method overloading for string concatenation by defining methods with the same name `concatenate` but differing in the number of string arguments. There are methods `concatenate(String str1, String str2)` and `concatenate(String str1, String str2, String str3)`, allowing concatenation of two or three strings respectively. The advantage of this approach is that it provides flexibility, allowing the user to concatenate different numbers of strings without the need for multiple function names, thus maintaining a clean and intuitive API for the class handling string operations .

Method overloading allows different methods in the same class to have the same name but differ in the type or number of their parameters. In the given context, method overloading is used to calculate the area of shapes without needing separate method names for different shapes. For instance, a method to calculate the area of a rectangle might take two double parameters (length and width), while a method to calculate the area of a square might take a single int parameter (side). This is implemented in the Rectangle class using methods `calculateArea(double length, double width)` and `calculateArea(int side)` .

The use of mathematical operations in overloaded methods exemplifies polymorphism as it allows objects to process data of different types through a single interface, exemplified by using a unified method name. For instance, the `calculateVolume` method is overloaded to compute volumes of either a sphere or a rectangular prism, depending on the number and type of arguments. This method polymorphism underlines polymorphic behavior where multiple forms of a method function adequately to fulfill different requirements, thus showcasing both compile-time and operational flexibility .

Method overloading facilitates performing different operations within the same class by allowing multiple methods with the same name but different parameters. This approach enhances code readability and usability as it reduces the need to remember different names for similar operations. For example, in the Addition class, overloading is used to perform addition on integers with the method `add(int a, int b)` and on doubles with `add(double a, double b)`. This allows for concise code where the desired operation can be inferred from the types of arguments provided .

Method overloading significantly enhances performing arithmetic operations by providing a flexible and intuitive method invocation system, where the operation type is inferred from input types. This is evident in the `add(int a, int b)` for integers and `add(double a, double b)` for doubles, allowing calculations to transcend basic operation constraints and extend functionality across different number types. This has broader implications in software development, such as simplifying the API, which in turn reduces potential for errors and enhances maintainability and scalability, as future enhancements can build on these overloaded methods without altering existing implementations .

The program identifies a 'lead number' as one where the sum of its even digits equals the sum of its odd digits. This is achieved in the method `print(int number)` by iteratively extracting digits from the number, classifying them as even or odd, summing each classification separately, and comparing the two sums. Method overloading is beneficial here because the same `print` method can also be used to perform entirely different tasks—displaying a pattern when no parameters are passed. This allows for a cleaner, more organized codebase where similar operations are grouped together, enhancing readability and reducing complexity .

You might also like