Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is there an equivalent of Pascal's typed constants

In Delphi / Pascal there is a mechanism by which local variables in a method can remember a value from one method call to the next. This is done using typed constants. For example:

procedure blah();
const
  i: integer = 0;
begin
  i := i + 1;

  writeln(i);
end;

On each call to blah() i will increment. The output will look like:

1 2 3 4 5 ...

(each number on separate lines, but the editor here put them on the same line)

Is there an equivalent thing with Java?

like image 988
Michael Vincent Avatar asked Jun 04 '13 11:06

Michael Vincent


3 Answers

you can use static variables. which are initiated once on the first call. and on each call they save the latest value.

public class usingBlah{
    static int i = 0;

    void blah() {
        i++;
        //print here by Log.i or whatever
    }
}

here, like your code in delphi, i is defined on the first call and initiated. on the next calls it will save the latest value.

like image 104
amirelouti Avatar answered Sep 30 '22 23:09

amirelouti


May be static variables can help you.

Static variables are initialized just one time when the first instance of the class is being created. After that it stores the value.

like image 37
Vyacheslav Avatar answered Sep 30 '22 22:09

Vyacheslav


The closest equivalent in Java is a static variable of a class. That has static lifetime, but also has a wider scope than a Delphi assignable typed constant.

In Java there is nothing exactly like Delphi's rather quaintly named assignable typed constants that has local scope, but static lifetime. A static class variable is as close as you can get.

In C/C++ you could use a local variable with static storage duration, which has the same semantics as Delphi's assignable typed constants.

like image 34
David Heffernan Avatar answered Sep 30 '22 22:09

David Heffernan