Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if int is initialized? [duplicate]

How can I check if an int I declared has been initialized with a variable? number == null will not work because ints are primitive types.

This question is not relevant because the user asks how to check if the int is null, to which the answerer responds to use Integer. However, I want to check if the primitive data type int is initialized.

This question is also irrelevant because that is for a reference type whereas I'm asking for a primitive type. Already clarified -.- and still getting marked...

like image 411
Ishan_Arya Avatar asked Aug 03 '18 19:08

Ishan_Arya


People also ask

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 // ... } } It's not always necessary to assign a value when a field is declared.

How do you check if a variable has been initialized?

There is no way to check if a variable has been initialized in C++. Initialization should be ensured by a programmer. Modern compilers warn on potential attempts to access an uninitialized variable.

Is an int initialized to 0?

No difference - int members are initialized to zero by default.

What is the value of int if not initialized?

Solution. If a variable is declared but not initialized or uninitialized and if those variables are trying to print, then, it will return 0 or some garbage value.


1 Answers

Instance fields are initialized to null, 0, etc. Local fields are not initialized. There is no way to test for this, short of attempting to use the field and generating an exception. A good practice is to always initialize local variables when you declare them.

like image 54
Steve11235 Avatar answered Oct 01 '22 04:10

Steve11235