This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes a question about method local variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "a question about method local variables" Watch "a question about method local variables" New topic
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: 24183
    
  34

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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: a question about method local variables
 
Similar Threads
Average age of Ranchers
Cookie.setMaxAge(-1), will the cookie expire after the browser is closed?
"does not compile" vs "compile time error"
cookie lifetime
Does not compile vs Compiles with Error? (John Hunt Mock Exam)