Reputation: 157
I read somewhere, while reading about the System.out.print
that in the System
class, there is a declaration of 'out' as a PrintStream
class type static variable as follows: public static final PrintStream out;
This invoked a question in me that what exactly happens if we just declare a variable of a certain class type and not initialize it by not calling any constructor? In above example 'out' is declared static and final, but I am looking for a generalized answer.
Upvotes: 1
Views: 1940
Reputation: 4039
When you create an object and store it in a variable, you don't actually store it. You only get a pointer to a specific memory address, where the object is currently located.
If you don't initialize an object, you get a null pointer. That object simply doesn't exist, there are are no fields or methods in it.
Static fields and methods are different, they aren't connected to an instance of an object, they're connected to the class (this is one of the many reasons using static is a bad practise). They can be accesed from anywhere at anytime.
Upvotes: 0
Reputation: 1499810
This invoked a question in me that what exactly happens if we just declare a variable of a certain class type and not initialize it by not calling any constructor?
Then like any other field, it starts off with its default value - which for references types (classes, interfaces, enums) is the null
reference. From section 4.12.5 of the JLS:
Every variable in a program must have a value before its value is used:
- Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
- For type
byte
, the default value is zero, that is, the value of(byte)0
.- For type
short
, the default value is zero, that is, the value of(short)0
.- For type
int
, the default value is zero, that is,0
.- For type
long
, the default value is zero, that is,0L
.- For type
float
, the default value is positive zero, that is,0.0f
.- For type
double
, the default value is positive zero, that is,0.0d
.- For type
char
, the default value is the null character, that is,'\u0000'
.- For type
boolean
, the default value isfalse
.- For all reference types (§4.3), the default value is
null
.
System.out
is a bit special - it's final, but can be changed via System.setOut
. I would try to avoid generalizing any other behaviour based on that.
Upvotes: 4