aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Variable Initialization Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Variable Initialization" Watch "Variable Initialization" New topic
Author

Variable Initialization

Snigdha Solanki
Ranch Hand

Joined: Sep 07, 2000
Posts: 128
Please see the following code
1.public class MyClass{
int i = 10;

public static void main(String[] arg){
int i = 20;
System.out.println("i is :"+i);
}
}
2.public class MyClass{
static int i = 10;

public static void main(String[] arg){
int i = 20;
System.out.println("i is :"+i);
}
}
3.public class MyClass{
static int i = 10;

public static void main(String[] arg){
static int i = 20;
System.out.println("i is :"+i);
}
}
4.public class MyClass{
int i = 10;

public static void main(String[] arg){
static int i = 20;
System.out.println("i is :"+i);
}
}
The output for case 1) and 2) is 20 and for case 3) and 4) the code doesn't compile. Can anyone please explain why?


Snigdha<br />Sun Certified Programmer for the Java™ 2 Platform
amol
Greenhorn

Joined: Aug 22, 2000
Posts: 3
if a variable or method is static it means that it is associated with the class and not an instance of a class. i.e. only one copy of that variable or method will exist for all the instances of that class in which this variable or method is defined.
any variable defined inside a method is local to that method.so we cannot define a member(class) variable inside a method.hope this is of some help to you
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
Also, you can access static variables from non-static methods but not the other way. ie., in order to access non-static variables from static methods you will need the instance of the class. Look out for this kind of questions in the actual exam!!
When you declare a local variable with the same name as the class variable, it "hides" the variable in the higher name-space. In your exaple (2), the variable 'i' declared within the main method hides the 'i' in the class-scope hence it prints 20.
Hope this helps,
Ajith


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Variable Initialization