How does the Date object update without recompiling the program in Java?

Caleb Suhy :

Example:

System.out.println(new Date());

Now obviously this is part of a larger program, but you can see what this does. Now, I run the compiler once, and then run the program. Then, without compiling the program again, I run it and the date updates. This might seem stupid but how does the date update without updating the bytecode?

From my understanding through what I have read the Java compiler takes my source code and compiles it to bytecode, which is saved in a class file. The JIT converts this code to machine code and it runs. However, wouldn't the state of the Date object stay the same? It obviously doesn't. I am just confused on how it changes.

Basil Bourque :

Compile-time versus Run-time

The Answer by Mureinik is correct. Objects defined in your code are constructed at run-time, not compile-time.

Compilation is like having an engineer review an architect’s plans for a building, and then writing out more detailed specifications. No building is yet built. We are now thoroughly ready to build, but have not actually built anything until “run-time” when the construction crew arrives on site.

In this metaphor, your source code is the architect’s drawings. The engineer’s more detailed specifications is the bytecode emitted by the Java compiler. The JVM running your app’s bytecode is the construction crew going to work on site.

Another way to think if it:

  • Classes are determined at compile-time.
  • Objects (instances) are determined at run-time.

java.time

Also, you should never use the Date class. That class and the other legacy date-time classes from the earliest versions of Java are terrible, riddled with poor design choices. They were supplanted years ago by the modern java.time classes.

The java.time classes use factory methods for instantiating rather than constructors and new.

Instant.now()  // Capture current moment in UTC. 
OffsetDateTime.now( ZoneOffset.UTC )  // Capture current moment in UTC. 
ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) )  // Capture current moment as seen though the wall-clock time used by the people of a particular region (a time zone). 
LocalDate.of( 2018 , Month.JANUARY , 23 )  // A date-only value, without time-of-day and without time zone. 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=95917&siteId=1