• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt about arrays and object making with them  RSS feed

 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

Here i'm with a real noob question. I'm looking into arrays and i've this question: if i make an array, before i can use it, i've to make real objects from this array.

Example, if i've a 'Book' class, and then i make an array of 'Book', i've to make new objects for different indices, like aBook[0]=new Book();. That's ok, but if i simply make for example, an array of String, like String[] names = new String[4], then i simply assign values to the array this way: names[0]="Sam"; names[1]="Martin"; etc.

So the question is, why in the first case i've to make objects, and in the second case i don't use the same syntax? I think because typing names[0]="Sam" is like making a new object. But i prefer to ask you just to have a clearer idea about this.

Hope the question is clear :P

Thank you in advance for replies!
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would suggest you try array initialisers:-If you use an array initialiser in an assignment, rather than part of a declaration as shown above, you need to add new String[] or similar before the {. That way you will avoid nulls, which are potentially dangerous.As you know, an array is implicitly filled with nulls or 0s or false until you replace those values. [edit: additional] Using an array initialiser will make sure that the array is completely full, not half full, and that its size is exactly right to contain all the elements wanted. [/edit]

The difference with Strings is that you are using String literals. If you write "Sam" in Java® code, that actually constitutes a String instance in its own right. There was a discussion about literals only about a week ago. So you shou‍ld usually write "Sam" rather than new String(...).
Does that answer your question?
 
Junilu Lacar
Sheriff
Posts: 11481
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because it's a very common data type, String has somewhat of a special status in Java. It's the only reference type that I can think of that you can assign a literal value to.  You can do it with primitive wrapper classes but it involves autoboxing magic.  The String type is also the only reference type for which the "+" operator is overloaded to mean concatenation.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Campbell Ritchie: Yes, thank you, only doubt is about this sentence "If you use an array initialiser in an assignment, rather than part of a declaration as shown above, you need to add new String[] or similar before the {. That way you will avoid nulls, which are potentially dangerous.", i did not totally understood this. Can you explain this more clearly/deeply? :P

@Junilu Lacar: So i can use this easy syntax with primitives, right?

Thanks!
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try that. See what happens. See whether it would be any better if you change line 1 to String[] words = new String[3]; Now try the original version I showed you (minus lines 2‑5). Try as you will, you cannot get those Exceptions out of it. That array initialiser has four Strings in, and will always produce a 4‑element array. No risk of any errors like that. If you specify the length of the array yourself, there is a risk of not filling the array completely (so you have a null), or of trying to fit n elements into n − 1 spaces, when you get an out of bounds Exception. If you use an array initialiser and use the correct formats of loops, you will not get Exceptions out of arrays. You will never try to fill a 5‑length array with 4 elements, nor try to fill a 3‑length array with 4 elements.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Try that. See what happens. See whether it would be any better if you change line 1 to String[] words = new String[3]; Now try the original version I showed you (minus lines 2‑5). Try as you will, you cannot get those Exceptions out of it. That array initialiser has four Strings in, and will always produce a 4‑element array. No risk of any errors like that. If you specify the length of the array yourself, there is a risk of not filling the array completely (so you have a null), or of trying to fit n elements into n − 1 spaces, when you get an out of bounds Exception. If you use an array initialiser and use the correct formats of loops, you will not get Exceptions out of arrays. You will never try to fill a 5‑length array with 4 elements, nor try to fill a 3‑length array with 4 elements.

Copied the code in Notepad++, added main method but won't compile. There is an illegal start of expression, and missing ';'.
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ivan Addeo wrote:Copied the code in Notepad++, added main method but won't compile. There is an illegal start of expression, and missing ';'

Add comma at the end of line 8.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:
Ivan Addeo wrote:Copied the code in Notepad++, added main method but won't compile. There is an illegal start of expression, and missing ';'

Add comma at the end of line 8.

Did it, but i've errors about line 9: not a statement, and ';' expected.
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No errors for me. In the way Campbell showed it was just missing comma at the end of line 8. The rest is good.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ivan Addeo wrote:. . . Did it, but i've errors about line 9: not a statement, and ';' expected.
That just goes to show how difficult it can be for a compiler to find the correct error message. And sorry for the mistake.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:
Ivan Addeo wrote:. . . Did it, but i've errors about line 9: not a statement, and ';' expected.
That just goes to show how difficult it can be for a compiler to find the correct error message. And sorry for the mistake.

Sorry but, what's the point with this? I can't compile it, here the code:



Here are the errors:

 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:just missing comma at the end of line 8.

, - comma
; - semicolon
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:
Liutauras Vilda wrote:just missing comma at the end of line 8.

, - comma
; - semicolon


Ops :P thanks! it's ok now. I know the difference but, you know, why think on what you doing when you can do same error again and again? :P

Ok, so @Campbell Ritchie. So it's better to not say "an array of tot. elements", so i can avoid the problems you talking about. But, you say: That array initialiser has four Strings in, and will always produce a 4‑element array. No risk of any errors like that. So the best way to make array is with the notation:


But the question is, this code works toghether with this?:



Because you say this way i'll avoid nulls etc. but you say that it prints null. So surely i'm missing the point in this specific post.

 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't know what to quote of your (Ivan Addeo) last post.

What Campbell basically told, is next..

Instead of creating an array and separately initializing elements, i.e.:

Better is initialize that way (if elements are known at the beginning):

In this way you're not risking to leave some uninitialized elements, which would result in null pointers in this case. As you noticed, in first example last element which is at index position 3, 's[3]' left uninitialized, and trying to do some work with it could cause you a null pointer exception.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Liutauras Vilda wrote:Don't know what to quote of your (Ivan Addeo) last post.

What Campbell basically told, is next..

Instead of creating an array and separately initializing elements, i.e.:

Better is initialize that way (if elements are known at the beginning):

In this way you're not risking to leave some uninitialized elements, which would result in null pointers in this case. As you noticed, in first example last element which is at index position 3, 's[3]' left uninitialized, and trying to do some work with it could cause you a null pointer exception.

Thanks, this part is clear to me, the parts i've doubts about are, this sentence:

If you use an array initialiser in an assignment, rather than part of a declaration as shown above, you need to add new String[] or similar before the {. That way you will avoid nulls, which are potentially dangerous.

And then he writes this code:



He says that i'll avoid null, and then he says that this code will propt nulls. This is the part i'm not understanding :P




 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ivan Addeo wrote:He says that i'll avoid null, and then he says that this code will propt nulls. This is the part i'm not understanding :P

Lets leave for him to clarify what he exactly meant, but I'm sure he meant something meaningful
 
L Hasan
Greenhorn
Posts: 24
4
Eclipse IDE Java Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It sounds like he's trying to say, there would be situations where you declare and instantiate an array object, with a size, possibly without declaring all of it's elements. Whether this comes down to forgetting to init one, or all of the elements, or some later error in the code that prevents all elements in the array being initialised.

This might be fine for arrays of primitives where values are default initialised to 0, or false, but with Objects, trying to access a reference to a 'null' value could cause undesired effects.

If you use an array initialiser in a declaration, you will never have the problem of a null element. If you initialise using during assignment, these undesired effects may happen.

Hope that makes some sense,

L.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
L Hasan wrote:It sounds like he's trying to say, there would be situations where you declare and instantiate an array object, with a size, possibly without declaring all of it's elements. Whether this comes down to forgetting to init one, or all of the elements, or some later error in the code that prevents all elements in the array being initialised.

This might be fine for arrays of primitives where values are default initialised to 0, or false, but with Objects, trying to access a reference to a 'null' value could cause undesired effects.

If you use an array initialiser in a declaration, you will never have the problem of a null element. If you initialise using during assignment, these undesired effects may happen.

Hope that makes some sense,

L.


I'm a little confused right now, can you make an example of an array i. in a declaration and another one in an assignment?
 
L Hasan
Greenhorn
Posts: 24
4
Eclipse IDE Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey,

I'll break this down. Let's say you declare and instantiate an array object (with a preset size), and later assign the elements; you could end up in a situation like:



[Un]Luckily, in this case, the println() method will not complain, it will simply print "This" "is" "a" "null". In other applications though, this could be a serious flaw that won't be found until runtime.

This is why Campbell says it is better to use the array initialiser during the declaration phase:

String[] myStrings = {"This", "is", "a", "test"};

As we will always have an array, that is the appropriate fixed size (of 4 elements), to contain the number of elements we pass in. No chance for undesired effects.

Hope that helps,

L.
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
L Hasan wrote:Hey,

I'll break this down. Let's say you declare and instantiate an array object (with a preset size), and later assign the elements; you could end up in a situation like:



[Un]Luckily, in this case, the println() method will not complain, it will simply print "This" "is" "a" "null". In other applications though, this could be a serious flaw that won't be found until runtime.

This is why Campbell says it is better to use the array initialiser during the declaration phase:

String[] myStrings = {"This", "is", "a", "test"};

As we will always have an array, that is the appropriate fixed size (of 4 elements), to contain the number of elements we pass in. No chance for undesired effects.

Hope that helps,

L.


Yes, thanks That's ok for array i. during declaration.
But why i would have problems unsing array i. during assignment? What the sentence "If you initialise using during assignment, these undesired effects may happen" exactly means?
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no possibility to edit my post? Strange.

I think I understand, it that sentence we are not talking about array initilisers, but it's exactly the case you talking about in your code, right?
 
Knute Snortum
Sheriff
Posts: 4276
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no possibility to edit my post?

There is a small window in which you may be able to edit your post, but in general, you should just make another post -- as you did.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What a nice post You explained what I meant better than I could have.

Except you wrote
. . . if(canInit == true) . . .
Never use == true , or == false.
I have written about that many times. It is very error‑prone.
Use
if (b) ...
or
if (!b) ...
instead.
 
L Hasan
Greenhorn
Posts: 24
4
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:What a nice post You explained what I meant better than I could have.

Except you wrote
. . . if(canInit == true) . . .
Never use == true , or == false.
I have written about that many times. It is very error‑prone.
Use
if (b) ...
or
if (!b) ...
instead.


That's no problem, glad to be of assistance!

Could you tell me why it is error prone? My best guess is that you could mistakenly assign:



As opposed to comparing for equality:



L.
 
Liutauras Vilda
Sheriff
Posts: 4917
334
BSD
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
L Hasan wrote:My best guess is that you could mistakenly assign
Your best guess is correct 
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
L Hasan wrote:. . . Could you tell me why it is error prone? My best guess is that you could mistakenly assign:

. . . .
That is exactly what happens; we see it every now and again on this forum. Because Java® has got rid of the notion that 0 ≡ false and non‑0 ≡ true, there is no need for the C convention of writing
if (0 == i) ... or if (3 == i) ...
An assignment instead of == will produce a compiler error unless the left operand of the = is a boolean variable (or possibly a Boolean; I haven't checked for a very long time). It is only if you try to write == true or == false and put = instead by mistake that the compiler will fail to notice the error. IDEs will probably notice it; Eclipse will give a yellow mark (warning) for inappropriate assignment.
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:An assignment instead of == will produce a compiler error unless the left operand of the = is a boolean variable (or possibly a Boolean; I haven't checked for a very long time).

It will work with Boolean, too (since auto-unboxing was introduced).
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A few minutes ago, I wrote:. . . I haven't checked for a very long time. . . .
I have checked more recently. The following crappy code compiles and sets b2 to true:-
 
Ivan Addeo
Ranch Hand
Posts: 52
Android Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, thank you all for the replies! The argument is really more clear to me now
I'm going to tag the thread 'Resolved'.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!