There is a variable that is simply declared:
int a; And there is a need to check whether it has already been initialized. How can I do that?
There is a variable that is simply declared:
int a; And there is a need to check whether it has already been initialized. How can I do that?
As I know, Java, unlike C ++ languages ββand below, does not in itself initialize variables ...
Suppose if in C ++ you write: int a; and not to initialize it, after compiling and displaying on the screen, you can see that your variable was automatically initialized with a certain number taken from the main memory.
But in Java, as I know it is not. And if you try to use your non-initialized variable or object in conditions, the compiler will not compile your code, well, or throw a NullPointerException ... Therefore, so that being used to use it in conditions and so on, itβs better in advance set a constant to this variable or 0 but be 100% sure that this variable will never assign your constant or 0, and then check whether the variable has changed or not ...
Something like that:
int a = -999; //code //ΠΠ΅ΠΉΡΡΠ²ΠΈΡ Π½Π°Π΄ ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½ΠΎΠΉ a //code if(a != -999){ System.out.print("Π’Π²ΠΎΡ ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½Π°Ρ Π±ΡΠ»Π° ΠΈΠ·ΠΌΠ΅Π½Π΅Π½Π°!"); } Java Π² ΠΎΡΠ»ΠΈΡΠΈΠΈ ΠΎΡ ΡΠ·ΡΠΊΠΎΠ² Π‘++ ΠΈ Π½ΠΈΠΆΠ΅ ΡΠ°ΠΌ ΠΏΠΎ ΡΠ΅Π±Π΅ Π½Π΅ ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·ΠΈΡΡΠ΅Ρ ΠΏΠ΅ΡΠ΅ΠΌΠ΅Π½Π½ΡΠ΅ - it initializes, but not all. - post_zeewint default int will be initialized to 0, and the Integer to null. Because int is a simple type, and Integer is a class. - Igor Kudryashovint will be initialized manually int int = 0; - JVicYou have only one option that the variable will not be initialized: If it is an object variable and it is a class field. Then it will be enough to check for null. Primitive types, if they are class fields, will be initialized by default. If the variable is declared in code, the compiler will not allow you to work with it until you initialize it, in most cases
null is initialization too. - post_zeewSource: https://ru.stackoverflow.com/questions/583189/
All Articles
int a = 1234567;and if this is a value that cannot be assigned elsewhere in the program, then you can check - if this value is preserved - it means that nothing is assigned valos -. m vokhm.int a = 1234567;, and then check it, for me somehow a crutch, because there is any likelihood that in the future this value will be assigned. Thanks for the answer, I will try to avoid this problem altogether :) - Semyon Shnurkov