Search code examples
javaboolean-expressiontype-mismatch

why would you want to declare a true false variable as type int?


The code below is from one of the classes in a SDK jar I'm using in my app. How did it compile with int as the type for the indexSize, bestWidth, etc. below?

        config = this.mCamera.getParameters();
        int indexSize = false;
        int bestWidth = false;
        int bestHeight = false;
        int maxRes = false;
        ZZZCLog.d("Camera supported sizes");
        List<Size> supportedSizes = config.getSupportedPreviewSizes();

        for(int i = supportedSizes.size() - 1; i >= 0; --i) {
            ZZZCLog.d(((Size)supportedSizes.get(i)).width + " " + ((Size)supportedSizes.get(i)).height + " aspect ratio: " + (double)((Size)supportedSizes.get(i)).width / (double)((Size)supportedSizes.get(i)).height);
        }

        config = this.mCamera.getParameters();
        ZZZCLog.d("Default preview size: " + config.getPreviewSize().width + "," + config.getPreviewSize().height);
        Size bestSize = this.getBestPreviewSize(config, width, height);
        int bestWidth = bestSize.width;
        int bestHeight = bestSize.height;
        ZZZCLog.d("Requesting preview size: " + bestWidth + "," + bestHeight);
        config.setPreviewSize(bestWidth, bestHeight);
        config.set("video-size", "" + bestWidth + "x" + bestHeight);

Solution

  • You can't trust decompiled Java code.

    Internally, Java bytecode treats booleans as integers. You can compile this class:

    class Test {
        public void foo() {
          boolean myBoolean = false;
        }
        public void bar() {
          int myInt = 0;
        }
    }
    

    And then examine the javap -c Test output:

    public void foo();
    Code:
       0: iconst_0
       1: istore_1
       2: return
    
    public void bar();
    Code:
       0: iconst_0
       1: istore_1
       2: return
    

    As you can see, the int and boolean become the exact same code.

    A decompiler will try its best to reconstruct valid source code from the stack based bytecode, but it's a hard problem even for unoptimized code with debug info, so it doesn't always get it right.