eli
eli

Reputation: 335

Confused regarding static variables?

 public class StaticVar {
 //example of a static method 
static int val=1024;//static variable 
//a static method
static int valDividedTwo(){
    return val/2;
}
}
 class SDemo{
public static void main(String[]args){
    //this is StaticVar.val which is equal to 1024
    System.out.println("Val is" +StaticVar.val);
    //thi sis the val/2
    System.out.println("StaticVar.ValDiv2 =" +StaticVar.valDividedTwo());
    StaticVar.val=4;
    System.out.println("val is "+StaticVar.val);
    System.out.println("val is "+StaticVar.valDividedTwo());
    System.out.println("val is "+StaticVar.val);
}
}

My question is for StaticVar.val=4; the first statment directly after System.out.println("val is "+StaticVar.val); the output is 4, obviously. Also it is also obvious why System.out.println("val is "+StaticVar.valDividedTwo());is 2 however, what is confusing me is that the statment afterwards System.out.println("val is "+StaticVar.val); is 4. As a static variable I would have expected it to be 2? What is going on here?

Upvotes: 0

Views: 57

Answers (1)

2ARSJcdocuyVu7LfjUnB
2ARSJcdocuyVu7LfjUnB

Reputation: 435

You are not changing the value of val with sysout. You are just performing a calculation and then printing the answer.

In order for the value of val to be changed, you would then need to set val equal to the your calculation, then print out the value.

Also this problem has nothing to do with it being static. You may want to look up the difference between "final" and "static", which in java can be confusing for newcomers.

Upvotes: 2

Related Questions