Variable Assignment Having No Effect

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

Moderator: admin

Post Reply
Sweetpin2
Posts: 27
Joined: Thu Feb 07, 2013 9:46 pm
Contact:

Variable Assignment Having No Effect

Post by Sweetpin2 »

Hi,

For below code

public class Test_Assignment {

static int x;

public static void main(String[] args) {
int x = 10;
x = x;
System.out.println(x);

}

}

The code prints 10. Why the assignment x(local variable) = x(static variable initialized with 0) has no effect.

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

Re: Variable Assignment Having No Effect

Post by admin »

In your statement x = x; How will the compiler know which x is which?
So the rule is local variable x shadows the static variable x.
You should do x = Test_Assignment.x; if you want to assign the value of static x to local x.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 235 guests