Quantcast

A community for students. Sign up today!

Here's the question you clicked on:

55 members online
  • 0 replying
  • 0 viewing

A.Avinash_Goutham

  • one year 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
    • one year ago
    Best Response
    You've already chosen the best response.
    Medals 0

    @rsmith6559 @slotema

  2. slotema
    • one year 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
    • one year 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
    • one year 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
    • one year 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

Ask a Question
Find more explanations on OpenStudy

Your question is ready. Sign up for free to start getting answers.

spraguer (Moderator)
5 → View Detailed Profile

is replying to Can someone tell me what button the professor is hitting...

23

  • Teamwork 19 Teammate
  • Problem Solving 19 Hero
  • You have blocked this person.
  • ✔ You're a fan Checking fan status...

Thanks for being so helpful in mathematics. If you are getting quality help, make sure you spread the word about OpenStudy.

This is the testimonial you wrote.
You haven't written a testimonial for Owlfred.