-1

I have following code:

String test = "Test" + System.currentTimeMillis();

When I print out this string several times it shows me exactly the same value.

System.out.println(test);
Thread.sleep(1000L);
System.out.println(test);

The result is following:

Test1591096276651
Test1591096276651

Why it didn't print result with difference in one second?

Is this JVM cache or something like that? How does variable initialization work? How does JVM know that it has been initialized and how to force it to reinitialize?

It would be great to read some documentation/specification to clarify why it works like it works.

Oleksandr Riznyk
  • 758
  • 1
  • 8
  • 19
  • 1
    When you write `System.out.println("Hello");`, it will also be executed only once. It’s not clear why you assume that this basic principle, that code does not get executed multiple times without any reason, could be violated for variable initializers nor why you think that adhering to the principle bears any obstacles to a JVM. – Holger Jun 02 '20 at 09:34
  • @Holger Sorry for unclear description, I mean if I execute it in loop it still will print the same value always – Oleksandr Riznyk Jun 02 '20 at 11:08
  • 2
    So you expect printing the contents of `test` to change the contents of `test`? – Holger Jun 02 '20 at 11:12
  • @Holger I consider two possible behaviours: 1. After first invocation result is cached/pulled into string pool or something like that and after future invocations it just refers to cached value 2. Each invocation goes to initialization line and recalculates – Oleksandr Riznyk Jun 02 '20 at 11:13
  • 1
    @Holger Okay, it is pretty stupid thinking that every usage of variable will reinitialize it :) – Oleksandr Riznyk Jun 02 '20 at 11:17
  • 1
    Reading a variable does never repeat evaluating its initializer. Further, the caches or string pools are irrelevant, as `String` is simply defined as a sequence of characters, not encapsulating an action that could be (re-)evaluated. In contrast to `Supplier s = () -> "Test" + System.currentTimeMillis(); System.out.println(test.get()); Thread.sleep(1000L); System.out.println(test.get());` – Holger Jun 02 '20 at 11:19
  • @Holger Yep, with lambda it is obvious :) Thanks a lot for your time – Oleksandr Riznyk Jun 02 '20 at 11:21

1 Answers1

-1

When you assign a value to variable it evaluate anything dynamic at that particular instance and doesn't re-evaluate it unless you assign it again.

String test = "Test" + System.currentTimeMillis(); print -- test test = "Test" + System.currentTimeMillis(); printe --test

Is there any specific requirement?