Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

Explain ouput?

 
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

import java.util.Arrays;
class C
{
static void foo(Object... oa)
{
String s = Arrays.toString(oa);
System.out.println(s);
}
public static void main(String[] args)
{

C[] ca = new C[]{};
foo((Object)ca);
foo(ca);
foo(new C());
foo(null);
foo((Object)null);
foo((C[])null);
}
}

output:


[[LC;@7f5580]
[]
[C@1c6572b]
null
[null]
null


Explain this output?


Thanks in advance
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The three dots "..." in the argument of foo() indicate that this is a method with a variable number of arguments. When foo() is called, the argument oa will look like an array. You can pass this array to Arrays.toString() to neatly format it to a string, which looks like this:

[E1, E2, E3]

where E1, E2 and E3 are the elements of the array. So in this code example, foo() simply prints the arguments that are passed to it. Now let's look at the cases:

1. foo((Object)ca);

Here, oa is an array that contains one element: the array that you passed to it. When you convert that object to a string, you get [LC;@7f5580.

2. foo(ca);

Here, because ca is an array itself (and you didn't cast it to an Object explicitly as in case 1) oa is made equal to ca. Because array ca doesn't contain any elements, you only see [].

3. foo(new C());

Here, oa is an array that contains one C object. Calling toString on the C object results in C@1c6572b.

4. foo(null);

In this case, oa will become null. When you pass in null, Arrays.toString(...) returns the string "null".

5. foo((Object)null);

Now, oa is an array that contains one element, which is null.

6. foo((C[])null);

The same as case 4.
 
If I had asked people what they wanted, they would have said faster horses - Ford. Tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic