Are String [] and String... (Var-args) same when they work internally? - java

class WrongOverloading{
void something(String [] a){ .. }
Integer something(String... aaa){ return 1;}
}
Above code does not compile! Compiler says these are duplicate methods.
So using String array or String var-args exactly mean the same?
How are they implemented internally?

They are effectively the same, except the compiler will not accept an varargs unless its the last argument and it won't allow you to pass multiple arguments to an array.
public void methodA(int... ints, int a); // doesn't compile
public void methodA(int[] ints, int a); // compiles
public void methodB(int... ints); // compiles
public void methodC(int[] ints); // compiles
methodB(1); // compiles
methodB(1,2,3,4); // compiles
methodC(1); // doesn't compile
methodC(1,2,3,4); // doesn't compile

From this SO discussion
The underlying type of a variadic method function(Object... args) is
function(Object[] args). Sun added varargs in this manner to preserve
backwards compatibility.
So, as every other answer has said, yes, they're the same.

String... aaa is just like having String[] aaa.
I am assuming that the semicolon after the second function is a typo...

Yes, it's the same.
You can read this article:
It is still true that multiple arguments must be passed in an array, but the varargs feature automates and hides the process.

yes, they are the same because when you call method with elipsis (String...) it converts to String array.

The compiler behind the scenes actually converts your var args method to a method with an array input.
This is the reason why you can have a var args method overloaded with an array as input because after compilation both of them will be identical.

Yes, both are the same ...
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html Just read this site, you will come to know

The [vararg] attribute specifies that the method takes a variable number of parameters. To accomplish this, the last parameter must be a safe array of VARIANT type that contains all the remaining parameters :
[vararg [, optional-attributes]] return-type function-name(
[optional-param-attributes] param-list,
SAFEARRAY(VARIANT) last-param-name);
The varargs syntax basically lets you specify that there are possible parameters, right? They can be there, or cannot be there. That's the purpose of the three dots. When you call the method, you can call it with or without those parameters. This was done to avoid having to pass arrays to the methods.
Have a look at this:
See When do you use varargs in Java?
final public class Main
{
private void show(int []a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
}
private void show(Object...a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
System.out.println("\nvarargs called");
}
public static void main(String... args)
{
int[]temp=new int[]{1,2,3,4};
Main main=new Main();
main.show(temp);
main.show(); //<-- This is possible.
}
}
It's for this reason, varargs is basically not recommended in overloading of methods.
System.out.printf(); is an example of varargs and defined as follows.
public PrintStream printf(String format, Object ... args)
{
return format(format, args);
}
format - A format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string. If there are more arguments than format specifiers, the extra arguments are ignored. The number of arguments is variable and may be zero. The maximum number of arguments is limited by the maximum dimension of a Java array as defined by the Java Virtual Machine Specification. The behaviour on a null argument depends on the conversion.

while calling a method it doesnt care about the return type it will consider the method name , number of parameters and type of parameters and order of parameters .here you are specifying a method with same name same parameters .bcoz in case of var arg if we call method with 2 parameters same method will be executed , if we call method with 3 parameters it will call same method .
here , if we call something(String [] a) and something(String... aaa) same method will be called .bcoz we can replace array with var-arg then a confusion will be arise wich method should be called. then method ambiguity will occour . thats why its showing duplicate method.
here if we pass array to var - arg parameter method it will be executed.internally it converts var - args to single dimensional array.

Related

public static void main(String args[]) why string args[] is compulsory ,why we not use public static void main(Object args[])?

why we not use Object args[] it can also hold any type of data.
class Demo {
public static void main(Object args[]) {
System.out.println("hello");
}
}
The main method receives its arguments from the command line, which in most (all?) OSes is string oriented. In other words, the information that Java will receive to call main, will already be in string form (and only string), so using Object[] for main would require programmers to add explicit casts to String each time they would want to use an argument as a string. Using String[] is therefor more logical, and leads to simpler code.
And of course, as Turing85 said in the comments, the legalistic point of view is that this is "because the JLS says so":
The method main must be declared public, static, and void. It
must specify a formal parameter (§8.4.1) whose declared type is array
of String.
Because you cannot pass an object via a command line argument.

Difference between var arg and array

Suppose I have a code like
public class HelloWorld {
public static String method1(String[] array){return ""+array.length;}
public static String method2(String... array){return ""+array.length;}
public static void main(String args[]) {
System.out.println(method1(new String[]{"test"})); //allowed
//System.out.println(method1("test")); Not allowed
System.out.println(method2(new String[]{"test"})); //allowed
System.out.println(method2("test")); //allowed
}
}
When I do javap HelloWorld
C:\Users\athakur\JavaProjectWorkspace\HelloWorld\bin\test>javap HelloWorld
Compiled from "HelloWorld.java"
public class test.HelloWorld extends java.lang.Object{
public test.HelloWorld();
public static java.lang.String method1(java.lang.String[]);
public static java.lang.String method2(java.lang.String[]);
public static void main(java.lang.String[]);
}
So as per the class file method1 and method2 take same array argument. Then why the difference in the input they can take?
Like method1 cannot take simple String input where as var arg can take variable String inputs as well as array?
So as per the class file method1 and method2 take same array argument.
Yes, except there's extra metadata within the class file to indicate that the parameter for method2 is a varargs parameter. It's really just an extra bit of data on the parameter - that's all.
You can detect it with reflection using Parameter.isVarArgs.
All it means is that the compiler is willing to take a call like this:
method2("test")
and implicitly convert it into
method2(new String[] { "test" })
You don't always want that behaviour, so it has to be explicitly specified on the parameter using the varargs syntax.
I suspect you're also using a slightly old version of javap, if it's not showing you the difference between the two method declarations. On my version (Java 8) I get:
public static java.lang.String method1(java.lang.String[]);
public static java.lang.String method2(java.lang.String...);
The only difference is signature of a method that might have a variable number of arguments, as opposed to an array argument you can pass only one argument. Anyway passing array to a method as vararg is accepted and will be used internally. On the other hand vararg arguments will be converted to an array and used there.
When you pass an array as argument to both method works. To answer you question lets don't use an array
System.out.println(method2("test")); //allowed
System.out.println(method2("test","test2")); //allowed
This works only if you use vararg argument, as you have noticed.

What is "String..." in java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
varargs and the '…' argument
Java, 3 dots in parameters
I saw this definition in my android java file.
It looks just like String[]. Are they different?
Thank you.
varags. If a method signature is method(Param param, String... x) it will take one Param type of object and any number of String objects.
There are couple if cool things about it:
It's nothing special. It's just sugared array. So, method(MyObject... o) is same as method(MyObject[] o).
Vararg has to be the last parameter in argument list.
There is this funny thing that bit me once. method(MyObject... o) can be called as method() without any compilation error. Java will internally convert the no-arg call to method(new MyObject[0]). So, be aware of this.
It's syntax for writing the items of the array as a parameter
for instance:
public String first (String... values) {
return values[0];
}
Then you can call this method with first("4","2","5","67")
The javacompiler will create an array of the parameters on its own.
It's a vararg, variable number of arguments. In the method body you treat it as a String[], but when you call the method you can either chose to supply a String[] or simply enumerate your values.
void foo(String... blah) { }
void bar() {
String[] a = { "hello", "world" };
foo(a); // call with String[]
foo("hello", "world"); // or simply enumerate items
}
Was introduced with Java 5.
It's for defining a method with a variable number of arguments.
String is a string type.
String[] is an array of strings.
String ... is a syntactic sugar named ellipsis, introduced in java 1.5 and taken from C. It can be used in methods definitions and actually the same as array with only one difference.
If method is defined as:
public void foo(String[] arg){}
you must pass array to it:
foo(new String[] {"a", "b"});
If method is defined as:
public void foo(String arg){}
You can call it either
foo(new String[] {"a", "b"});
or
foo("a", "b");

Method overloading using varargs in Java

The following code in Java uses varargs to overload methods.
final public class Main
{
private void show(int []a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
}
private void show(Object...a)
{
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+"\t");
}
System.out.println("\nvarargs called");
}
public static void main(String... args)
{
int[]temp=new int[]{1,2,3,4};
Main main=new Main();
main.show(temp);
main.show(); //<-- How is this possible?
}
}
The output of the above code is as follows.
1 2 3 4
varargs called
The last line main.show(); within the main() method invokes the show(Object...a){} method which has a varargs formal parameter. How can this statement main.show(); invoke that method which has no actual arguments?
main.show() invokes the show(Object... a) method and passes a zero-length array.
Varargs allows you to have zero or more arguments, which is why it is legal to call it with main.show().
Incidentally, I'd recommend that you don't embed \n in your System.out.println statements - the ln bit in println prints a newline for you that will be appropriate for the system you're running on. \n isn't portable.
The varargs syntax basically lets you specify that there are possible parameters, right? They can be there, or cannot be there. That's the purpose of the three dots. When you call the method, you can call it with or without those parameters. This was done to avoid having to pass arrays to the methods. For example, you can write:
main.show(1, 2, 3, 4);
That will also work, because the numbers will become objects in wrapper classes.
If you're still confused, take a look at this:
http://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
or this:
When do you use varargs in Java?
The main.show() call takes NO arguments, which is perfectly valid for matching the show(Object...a) method.

why primitive type will call first rather than wrapper classes?

public class A {
public void test(Integer i) {
System.out.println("In Wrapper Method");
}
public void test(int i) {
System.out.println("In primitive Method");
}
public static void main(String args[]) {
A a = new A();
a.test(5);
}
}
When I will call test method from main and pass integer argument, then it will call the method which accept primitive type as argument. I just want to know that why it call primitive type method rather than the method who accepts wrapper class as argument? Is there any rule, which java follow to call methods?
Thanks,
As a rough "rule of thumb", Java uses the closest matching method for the declared types of the argument expressions when choosing between different overloads. In this case test(int i) is closer than test(Integer i) when the method is called as test(5), because the latter requires a type promotion (auto-boxing) to make the actual argument type correct.
In fact the decision making process is rather more complicated than this, but the "rule of thumb" works in most cases.
In this case, you are using the literal value 5, which is a primitive int in Java. Any bare number literal such as that in Java is a primitive. To call the other method would require passing new Integer(5) instead. The autoboxing that was introduced in Java 5 can blur the lines between the two, but they are still distinct from each other.
Not really an answer, but when overloading it shouldnt matter which method is called. In this case calling either method if the value is an Integer or int the result should be the same. Overloading should only be used to convert values to some other form, or as a mechanism to provide defaults.
String.valueOf() is a good example of converting inputs to a String.
a.test(5) // test(int i)
Compiler understands it as a primitive type. If you want run the other method you should send
a.test(new Integer(5)) // test(Integer i)
because Java select the closest matching method to run
You have passed 5 as primitive type so it will call the method that accepts primitive so if you want to call the one that accepts 5 as object then you have to first covert it to object as below
int a = 5;
Integer b = new integer(5);

Categories

Resources