What is the initial value of declared var?

Hello!
I just starting programming in Java.
I am pretty good with JavaScript and PHP, but now learning Java.

So the question is, when I declare the instance variable like this:

int myNumber;

But don’t assign any value to it yet, what is the initial value?
The logic is that its value is assigned from one of the methods, but initially there is no value.
How can I test from one of the methods if the myNumber has been actual integer value?

Hye…in case of instance variables if we don’t giv any initial value to the variables then the default value 0 is taken for primitive types nd false for boolean types. It is necessary to assign any value to the instance variables unlike of local variables…

i also am starting in java so i found your question a must for me to answer :slight_smile:

in order to test you can use java classes of course: one to actually give you an instance variable:

/*
* InstanceVariable
* This class is used to give the initial value of
* an instance variable.
*/
public class InstanceVariable {
	int p;
	
	public void printIV() {
		System.out.print("p = " + this.p);
	}
}

and another to test it:

/*
* InstanceVariableTest
* This class is used to test the initial value of
* an instance variable.
*/
public class InstanceVariableTest {
	
	public static void main(String[] args) {
		InstanceVariable iv =  new InstanceVariable();
		iv.printIV();
	}
}

as for the integer value, you don’t have to worry about this in java. unlike javascript, java allows for a variable only the same type values you’ve initially declared for it. you need to explicitly cast a value in java in order to change it’s type.

Yeah, ignore that part :stuck_out_tongue:

Roz: He shoots, he scores!
FF: wth? (a null int? That’s unpossible)

For primitive types, byte, char, int, long they’ll default to 0 and boolean defaults to false. Any other Object will default to null. However this is only in the case of instance variables. If it’s a local variable and you don’t assign it a variable, the code won’t even compile. The compiler will tell you to initialize the variable.

null, since it hasn’t been initialized.

It’s good practice to initialize all your variables unless you have a good reason not to.

So for an int, depending on what you’re using it for, -1, 0, or 1 would be good values to choose from for initialization.