Ask your own question, for FREE!
Computer Science 8 Online
OpenStudy (anonymous):

public class StaticChecker { public static void main(String[] args) { sChecker s1 = new sChecker(); } public class sChecker{ static int i =99; } } what is wrong with this piece of code?

OpenStudy (anonymous):

@rsmith6559 @slotema

OpenStudy (anonymous):

Java does not seem to like the use of an inner class in a static function. If you put the sChecker class in a separate file, it should work.

OpenStudy (anonymous):

yes that worked but the value of i is changed for both the objects :-/ public static void main(String[] args) { sChecker s1 = new sChecker(); sChecker s2 = new sChecker(); System.out.println(s1.i); System.out.println(s2.i++); System.out.println(s1.i); } Result:- 99 99 100 i am able to manipulate a class using an object !!!

OpenStudy (anonymous):

The fact that `i` is updated for both objects is normal. A static variable/method is independant of any object. It is a shared variable that can be accessed even without an object (as long as it's declared public. You can also access it with `sChecker.i`.

OpenStudy (anonymous):

yup i did that too

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!