• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable initialization

 
Deepali Pate
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Why doesnt this code give compile error that j is not initialized in givemeJ() method.
 
Amir Ghahrai
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One possibility may be that the variable j is an instance variable not a local variable, and gets initialized to the default value of 0. Only local variables have to be explicitly initialized before they're used.
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JLS 8.3.2.3 explains that. Field access expressions that ocurr whithin a method are not checked for forward references.
 
Alan Chong
Ranch Hand
Posts: 106
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class Whatever { int i = 2; }
The above statement in C++ will just reserve a
int variable with an initial value of 2.
But in Java, the above statement reserves a int
variable with a value of 0. After the program
starts, 2 is assigned to i. It is a two-step job.
I got a question like this in JQPlus, and I answered wrong.
 
Chung Huang
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Um...could it be because j is an instance variable, and the method is also an instance member and so each object get a copy of j which the object can access. Since j is an instance member, it is initialized to default value of zero.
Correct me if I am wrong.
Let me modify this thing, j was initialized to 10 (or was it 20?). The rest is just that your j inside of the method is interpreted as j of the instance member which does exist, so no complain.
[ June 30, 2002: Message edited by: Chung Huang ]
 
Mandar Patki
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
I am preaparing for SCJP and I am finding Javaranch very useful for this. Lots of interesting discussions goes on here and help me to grasp the basics of Java. I am really thankful to all my new freinds here. I will try myself to get involve into discussions soon as I am revising my Java concepts.
Thanks once again,
-Mandar Patki
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wellcome to the Ranch Mandar!
Yes it is maybe the best resource in the net for the exam. It also helped me a lot when I took the exam.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic