Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

A.Avinash_Goutham

  • 3 years ago

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?

  • This Question is Closed
  1. A.Avinash_Goutham
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    @rsmith6559 @slotema

  2. slotema
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 1

    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.

  3. A.Avinash_Goutham
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

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

  4. slotema
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 1

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

  5. A.Avinash_Goutham
    • 3 years ago
    Best Response
    You've already chosen the best response.
    Medals 0

    yup i did that too

  6. Not the answer you are looking for?
    Search for more explanations.

    • Attachments:

Ask your own question

Sign Up
Find more explanations on OpenStudy
Privacy Policy