Ads

Friday, December 25, 2020

Create a class named "PrintNumber" to print various numbers of different datatypes by creating different methods with the same name "printn()" having a parameter for each datatype.

 


Here's an class named "PrintNumber" which contains different methods with the same name "printn()" but with different data types as parameters:

 

Here is the code to implement the scenario described

Source Code..


public class PrintNumber {

   

    // Method to print an integer

    public void printn(int num) {

        System.out.println("Integer: " + num);

    }

   

    // Method to print a float

    public void printn(float num) {

        System.out.println("Float: " + num);

    }

   

    // Method to print a double

    public void printn(double num) {

        System.out.println("Double: " + num);

    }

   

    // Method to print a long

    public void printn(long num) {

        System.out.println("Long: " + num);

    }

   

    // Method to print a boolean

    public void printn(boolean value) {

        System.out.println("Boolean: " + value);

    }

   

    // Method to print a string

    public void printn(String str) {

        System.out.println("String: " + str);

    }

   

    // Main method to test the class

    public static void main(String[] args) {

        PrintNumber obj = new PrintNumber();

        obj.printn(10);

        obj.printn(3.14f);

        obj.printn(3.14159);

        obj.printn(100000000000L);

        obj.printn(true);

        obj.printn("Hello, world!");

    }

}

 Code Explanation:

In this code, we define a class named "PrintNumber" which contains six different methods with the same name "printn()" but with different parameters (int, float, double, long, boolean, and String). Each method simply prints the value of the parameter with a corresponding data type label.

 

To test the class, we create an object of the class and call each method with different values. In the main method, we call "printn()" with an integer, a float, a double, a long, a boolean, and a string parameter respectively.

 

When we run the code, we should see the following output:

Integer: 10

Float: 3.14

Double: 3.14159

Long: 100000000000

Boolean: true

String: Hello, world!


This example demonstrates how we can define multiple methods with the same name but with different parameters in Java using method overloading. This allows us to write more concise and readable code by avoiding the need to use different method names for similar functionality


No comments:

Post a Comment