1

The value of k is 0 when I run the following code:

public class Main {
    public static void main(String[] args) {
        A.Inner1 inner1_2 = new A.Inner1();

        System.out.println(inner1_2.getK());
    }
}

class A{
    private int j;
    public static class Inner1{
        private static int k;

        public int getK() {
            System.out.println("value:" + k);
            return k;
        }

        public void setK(int k) {
            this.k = k;
        }
    }
}

value:0
0

Jdk 1.8_181

This my comlier error or jvm error? I couldn't find an answer

Abdullajon
  • 366
  • 3
  • 12
  • 3
    _The value of k is 0..._ Why are you expecting it not to be zero? – B001ᛦ Aug 28 '19 at 13:16
  • 3
    The `int` fiield is initialized with a default value of `0` and you never change it, so this is all normal. – Arnaud Aug 28 '19 at 13:16
  • 1
    Seems like `k` isn't manually initialized anywhere by you. Whenever you have an `int` as a field, its value is automatically initialized to 0 when it's containing object is instantiated. – Austin Schaefer Aug 28 '19 at 13:16
  • 1
    What value would _you_ expect `k` to have? What should the output be in your opinion? – Thomas Aug 28 '19 at 13:22

3 Answers3

4

It is not an error, this is expected.

From the language spec, "Initial Values of Variables":

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):

  • ...
  • For type int, the default value is zero, that is, 0.
  • ...

k is a class variable, and you don't give it a value explicitly, so you will read its default value.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
2

This is because integers initialize with a default value of zero. In this instance, your k variable is never assigned a value so when it's returned the default (0) is returned.

B001ᛦ
  • 2,036
  • 6
  • 23
  • 31
  • It is not quite accurate to say integers initialize with a default value, if you use a local integer such as `int j;` and don't initialize it, you will find you will get an unresolved compilation problem when you attempt to use it. A _class_ variable of type `int` has a default value. – Nexevis Aug 28 '19 at 13:35
2

Every primitive type has a default value so when you wrote private static int k; the value assigned to the integer k is set by default to 0, and you never changed that value in your code, therefore it will output 0.

Daniel_Kamel
  • 610
  • 8
  • 29
  • 1
    It's not just primitive types. Reference-typed variables have a default value too, namely `null`. – Andy Turner Aug 28 '19 at 13:27
  • @AndyTurner correct and i never said anything about reference types since we're talking here about an ```int``` which is a primitive type, but thanks for pointing it out. – Daniel_Kamel Aug 28 '19 at 13:29
  • 1
    My point is that "Every primitive type has a default value" is unnecessarily qualified with "primitive". – Andy Turner Aug 28 '19 at 13:30