简体   繁体   中英

Passing string as a parameter in method overloading

package chapter3;
class MatchClass
{
    int x=0,y=0,z=0,res=0;
    float a=0,b=0,c=0,ress=0;
    String str=null;`enter code here`
    void add(int x,int y,int z)
    {
        res=x+y+z;
        System.out.println("Addition of integers="+res);
    }

    void add(float a, float b, float c)
    {
        ress=a+b+c;
        System.out.println("Addition of float values="+ress);
    }

    void add(String...str)
    {

        System.out.println("Concatenation of string="+str); 
    }
    public static void main(String ar[])
    {
        MatchClass ob=new MatchClass();
        ob.add(10,20,30);
        ob.add(3.5F,4.5F,6.0F);
        ob.add("Mountain","sick");

    }
}

here is the code that I have written and the output I am getting for string parameter that I have passed is quite ambiguous. Can someone please help me with a quick fix. PS- I want to use varagrs concept for passing string values.

I think the problem you're talking about is the output you get for the string function. Something like :

Concatenation of string=[Ljava.lang.String;@6d06d69c

At the line

System.out.println("Concatenation of string="+ str);

You're printing the variable "str" but "str" is not a string, it is an array and an array is an object. So, in order to be printed the function .toString() is called implicitly on "str". The problem here is the method Object.toString() does not print the content of the array but the object's type and reference inside the memory.

To print the content of the array the following will work (at least JDK8 required)

System.out.println("Concatenation of string="+ String.join(",",str)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM