Static variable

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
Meghana
Posts: 29
Joined: Sun Feb 11, 2018 3:13 am
Contact:

Static variable

Post 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?

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Static variable

Post by admin »

What happened when you tried it out?
If you like our products and services, please help us by posting your review here.

Meghana
Posts: 29
Joined: Sun Feb 11, 2018 3:13 am
Contact:

Re: Static variable

Post 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.

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: Static variable

Post 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.
If you like our products and services, please help us by posting your review here.

Meghana
Posts: 29
Joined: Sun Feb 11, 2018 3:13 am
Contact:

Re: Static variable

Post 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!

Post Reply

Who is online

Users browsing this forum: Google [Bot] and 32 guests