Passing a Literal Array to a Method

K

KevinSimonson

Java lets one assign a literal array to a variable, and then pass the
variable
to a method. Why can't one just pass the literal array to the
method? For
example, I can write:

public class Bug
{
private static void processArray ( int number
, String[] strngArray)
{
System.out.println( "Number is " + number + '.');
for (int index = 0; index < strngArray.length; index++)
{ System.out.println
( "Array position " + index + " is \"" + strngArray[ index] +
"\".");
}
}

public static void main ( String[] arguments)
{
String[] sa = { "Abc", "Def" };
processArray( 7, sa);
}
}

and have my code work just fine, but if I try:

public class Bug
{
private static void processArray ( int number
, String[] strngArray)
{
System.out.println( "Number is " + number + '.');
for (int index = 0; index < strngArray.length; index++)
{ System.out.println
( "Array position " + index + " is \"" + strngArray[ index] +
"\".");
}
}

public static void main ( String[] arguments)
{
processArray( 7, { "Abc", "Def" });
}
}

and then compile it I get error messages:


sh-4.1$ javac Bug.java
Bug.java:15: illegal start of expression

processArray( 7, { "Abc", "Def" });

^

Bug.java:15: ';' expected

processArray( 7, { "Abc", "Def" });

^

Bug.java:15: illegal start of expression

processArray( 7, { "Abc", "Def" });

^

Bug.java:15: ';' expected

processArray( 7, { "Abc", "Def" });

^

Bug.java:15: illegal start of type

processArray( 7, { "Abc", "Def" });

^

Bug.java:17: class, interface, or enum expected

}

^

6 errors

sh-4.1$

Anybody know why this happens? Is there any way to pass a literal
array to a
method?

Kevin Simonson
 
K

KevinSimonson

Java need to know the type of the array before it can dispatch on it.
Is { "Abc", "Def" } an String[], CharSequence[] or Object[]? The answer
isn't obvious.

You can do what you want in Java, however, but the syntax is a little
more involved:

  processArray( 3, new String[] { "Abc", "Def" } );

Thanks Leif! This worked just fine!

Kevin Simonson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top