wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes array of Vectors - null pointer exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array of Vectors - null pointer exception" Watch "array of Vectors - null pointer exception" New topic
Author

array of Vectors - null pointer exception

karl holmgren
Greenhorn

Joined: Aug 16, 2004
Posts: 4
I am getting a null pointer exception for the last line of code, why? Am I not allowed to put Vector objects in arrays?

import java.util.*;

private int noCh=1;
private Vector channels[];
.
.
.
private channels = new Vector[noCh+1];
.
.
.
if(channels[ch].size()>=sample && sample>-1){.....}

Thanks!
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by karl holmgren:
I am getting a null pointer exception for the last line of code, why? ...

I would need to see more of the code, but my guess is that channels[ch] is simply referencing a null value at some point (that is, there's no Vector object at the array index).
[ October 11, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi Karl,

Welcome to JavaRanch!

You are indeed allowed to put Vectors into arrays. Java is complaining because you haven't done so! The line

private Vector channels = new Vector[noCh+1];

allocates an array of Vector variables -- i.e, references to Vectors. There are no Vectors in the array, though -- all those variables are null. You have to actually allocate the Vectors:



Then you can call size() on them.

If this is confusing you, have a look at this and this.
[ October 11, 2005: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
karl holmgren
Greenhorn

Joined: Aug 16, 2004
Posts: 4
Thanks for the great answers!

When I fill the arrays with empty Vectors it works.
 
Don't get me started about those stupid light bulbs.
 
subject: array of Vectors - null pointer exception