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

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");

Related

java.lang.ArrayStoreException: when assigning value with incorrect type to Object[] array [duplicate]

This question already has answers here:
Why are arrays covariant but generics are invariant?
(8 answers)
Closed 4 years ago.
I come from a C background. It doesn't make sense to me that I can't add an Object to a Object[] in foo().
I would expect the code in function foo to work at runtime but fail in main() when I attempt to do strings[0].toLowerCase(); because the object in strings[0] is not a String but is actually a StringBuilder which doesn't have a toLowerCase(). At the end of the day, I am storing a pointer into an array of pointers and the line objects[0] = other should not be invalid. It is clear my understanding of java is wrong (but I an fairly new at the moment).
class Main {
static void foo(Object[] objects, Object other) {
objects[0] = other;
}
public static void main(String[] args) {
String[] strings = { "stringValue" };
foo(strings, new StringBuilder());
}
}
EDIT: Thanks all for the answer. I googled "java covariance of arrays" thanks to #Andy Turner and came across this which discusses this behaviour. The trick is that the compiler and runtime treat the code very differently. Compiler is fine with the code, runtime isn't.
From the documentation of ArrayStoreException:
Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. For example, the following code generates an ArrayStoreException:
Object x[] = new String[3];
x[0] = new Integer(0);
Just because you're passing a String[] into a method that expects an Object[] doesn't mean that it's actually an Object[]. Because you create a String[], you can only add instances of String to it, and you're trying to add a StringBuilder, which doesn't make sense.
Notice how it does not throw an exception if you change the type of String[] to Object[]:
public static void main(String[] args) {
Object[] strings = { "stringValue" };
foo(strings, new StringBuilder()); // Perfectly fine
}
It is evaluated at runtime that your String Array is in fact trying to assign a different type. You would an ArrayStoreException, which clearly says that
Thrown to indicate that an attempt has been made to store the wrong
type of object into an array of objects. For example, the following
code generates an ArrayStoreException:
Object x[] = new String[3];
x[0] = new Integer(0);
It is not generally a good practice to accept Object types as parameters or even return values of methods/functions. They could be polymorphic interfaces, but Object is at the highest levels of abstraction, and is not ideal for this purpose.
You are trying to add the Object "StringBuilder" to an Array of the object "String". Under some circumstances this might actually work, if you were to assign the StringBuilder Value but I am not to shure about that, as I never used this myself.
Here's a good read: https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
Usually Java takes care of pointers for you which makes it really hard to mess it up.
I hope I could help you :)

Convert an Object[] to a Class<?> type at runtime?

I am having deep trouble and this is advanced Java (I am using Reflection API).
Two questions.
I have the following:
Class<?> clazz = String.class;
Object[] values = new Object[] { "abc", 50L, 20 } // notice the different types
I want to be able to Object[] -> clazz[]. Why am I asking this? Because the type of "clazz" is known at runtime via reflection.
// This works
String[] params = Arrays.asList(values).toArray(new String[values.length]);
// This doesnt
String[] params = Arrays.asList(values).toArray(new clazz[values.length]);
There's something else: Let's say that, at runtime, the class is java.lang.String. In the middle of the creating of the array above, how can I use String.valueOf() on each element?
How can I achieve this?
Thank you!
Explaning more what I am trying to achieve
I have this class:
class A {
public void doIt(String... params) {
...
}
}
And also this class:
class B {
public void doIt(Long... params) {
...
}
}
As you can see, A and B have the same method doIt() but with different argument types.
I the code below will fail:
Object[] params = {1, 2, 3};
new A().doIt(params);
With the exception:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]
So, what I am trying to do, is find the type of doIt()'s first param and I am trying to convert Object[] to String/Long/Integer[]. Is is more clear now?
Skipping the comments on whether that kind of coding yields the best program, but answering your very question...
You cannot do new clazz[] as new in Java takes a class name, not an expression which evaluates to a Class object.
More pragmatically: new String[10] is not the same as new String.class[10]. The latter is what your example does. And is simply not supported.
You can do Array.newInstance(clazz, values.length), that seems like it would be what you are trying to do. But I don't see how it helps you. If the elements of the array are of different types, and you end up with an array of Strings (albeit dynamically created), you won't be able to put all of the elements into it anyhow.
Are you looking for Array.newInstance(Class<?>, int)? That's the way to reflectively build an array with a Class object rather than a compile-time type.
You cannot write new clazz[values.length], but you can write Array.newInstance(clazz, values.length).

passing a String array as argument

A String array can be declared and initialized in the following way:
String[] str = {"A", "B"};
but for a method which accepts a String array as argument, why can't the same be used there?
For example: if in the code below, i replace the call to show() from show(str); to show({"A" "B"});, it shows complier error. Why?
public class StringArray {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] str = {"A", "B"};
show(str);
}
static void show(String[] s) {
System.out.println(s[0] + s[1]);
}
}
The compiler errors shown are:
StringArray.java:9: illegal start of expression
show({"A", "B"});
^
StringArray.java:9: ';' expected
show({"A", "B"});
^
StringArray.java:9: illegal start of expression
show({"A", "B"});
^
StringArray.java:9: ';' expected
show({"A", "B"});
^
StringArray.java:9: illegal start of type
show({"A", "B"});
^
StringArray.java:11: class, interface, or enum expected
static void show(String[] s) {
^
StringArray.java:13: class, interface, or enum expected
}
^
7 errors
Also using show(new String[] {"A", "B"}); is allowed. How is new String[]{"A", "B"} different from {"A", "B"} when passing them as method arguments?
Thanx in advance!
The syntax {"A", "B"} (without new String[] in front of it) can only be used as an array initializer expression. In all other contexts (including method calls), you need to use the new operator.
See the Java Tutorial on Arrays for more info.
String[] str = {"A", "B"}; is minified version of String[] str = new String[]{"A", "B"};, Compiler doesn't know about plain {"A", "B"} as a string array unless you explicitly mention.
Short Answer
It has everything to do with memory management.
Long Answer
Background:
There is another question about passing arrays as arguments (marked as a duplicate) that is asking about the same behavior but is interested in a deeper 'why'.
Other answers have correctly explained the difference between
A)
new String[]{"A", "B"}
and
B)
{"A", "B"}
when passing them as method arguments.
A) constructs an instance of an array on the heap and the expression results in a reference to the instance.
B) is the syntax to define an array but that syntax is only valid during the initialization of a local array variable. This syntax is not an expression that can be evaluated by itself, it expects there to be an array already instantiated but uninitialized where this block is then used as the initializer.
Blame it on Java
All this has already been mentioned, so what I'd like to answer is the why behind the language design decision that puts this behavior in place.
One of the basic tenets of Java is that it manages memory to really minimize the huge problems that introduces when each programmer has to understand all the ins and outs, all the edge cases with dynamic memory management. So, when they designed the language's type system they would have liked to have every variable be a reference type but for efficiency they allowed some basic types that can be passed by value as an argument to a method, where the result is a simple clone of the contents of the variable, these are called primitive types, int, char, etc. All other types require a reference to the heap, which allows for good efficiency in parameter passing, these are called reference types. Reference types, as the name implies, are actually a reference to memory that has been allocated usually on the heap but can be memory on the stack.
Array Initializers
Ok, that's it for the Java Primer, but why is that important? It's because when you attempt to pass an array as in argument but use the literal syntax, the language expects a reference type but the array initializer construct does not resolve to a reference.
Now, the next question might be whether it would have been possible for the compiler to take the initializer syntax and transform it into a properly allocated instance of an array. That would be a fair question. The answer goes back to the the syntax that uses the initializer clause:
String[] str = {"A", "B"}
If you only have the expression on the right-hand-side of the equals sign, how do you know what type of array should be constructed? The simple answer is you don't. If we took that same initializer and used it like this
Circle[] cir = {"A", "B"}
it becomes more clear why this is the case. First you might notice the 'new' keyword seems to be missing. It's not missing but is implicitly being included by the compiler. This is because the initializer syntax is a short form of the following code
Circle[2] cir = new Circle[]();
cir[0] = new Circle("A");
cir[1] = new Circle("B");
The compiler uses the constructor for the array variable to instantiate each element of the array based on the list provided, So when you try to pass
{"A", "B"}
the compiler has no information about what type of array should be constructed nor does it know how to construct the individual elements of the array, hence the need to use the form that explicitly allocates memory.
For the Student of Languages
This separation between the type of the reference and the type of each element of the array is also what allows the array type to be a parent type of the elements, such as
Circle[2] shapes = new Circle[]();
shapes[0] = new Circle(); // parent
shapes[1] = new Ellipse(); // child of Circle
and Java's use of a parent class, Object for all classes allows arrays with completely unrelated objects
Object[2] myThings = new Object[]();
myThings[0] = new Car();
myThings[1] = new Guitar(); // unrelated object
When you pass {"A", "B"}, there is no object referencing to it because that array is not yet created in memory and that reference is needed to be passed.
But we can pass a string like "A" directly [without a reference] to a method accepting String, because String is java's special object for which String pool is maintained. and that is not the case with array which is like simple java object.
Since String[] str = {"A", "B"}; defines that it is an array of strings, {"A", "B"} nowhere says this is an array of string as an array of objects could be defined like that too, thus compiler doesn't know what type of array you are referring to :)
It works if you do it like this
public class StringArray
{
/**
* #param args
*/
public static void main(String[] args)
{
show(new String[]{"A", "B"});
}
static void show(String[] s)
{
System.out.println(s[0] + s[1]);
}
}
because you are actually creating a new array "object". The other way, {"A", "B"} doesn't mean anything. {"A", "B"} isn't an array object, so it won't work. The first way works because you are actually specifying that what is being passed to the function is an array object.
show({"A" "B"}); this expression is not passing array object. Passing array object You have to first declare and intialize the array object then passing array reference into method.
String[] str = {"A", "B"};
show(str);
OR
String[] str = {"A", "B"};
show(new String[]{"A", "B"});
In the above example, the signature of the show() method guides the compiler that it is expecting a String reference at the time of calling, thus we can pass only a reference variable of type String while calling the show() method. On the other hand {"A","B"} is just an expression not a reference that's why it is giving a compilation error like "Illegal Start of Expression".

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

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.

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.

Categories

Resources