Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a variable has been initialized

Tags:

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=1; i < s.length; i++){
    n[i-1] = (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.

like image 976
Javier Parra Avatar asked Apr 12 '10 15:04

Javier Parra


People also ask

How do you check if a variable has been initialized?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.

How do you check if a variable has been initialized C++?

There is no way in the C++ language to check whether a variable is initialized or not (although class types with constructors will be initialized automatically). Instead, what you need to do is provide constructor(s) that initialize your class to a valid state.

How do you check if an int is initialized?

For a field variable you can check by comparing the int to 0 that is the default value for an int field : private int x: // default 0 for an int ... public void foo(){ if (x == 0){ // valid check // ... } }

How do you check variable is defined or not?

The typeof operator will check whether a variable is defined or not. The typeof operator doesn't throw a ReferenceError exception when it is used with an undeclared variable. The typeof null will return an object. So, check for null also.


1 Answers

You can't cast a String to an int. Java is strongly typed, and there is no implicit type conversion like you might find in a scripting language.

To convert a String to an int, use an explicit conversion, like Integer.parseInt(String).

All member variables and elements of arrays are initialized with a default value. For int types, the value is 0. For reference types (any subtype of Object), the default value is null. Local variables don't get a default value, but the compiler analyzes the code to ensure that a value is assigned before the variable is read. If not, the code will not compile.

I think what you want is something like this:

int[] n = new int[Integer.parseInt(s[0]);
for (int idx = 0; idx < n; ++idx)
  n[idx] = Integer.parseInt(s[idx + 1]);
like image 139
erickson Avatar answered Oct 19 '22 07:10

erickson