• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

compile time constants

 
sakthi moorthy
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
package
sample;
public
class StaticVar {
/**
* @param args
*/
public static void main(String[ ] args) {
// TODO Auto-generated method stub
System.
out.println(x);
}
private static int x=getValue();
private static int y=5;
public static int getValue(){
return y;
}
}

how the output of program is 0 instead of 5 i think it may be of runtime constants can anyone explain the why the output is like that and what is runtime constants
 
Thirugnanam Saravanan
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
private static int x=getValue();

During this assignment, the value of static instance variable Y is 0 and is not initialized to 5. In the next line only you are initializing Y to 5. That's why the output is 0.

If the output should have been 5, then you have to initialize the Y value before you actually use that value. Refer the below code to get the Output of 5 :

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic