This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on local variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on local variables" Watch "Question on local variables" New topic
Author

Question on local variables

Nikhil Bansal
Ranch Hand

Joined: Jan 24, 2005
Posts: 60
Hi All,

This from Kathy Sierra Chp 2

" The key is to remember that a local variable must be initialized before you try to use it. The compiler will reject any code that tries to use a local variable that hasn�t been assigned a value "


What exactly does it mean

" before you try to use it."

For ex won't the compiler complain in the foll. code.

int i, j;
int k = 0;
j = 2;
k = j = i = 1;


Please post your inputs.

Regards

Nikhil Bansal


ban$al
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9345
    
    2

Hi Nikhil,

Your quote,

For ex won't the compiler complain in the foll. code.

int i, j;
int k = 0;
j = 2;
k = j = i = 1;


It means that you cannot use the uninitialized variable on the right hand side of the = operator. Now in the above code, the compiler interprets it as

k = j = i = 1 as k = (j = (i = 1)) and it works. As you can see that the variable i is not at the righthand side of the operator and by the time it comes to the right had side of the = operator, it already has the value set to 1.

Hope you got it.

Regards,
Jothi Shankar Kumar. S
[ November 01, 2006: Message edited by: Jothi Shankar Kumar Sankararaj ]

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18508
    
  40

What exactly does it mean

" before you try to use it."

For ex won't the compiler complain in the foll. code.

int i, j;
int k = 0;
j = 2;
k = j = i = 1;


Try...

int i, j;
int k = i + j;

For local variables, this shouldn't compile...

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question on local variables
 
Similar Threads
compile time constant expression
final variable
final variable declaration
complie time constants
Comma seperator for the FOR loop