Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why static varible in Java program not retaining its value?

I am calculating this java programme output…Here for first print statement….I get F….and after calling krinsh(c) metod….I get char c=190….According to ascII 190 represents 3/4…..and as c was declared as static its value should change to 190 and retain its value……so for second print statement I should get 3/4…..But when I execute the program I get F for both Print statement…..I tried to print c inside krish method but then I get 3/4……why am I not getting c=3/4 in the second print statement inside main method.

  public class Krish {
     static char c = 70;
     public static void main(String[] args) {
      Krish krish = new Krish();
      System.out.print(c + " ");
      krish(c);
      System.out.println(c);
     }
     static void krish(char c) {
       int cr = c;
       cr = cr * 2;
       cr = cr + c - 20;
       c = (char) cr;
     }
    }

output without print statement inside krish
output with print statement inside krish

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You have to set c in this way: Krish.c = (char) cr;, otherwise you’re setting the local variable in krish method instead of the static variable (Krish.c).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading