| Author |
a question about method local variables
|
amalip epa
Greenhorn
Joined: Mar 19, 2005
Posts: 7
|
|
k&b says always must be initialized before you attempt to use them. but i can't understand the answer of the below question public class Test{ publis statis void main(String args[]){ int age; age = age + 1; System.out.println("The age is" + age); }} the answer was Doesn't compile and i thought it wud print 1
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
|
On the fourth line, the value of "age" is read, 1 is added to that value, and the result stored back in "age". But when "age" is declared on the third line, no value is assigned to it. Therefore, it is uninitialized, and the code on the fourth line that tries to read the value won't compile.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Alan Jump
Greenhorn
Joined: May 25, 2005
Posts: 26
|
|
This won't compile because age was never initialized, only declared. If you try to make use of a declared variable before it's initialized you'll get a compile-time error. (Edited to correct typo in code) [ May 26, 2005: Message edited by: Alan Jump ] [ May 26, 2005: Message edited by: Alan Jump ]
|
 |
Nik Raut
Greenhorn
Joined: May 23, 2005
Posts: 22
|
|
|
And what about the default initialization to 0 for integers?
|
To be yourself is the best thing to be.
|
 |
Alan Jump
Greenhorn
Joined: May 25, 2005
Posts: 26
|
|
|
age was declared inside a method (i.e. local variable), so it doesn't automatically get a default value.
|
 |
 |
|
|
subject: a question about method local variables
|
|
|