Page 1 of 1
Static variable
Posted: Sun Feb 11, 2018 3:25 am
by Meghana
public class Test{
int i1;
static int i2;
public void method1(){
int i;
// line6
} }
Q1. Can a static field's value be changed to a non-static field's? Like, say by inserting the following code (at line6)?
this.i1=i2
Q2. Does this mean that the value of static variables can always be changed?
Re: Static variable
Posted: Sun Feb 11, 2018 3:38 am
by admin
What happened when you tried it out?
Re: Static variable
Posted: Sun Feb 11, 2018 4:56 am
by Meghana
I wasn't trying to run it. It was just a doubt I had in this question:
Given the following code, which statements can be placed at the indicated position without causing compile and run time errors?
public class Test{
int i1;
static int i2;
public void method1(){
int i; // ... insert statements here } }
This is one of the valid options:
this.i1=i2
So, I just wanted some clarity on reassigning static variables. I thought they could not be altered just as "final" variables can't be.
Re: Static variable
Posted: Sun Feb 11, 2018 6:52 am
by admin
1. I am not really sure what you mean by "reassigning" here. The statement this.i1=i2 simply assigns the value of the static variable i2 to the instance variable i1.
2. Since the value of i2 is not being changed, there is no question of it being altered in the above statement.
3. Now, regarding whether static variables can be altered, yes, they can be if they are not final.
The question have you have asked is really very basic and should have been cleared at this stage. I will suggest you to go through a good book to learn the basics before attempting mock exams.
Hope this clears your doubt but I would like to mention that we encourage students to show their effort by writing small test programs and posting the result that they got. This helps us understand the actual program and also discourages spoon feeding.
Re: Static variable
Posted: Wed Feb 14, 2018 10:59 am
by Meghana
Thank you so much. I understood. Yeah, the question was very basic I suppose.
I will try to run and then post from here on!