• Post Reply Bookmark Topic Watch Topic
  • New Topic

Read that refernce variables are automatically assigned default value??  RSS feed

 
Vishal Hegde
Ranch Hand
Posts: 1078
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i just read that default values are assigned a default value and just wrote a simple program

class Demo
{
}
class TestD
{
public static void main(String args[])
{
Demo d;
System.out.println(d);
}
}

but it is giving error that d has not been initialised???
 
Priety Sharma
Ranch Hand
Posts: 156
Android Eclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to read again.

Member variables are assigned default values.
The variable declaration:


is a local variable to the main() method and it needs to be initialized before usage.
 
Greg Stevens
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the main method, after declaring d, no reference is assigned. So when you
pass d to println, and toString is called on d, there is no object to call the method on.

Perhaps you are thinking of instance variables, which are assigned a default
value (0 for integer types, false for boolean, and the null string for String).
 
Kapil Mishra
Greenhorn
Posts: 25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
default value assigned only for instance variables....not for method local variables....

in your code,d is local to main method.. and hence not initialized....if you declare that as class variable then it would be initalized to "null"..

like-

class TestD
{
Demo d;
public static void main(String ar[])
{
System.out.println(d); //print null
}


}
 
Vishal Hegde
Ranch Hand
Posts: 1078
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class TestD
{
Demo d;
public static void main(String ar[])
{
System.out.println(d); //print null
}


}

in this case isnt it necessary to make reference variable static
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
More precisely, default values are assigned to fields, both instance and static. Java Language specification.
 
Vishal Hegde
Ranch Hand
Posts: 1078
Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but instance variables are initialised when objects are created??
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Instance fields are initialised to their default values when an instance is created, yes, and you ought to initialise them properly in a constructor. The exception is final fields, which must be initialised once and once only, often in a constructor.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!