• Post Reply Bookmark Topic Watch Topic
  • New Topic

Variable declaration  RSS feed

 
Kamila Bertran
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok, this one seems to be the pretty basic one. I have this question on my practise test for Java exam:

Given:



Which line of code declares variable(s) so that the code fragment will compile?

I marked answer: int i1; as you don't really need to initialize it (it will be assigned default value 0 anyway).
but the correct answet was int i1 = 0;

why?
 
Kamila Bertran
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's a theory practice test for the course I'm doing.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66207
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kamila Bertran wrote:I marked answer: int i1; as you don't really need to initialize it (it will be assigned default value 0 anyway).

So sure of this, are you?
 
Kamila Bertran
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
could you elaborate?
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 66207
151
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kamila Bertran wrote:could you elaborate?


What compiler error do you get when you try to compile a class containing the following?
Does the text of the compiler error message contradict your assertion?
 
Kamila Bertran
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ha! I've been wrong all this time! But why??? If you don't initialize int it's going to be assign a default value 0. Is it because i1 is used to initialize i2 ? But why? Shouldn't compiler just assign 0 to i1 and than initialize i2 with i1 being 0? i1 is called first after all.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you know that there are two different kinds of variables in java? 

a variable can be local to a method, or it can be an instance variable.

They are treated differently.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16028
87
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only member variables are initialized implicitly if you don't explicitly initialize them. Local variables (inside a method) must be explicitly initialized.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!