what is the initial value of arrays of object

G

George

I am using java 1.5.


class A{
A(){
}
A(int){
}
....
}

A[] a=new A[10];

For such an array, what is the initial value for each a[0]...a[9]?
null, null constructor, or something else? Is it specified by java or
varied from compilers? Can I create the array with other constructor
A(int)?

Thanks.
 
G

George

Thanks. Sorry for my un-standard word. By null constructor, I mean
the non-argument constructor. The problems for the books are they did
not specifies details like this.

Zhu, Guojun


George said:
I am using java 1.5.
class A{
A(){
}
A(int){
}
...
}
A[] a=new A[10];
For such an array, what is the initial value for each a[0]...a[9]?
null, null constructor, or something else?

     They are all null.  (I don't know what you mean by "null
constructor;" it's a term I've never seen before.)
Is it specified by java or
varied from compilers?

     It's part of the definition of Java.  Also, the compiler as
such has nothing to do with it: The array is created by the JVM
as it executes the `new' operator, and it's the JVM's business
to see to it that the array is null-filled.
  Can I create the array with other constructor
A(int)?

     No.  A factory method could do this, but the unaided `new'
operator cannot.  The closest `new' can come to something of this
kind is when you create multi-dimensional arrays:

        A[][] array = new A[5][10];

After this, array[0] through array[4] are not nulls, but references
to five arrays of ten A references each.  Those fifty A references
are all null, though.

     Read your Java textbook, if you have one.  If you don't, read
it anyway.  This is elementary stuff.
 
M

Mike Schilling

George said:
I am using java 1.5.


class A{
A(){
}
A(int){
}
...
}

A[] a=new A[10];

For such an array, what is the initial value for each a[0]...a[9]?
null, null constructor, or something else? Is it specified by java or
varied from compilers? Can I create the array with other constructor
A(int)?


It's the default value for the array's base type:

0 for numeric types (including char)
false for boolean
null for object reference
 
L

Lew

Thanks.  Sorry for my un-standard word.  By null constructor, I mean
the non-argument constructor.  The problems for the books are they did
not specifies details like this.

Please do not top-post.

For complete knowledge of such matters, the authority is the Java
Language Specification (JLS), 3rd edition for Java 5 and up.
<http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html>
in particular,
<http://java.sun.com/docs/books/jls/third_edition/html/
expressions.html#15.10.1>

It's a question of reading the right book.
 
R

Roedy Green

class A{
A(){
}
A(int){
}
...
}

A[] a=new A[10];

For such an array, what is the initial value for each a[0]...a[9]?
null, null constructor, or something else? Is it specified by java or
varied from compilers? Can I create the array with other constructor
A(int)?

That does not look like Java to me. To learn about array
initialisation, see http:://mindprod.com/jgloss/array.html
 
G

George

That does not look like Java to me. To learn about array
initialisation, see http:://mindprod.com/jgloss/array.html

Thanks for the link. It helps. It is a great site, I learned a lot
about enum there before.

But what do you mean that does not look like Java? The style or
something? I would like to be more java. How?
 
L

Lew

George said:
class A{
A(){

}
A(int){
}
...
}

A[] a=new A[10];

Roedy said:
That does not look like Java to me.
But what do you mean that does not look like Java?  The style or
something?  I would like to be more java.  How?

Aside from the lack of indentation, which Java doesn't require but
programmers do, there are several errors or questionable idioms.

- You defined a constructor 'A(int)' but left out the formal
parameter, e.g., 'A( int val )'.
- The class and all its methods have package-private access, not
forbidden but questionable.
- The array declaration and initialization occur outside the class.
- It's incomplete and uncompilable as it stands. Study up on SSCCE.
<http://sscce.org/>
 
Z

zerg

Eric said:
George said:
I am using java 1.5.


class A{
A(){
}
A(int){
}
...
}

A[] a=new A[10];

For such an array, what is the initial value for each a[0]...a[9]?
null, null constructor, or something else?

They are all null. (I don't know what you mean by "null
constructor;" it's a term I've never seen before.)

Probably the no-argument constructor.

It occurs to me that it might be somewhat-useful if Java added some
syntax (which wouldn't break source compatibility, I don't think) as a
shortcut for constructing multidimensional arrays and for initializing
arrays with all-identical elements other than zero, null, or false.

Proposed:

new X[x][y] -> an array of y X[] references, each pointing to a distinct
new X[x] instead of to null.

new X[x]() -> an array of x X references, each pointing to a distinct
new X().

new prim[x](value) -> an array of the appropriate primitive type, each
cell assigned the specified value (e.g. new int[10](1) would produce an
array of ten ints with the value 1 instead of the normal 0; new int[10]
would still produce an array of ten zeros of course).

new X[x](arg1, arg2...) -> an array of x X references, each pointing to
a distinct new X(arg1, arg2...)

new X[x][y](arg) -> an array of y x[] references, each pointing to a
distinct new X[x](arg) instead of to null; essentially, a
two-dimensional x by y array of x*y new Xs all constructed with the same
arg.

The usual rules would apply vis-a-vis overload resolution of
constructors, narrowing conversions, and so forth; indeed, all of the
above (and their obvious generalizations for more dimensions) would just
be short forms for

foo = argument_expression;
X[] temp = new X[x];
for (int i = 0; i < x; ++i) {
temp = new X(foo);
}

and suchlike. (Argument expression assigned to a temporary so if it has
side effects, they only occur once.)

The obvious optimizations would apply when the array is of primitives or
strings and the construction argument value is known at compile time,
and its evaluation known to lack side effects. Then

new int[10](1)

is simply short for the array literal

{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}

though it is perhaps a bit more readable (it's shorter, and the number
of 1s can be read off at a glance).

This sort of thing might not be used enough to justify the effort,
though, save perhaps for the not-infrequent case of initializing an
array of arrays with equal-sized subarrays (that is, making rectangular
two-dimensional arrays, or analogous structures in more dimensions).
 
Z

zerg

Eric said:

Is there a reason for dumping a large load of hostility into the
newsgroup? Generally speaking, there isn't much point posting if you
have nothing genuinely constructive to say.
 
R

Roedy Green

But what do you mean that does not look like Java? The style or
something? I would like to be more java. How

Try compiling it. The compiler will have quite a number of
complaints.
 
P

Patricia Shanahan

Eric said:
zerg said:
[...]
It occurs to me that it might be somewhat-useful if Java added some
syntax (which wouldn't break source compatibility, I don't think) as a
shortcut for constructing multidimensional arrays and for initializing
arrays with all-identical elements other than zero, null, or false.

Proposed:

new X[x][y] -> an array of y X[] references, each pointing to a
distinct new X[x] instead of to null.

Sorry, that syntax is already taken: it constructs an array
of x X[] references, each pointing to a distinct array of y X
references, all null.
....

I like initializer blocks as a very general solution to this class of
problem.

X[] myXArray = new X[y];
{
for(int i=0; i<myXArray.length; i++){
myXArray = new X();
}
}

int[] myInts = new int[10];
{
Arrays.fill(myInts, 1);
}

This solution avoids extra syntax, and yet keeps the full initialization
together, rather than spreading it between the declarations and the
constructor. It is far more powerful than any special case syntax could
be.

Patricia
 
M

Mike Schilling

zerg said:
Is there a reason for dumping a large load of hostility into the
newsgroup? Generally speaking, there isn't much point posting if you
have nothing genuinely constructive to say.

And here we thought you were back on your meds.
 
Z

zerg

(Peter has nothing worthwhile or Java-related to say, just personal slurs)

Peter, didn't your mother ever teach you any manners?
 
Z

zerg

(Lew had nothing worthwhile or Java-related to say)

Lew should find something more constructive to do than play "pick on the
new guy". This is neither the time nor the place for that sort of
childishness. Don't you have some actual Java related stuff to discuss?
 
Z

zerg

Peter said:
For controls, it's possible that the specific variations for each
control will be handled elsewhere (for example, you want a bunch of
buttons that are the same except for their text, which will be set
later). And for sockets, generally the binding that makes each instance
unique happens after initialization.

Thread pools.
Another example that comes to mind is related to Java's lack of
pass-by-reference.

What? Java has little EXCEPT pass-by-reference. Or do you mean for
primitive types? So, for instance arrays of mutable int-holders, which
(unlike int[] cells) would have individual references?

I can certainly imagine a method that requires an
initialized array of mutable objects to be passed to it, for the purpose
of allowing it to return values in those objects. Sure, one could
alternatively have the called method instantiate the objects, but
there's nothing mandatory about that.

And there may be design reasons not to do that -- such as to decouple
the method implementation from the code that decides what exact class of
objects to instantiate.
Heck, even your own post included an example like that, so I'm a bit
confused as your apparent claim that you can't think of examples like that.

That's not to say this sort of thing comes up often enough to justify
building a language feature around the scenario.

Keep in mind that the language feature would be "cheap" in several
senses: not breaking backwards source-compatibility, not really
complicating things too much, and not requiring much actual
implementation effort (in the simplest case, the existing compiler just
has a preprocessing stage prepended that basically does a form of
macro-expansion, with temporaries where necessary to prevent repetition
of expression side-effects of course).
But I think it should
be possible for anyone to recognize that it's at least hypothetically
possible to have code that could take advantage of that.

More than hypothetically. I don't know about you guys but I've
personally seen (and written) real, live, production code that could
have taken advantage of that, had it been available.
Your previous post mentioned a number of work-arounds, but that's surely
not the point. In Java, you can implement whatever functionality you
need.

I should certainly hope so. Ordinarily, one wants languages to be
Turing-complete, unless it's very special-purpose. Even some document
description languages seem to be Turing-complete.
The question is how simple it is to do so, and in thinking about
what features might be useful, being able to do something in an
alternative way isn't necessarily relevant to the question. After all,
there are a number of things in Java that are redundant with other Java
features, but which provide some recognizable benefit in elegance, speed
of development, etc.

Exactly. The relatively recently introduced collection-iterating "for"
loop is a good example. Even the + operator overload for strings, which
was there from the outset, more-or-less.

A few others I've thought might be nice include:

for (type x : coll) {
...
remove(x)
...
}

interpretation changed so that IF there is no method call resolution for
"remove(x)" it invokes the remove on the iterator that exists under the
hood. (Only applied if the argument expression is simply the reference
name for a loop variable that's in scope, not hidden, and from a new-for
loop rather than some other sort of loop.)

for (type1 x, type2 y : coll1, coll2) -- tandem iterations,
generalizable to three or more tandem iterations and stopping when the
smallest collection is exhausted.

typedefs with an optional boolean expressions that is a range
check/validator, and which create immutable value types:

typedef twoDigitInt = int {
this >= 0 && this <= 99;
}

typedef nonEmptyString = String {
this != null && this.length() > 0;
}

This one requires a new keyword, which impacts source compatibility.
Immutability of a reference-type base would be enforced: if any method
invoked on one of these tried to change a non-transient field, a runtime
exception would result, and the compiler would not accept code that
assigned a reference of the base type to a reference of the new type if
that reference was not the direct result of a new expression AND the
base type has non-transient non-final fields. This keeps mutable
references to the same object from being used to violate the range
constraint later. Range constraint tests would be evaluated once at
assignment time (with any side effects occurring then, the once) and a
false evaluation would result in an IllegalArgumentException or similarly.

public class Foo implements BarAlike {
Bar internal = ...;
delegate (internal) method1, method2, method3
}

Shorthand for Type1 method1 (args...) throws Ex1 {
internal.method1(args...); } and so forth. Would need a new keyword
"delegate" and would save a lot of boilerplate typing when implementing
some things using a delegate, or doing some other delegation based
patterns. One issue here is that "delegate" is a not-uncommon variable
name so the source compatibility issue is significant. Perhaps "punt",
which implies the same meaning and is a very rare variable name, instead?

synchronized { ... } as a shorthand for synchronized (this) { ... }
(with "this" being the class object if in a static context)

synchronized (foo, bar, baz) { ... } to synchronize on multiple
resources, with the locks acquired in order of the objects' physical
memory addresses (which the JVM knows, so this is possible, though not
without making a new JVM opcode perhaps). This acquires particular pairs
of locks always in the same order and helps prevent deadlocks, as well
as making conciser code in some cases. Doing the fixed-order thing
without such a language feature is possible, but difficult: the
resources need GUIDs of some sort assigned, that implement Comparable,
and you need an extended sort of Visitor pattern. Your resources need to
extend some class that has a private int guid field and a
receive(Visitor, List<Resource>) sort of method, with the latter being
something recursive like

synchronized (this) {
next = findMinBiggerID(list);
if (next == null)
visitor.visit(list);
else
next.receive(visitor, list);
}

so that the locks are acquired in ascending order of id and then
visitor.visit(list_of_resources) occurs.

What a pain...

The multi-synchronizer syntax added to the language would save some
projects one interface, one abstract class, several short but tricky
chunks of code that might harbor bugs, and method calls, comparisons,
container construction, stack frames, and suchlike per usage. The
performance difference if in a frequently used piece of code might be
considerable, even given the need for an under-the-hood temporary list
of references and sorting operation on same.
Rather, the real question is whether it would be useful, and whether it
would come up often enough to justify the feature. And sure, perhaps
it's infrequent. But it seems obvious to me that the scenarios do exist.

There's also the question of how high a burden of justification should
be needed. Depending on how much work would be involved, or how little,
and how easily backward compatibility could be maintained, the bar might
be higher or lower in each separate case.

Of all the things proposed in this thread so far, the multi-synchronize
is the only really complex one to implement and the only one that might
require changing the class file format, and even then could retain
source compatibility and probably binary compatibility. It's also the
one that is sometimes particularly hard to work around the lack of.

The ones involving new keywords break backwards source compatibility
mildly, can be done without breaking binary compatibility (typedef types
could exist as distinct types only at compile time, and delegates just
expand macro-like into the boilerplate they saved you typing), and are
also particularly useful-looking. Adding "remove" to new-for loops
doesn't actually make "remove" a keyword if done as described above.
Syntax-highlighting editors could color a "remove" they determine to act
as an iterator-remove specially, or as if it were a keyword, per the
developer's choice.

Anyone want any more examples or language-tweaking suggestions? :)
 
A

Andreas Leitgeb

zerg said:
Peter said:
Another example that comes to mind is related to Java's lack of
pass-by-reference.

What? Java has little EXCEPT pass-by-reference. Or do you mean for
primitive types? So, for instance arrays of mutable int-holders, which
(unlike int[] cells) would have individual references?

There is a subtle difference between the meaning of the english phrase
"call by reference" and the (seemingly deliberately defined) technical
term "call-by-reference".

There has been a long thread about this difference in the past, and it's
not neccessary nor worthwhile to drift the parent-thread's topic there
again.

I kindly ask everyone not to followup on this particular paragraph,
at least not without also adjusting the Subject.
 
Z

zerg

Andreas said:
zerg said:
Peter said:
Another example that comes to mind is related to Java's lack of
pass-by-reference.
What? Java has little EXCEPT pass-by-reference. Or do you mean for
primitive types? So, for instance arrays of mutable int-holders, which
(unlike int[] cells) would have individual references?

(Andreas' response to this is something vaguely insulting and imperious
in tone, rather than something constructive)

And what, exactly, is YOUR problem?
 
A

Andreas Leitgeb

Patricia Shanahan said:
I like initializer blocks as a very general solution to this class of
problem.
If you've devised some idiom for this kind of job, you effectively
agree to zerg, that there is indeed some use for that job. :)
X[] myXArray = new X[y];
{
for(int i=0; i<myXArray.length; i++){
myXArray = new X();
}
}


X[] myXArray = new X[y]();
int[] myInts = new int[10];
{
Arrays.fill(myInts, 1);
}

int[] myInts = new int[10](1);
This solution avoids extra syntax, and yet keeps the full initialization
together, rather than spreading it between the declarations and the
constructor. It is far more powerful than any special case syntax could
be.

Zerg's proposal avoids verbose wording and yet keeps the full
initialisation together with the declaration and the constructor
(provided that indeed the thusly construed items are what is
wanted). It is far more concise than calling Array.fill for
primitives or looping for Objects.

PS: where I disagree to zerg is, that I'd actually *want* the
multiple-evaluation and making use of possible sideeffects:

List<String> list=getStringList(); // just for context
Iterator<String> it=list.iterator(); // just for context
MyObj moArr=new MyObj[list.size()](it.next());

and have an array of MyObj's allocated and construed with
each element of an equally-sized Collection as the respective
array-element's constructor's argument.

or:
int i=0,ia[]=new int[N](i++);

But I do expect that others may find this abhorrently bad, so
I probably won't spend much of my energy in proposing it further.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top