Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable Initialization

 
Snigdha Solanki
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
amol
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic