wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Qs about scope Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Qs about scope" Watch "Qs about scope" New topic
Author

Qs about scope

chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Could some one advise why compiler accept 2nd time " i " declaration on prog1 but object prog2 ?
thanks
chichih
class Prog1 {
int i;
{ int i;} //compiler accept 2nd time declaration of i

public static void main (String args[]) {
int i;

}
}
==================================================================
class Prog2 {
int i;
public static void main (String args[]) {
int i;
{ int i;} // compiler object 2nd time i declarationd
}


not so smart guy still curious to learn new stuff every now and then
Michael Ernest
High Plains Drifter
Sheriff

Joined: Oct 25, 2000
Posts: 7292

A class can have anonymous scope; methods can't, unless it's part of an inner class definition. In your second example, the second initialization of i would work if the code braces were "named," i.e., preceded by an if/while statement or some other constructs that labels the ensuing scope declaration.
------------------
Michael Ernest, co-author of: The Complete Java 2 Certification Study Guide
[This message has been edited by Michael Ernest (edited December 28, 2001).]


Make visible what, without you, might perhaps never have been seen.
- Robert Bresson
Raghav Sam
Ranch Hand

Joined: Apr 12, 2001
Posts: 412
Originally posted by chichih Lin:
Could some one advise why compiler accept 2nd time " i " declaration on prog1 but object prog2 ?
thanks
chichih
class Prog1 {
int i;
{ int i;} //compiler accept 2nd time declaration of i

public static void main (String args[]) {
int i;

}
}
==================================================================
class Prog2 {
int i;
public static void main (String args[]) {
int i;
{ int i;} // compiler object 2nd time i declarationd
}


In class Prog2, just try placing the code { int i;} before int i as in:

This is because the scope of i in line //1 ends with the block itself and the scope of i in line //2 starts to the right of the that line and extends for the remaining block.
In your example,

the scope of i in line //3 is the entire main method including, inside the block in line //4. That is why you get an error.
------------------
Raghav.


Be who you are and say what you feel, because those who mind don't matter and those who matter don't mind.<br />- Dr. Seuss
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Qs about scope
 
Similar Threads
Problem with Access modifiers
var initialization
Urgent Help.........
Output Not understand!!!
help with easy code