File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Variable initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Variable initialization" Watch "Variable initialization" New topic

Variable initialization

Deepali Pate
Ranch Hand

Joined: Mar 20, 2002
Posts: 114

Why doesnt this code give compile error that j is not initialized in givemeJ() method.
Amir Ghahrai
Ranch Hand

Joined: Jun 19, 2002
Posts: 110
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

Joined: Jul 03, 2001
Posts: 2120
JLS explains that. Field access expressions that ocurr whithin a method are not checked for forward references.

SCJP2. Please Indent your code using UBB Code
Alan Chong
Ranch Hand

Joined: Jun 05, 2002
Posts: 106
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

Joined: Jun 21, 2002
Posts: 56
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 ]

Let us be showered in the light of confusion!
Mandar Patki

Joined: Jun 27, 2002
Posts: 16
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

Joined: Jul 03, 2001
Posts: 2120
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.
I agree. Here's the link:
subject: Variable initialization
It's not a secret anymore!