Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Integer type

 
Sneha Kapoor
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,



I thought answer would be 4 but answer is D

Can anyone please explain

Source : Whizlabs simulator

Thanks
 
Sagar Rohankar
Ranch Hand
Posts: 2907
1
Java Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rule : Instance class variables, if not initializes, assign null object and instance primitive variable, if not initialize, get assigned default (0) value.
 
Vijitha Kumara
Bartender
Posts: 3914
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


What this i refers to at runtime? That would give you the answer.
 
Sneha Kapoor
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks got it

I was null hence got null pointer
 
ram prabu
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

The primitive instance variable default value is 0 (if not explicitly declared).
int i;
now i value is 0

Wrapper instance variable default value is null. Because the wrapper is object

Integer i;

now i value is null

Now the answer is null pointer exception because you are adding (null+value). No way to add by this way.

Thanks
Ram
 
Till Stoschus
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi "ram prabu"

but the exception is thrown because the implicit Method call i.intValue() in "x = i+y;" refers on a null-value, right?

Till
 
ram prabu
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
yes till
we got null pointer exception when we are adding null with value.

Thanks
Ram
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic