Pass long parameter to an overloaded method in Java


Method overloading in a class contains multiple methods with the same name but the parameter list of the methods should not be the same. One of these methods can have a long parameter in their parameter list.

A program that demonstrates this is given as follows −

Example

 Live Demo

class PrintValues {
   public void print(int val) {
      System.out.println("The int value is: " + val);
   }
   public void print(long val) {
      System.out.println("The long value is: " + val);
   }
}
public class Demo {
   public static void main(String[] args) {
      PrintValues obj = new PrintValues();
      obj.print(15);
      obj.print(8L);
   }
}

Output

The int value is: 15
The long value is: 8

Now let us understand the above program.

The PrintValues class is created with two methods print() in the implementation of method overloading. One of these takes a parameter of type int and the other takes a parameter of type long. A code snippet which demonstrates this is as follows:

class PrintValues {
   public void print(int val) {
      System.out.println("The int value is: " + val);
   }
   public void print(long val) {
      System.out.println("The long value is: " + val);
   }
}

In the main() method, object obj of class PrintValues is created and the print() method is called two times with parameters 15 and 8L respectively where the former is an int value and the latter a long value. A code snippet which demonstrates this is as follows:

public class Demo {
   public static void main(String[] args) {
      PrintValues obj = new PrintValues();
      obj.print(15);
      obj.print(8L);
   }
}

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements