Identify the state of variables in a Java program

RM777 :

This was homework and the task was to state which variables were visible at the points in the code marked *a*, ..., *e* and what value each one had. Can someone tell me if my solutions were right?

public class Zustand {
  public static void main(String[] args) {
    final int DIV = 24;
    int variable;
    int counter = 1;
    {
      // *a*
      variable = counter++;
      int y = 12;
      variable += y;
      counter++;
      // *b*
    }
    final double d;
    {
      counter = 4;
      double a = 10.0;
      {
        d = a + ++counter;
        // c
      }
      counter = 3;
      while (counter > 0) {
        counter--;
        a -= counter;
        // *d*
      }
    }
    variable = variable / DIV;
    // *e*
  }
}

First what variables are there? My answer to this is:

  • final int DIV
  • int variable
  • int counter
  • int y
  • final double d
  • double a

There are 6 variables for each *a*, ..., *e*. I will assign to the 6-tuple (DIV, variable, counter, y, d, a) another 6-tuple where the component of the tuple is either a number, the character w, or the symbol -. - means it is not visible. If it is a number it means that it is visible and the number is the value which is assigned to the variable. If it is the character w it means no value is assigned to the variable but it is visible.

So, this is my solution (is it right?). If something is wrong please give me a hint where my mistake could be.

  • *a* = (24,w,1,-,-,-)
  • *b* = (24,14,2,12,-,-)
  • *c* = (24,14,4,12,15,10.0)
  • *d* = (24,14,0,12,15,4.0)
  • *e* = (24,0,0,12,15,4.0)
Jin Lee :

if you use System.out.println, it will help you solve it!

public static void main(String[] args) {
    final int DIV = 24;
    int variable;
    int counter = 1;
    {
      // *a*
      variable = counter++;
      int y = 12;
      variable += y;
      counter++;
      // *b*
      System.out.println("y: " + y);            //  just an example

    }
    final double d;
    {
      counter = 4;
      double a = 10.0;
      {
        d = a + ++counter;
        // c
        System.out.println("d: " + d);             //  just an example

      }
      counter = 3;
      while (counter > 0) {
        counter--;
        a -= counter;
        // *d*
        System.out.println("a: " + a);                   //  just an example
      }
    }
    variable = variable / DIV;
    // *e*

    System.out.println("variable: " + variable);            //  just an example
    System.out.println("DIV: " + DIV);
    System.out.println("d: " + d);
    System.out.println("counter : " + counter);
}

In your console, you will see something like this.

y: 12
d: 15.0
a: 8.0
a: 7.0
a: 7.0
variable: 0
DIV: 24
d: 15.0
counter : 0

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related