String[] files = {"a.doc, b.doc"}; VERSUS String[] files = new String[] {"a.doc, b.doc"};

M

Matt

What's the differences between the following:

String[] files = {"a.doc, b.doc"};
and
String[] files = new String[] {"a.doc, b.doc"};

I think similar question as:

String file = "a.doc";
and
String file = new String("a.doc");
 
W

Will Hartung

Matt said:
What's the differences between the following:

String[] files = {"a.doc, b.doc"};
and
String[] files = new String[] {"a.doc, b.doc"};
I think similar question as:

String file = "a.doc";
and
String file = new String("a.doc");

The difference is more like this:

public String getFile() {
String file = "a.doc";
return file;
}

String a = getFile();
String b = getFile();

In the first case, a == b, in the second, they don't.

With the arrays, I don't believe that Java will statically allocate the
array using the first technique.

Consider:

public String[] getFiles() {
String[] files = {"a.doc", "b.doc"};
return files;
}

String a[] = getFiles();
String b[] = getFiles();

If Java statically allocated the array, then you would see this:
a == b

If it creates the array anew with every method call, then they'd be
different.

Regards,

Will Hartung
([email protected])
 
J

Jesper Nordenberg

Will Hartung said:
With the arrays, I don't believe that Java will statically allocate the
array using the first technique. ....
If it creates the array anew with every method call, then they'd be
different.

Actually both statements produce exactly the same byte code which
creates a new array and fills it with String's. You can't have
String[]'s in the class file constant pool, only String's.

/Jesper Nordenberg
 
T

Tor Iver Wilhelmsen

String[] files = {"a.doc, b.doc"};
and
String[] files = new String[] {"a.doc, b.doc"};

The first variant can only be used non-method-local variable
declarations. It's a compiler thing: The resulting code is the same.
 

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

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top