Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

a question about method local variables

 
amalip epa
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Alan Jump
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 22
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And what about the default initialization to 0 for integers?
 
Alan Jump
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
age was declared inside a method (i.e. local variable), so it doesn't automatically get a default value.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic