GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Object Reference Not Initialized Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Object Reference Not Initialized" Watch "Object Reference Not Initialized" New topic
Author

Object Reference Not Initialized

Brit Wright
Greenhorn

Joined: Aug 16, 2003
Posts: 3
Hello All:
What will be the output of the following code:
public class Book{
private String title;
public String getTitle() {
return title;
}
public static void main() {
Book b = new Book();
System.out.println("The title is " + b.getTitle());
}
}
The book I am reading says: The title is null
Does that mean, the default value of the class String is interpreted as string "null". Or, is there soem explicit conversion during the execution of + operator of the String class??
I thought the output should be: The title is
[ August 16, 2003: Message edited by: Brit Wright ]
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1871
hi Brit
all instance variables gets default initialization values.
-object ref = null
-int, long,short,double = 0
-boolean = false (i don recollect about char)
so ur String variable got initialized to null and so u get null in output. u'd get the output u expect if the string is "".
regards
maulin
Brit Wright
Greenhorn

Joined: Aug 16, 2003
Posts: 3
The default for char is '\u0000'.
Originally posted by Maulin Vasavada:
hi Brit
all instance variables gets default initialization values.
-object ref = null
-int, long,short,double = 0
-boolean = false (i don recollect about char)
so ur String variable got initialized to null and so u get null in output. u'd get the output u expect if the string is "".
regards
maulin
venu gopal
Ranch Hand

Joined: Nov 21, 2000
Posts: 40
Hi Brit,
Watch out this will generate runtime error???
public class Book{
private String title;
public String getTitle() {
return title;
}
public static void main(){ // public static void main(String args[])
Book b = new Book();
System.out.println("The title is " + b.getTitle());
}
}
Thanks,
Venu Gopal.
Alton Hernandez
Ranch Hand

Joined: May 30, 2003
Posts: 443
Hi,
You can refer to JLS 15.18.1 for a better explanation
 
GeeCON Prague 2014
 
subject: Object Reference Not Initialized