How do I check if a variable has been initialized
Posted
by Javier Parra
on Stack Overflow
See other posts from Stack Overflow
or by Javier Parra
Published on 2010-04-12T15:18:03Z
Indexed on
2010/04/12
15:23 UTC
Read the original article
Hit count: 244
java
First of all, I'm fairly new to Java, so sorry if this question is utterly simple.
The thing is: I have a String[] s made by splitting a String in which every item is a number. I want to cast the items of s into a int[] n.
s[0] contains the number of items that n will hold, effectively s.length-1. I'm trying to do this using a foreach loop:
int[] n;
for(String num: s){
//if(n is not initialized){
n = new int[(int) num];
continue;
}
n[n.length] = (int) num;
}
Now, I realize that I could use something like this:
int[] n = new int[(int) s[0]];
for(int i=0; i < s.length; i++){
n[n.length] = (int) s[i];
}
But I'm sure that I will be faced with that "if n is not initialized initialize it" problem in the future.
© Stack Overflow or respective owner