• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Constant Folding  RSS feed

 
lavnish lalchandani
Ranch Hand
Posts: 79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read that the code snippet

uses java compiler optimization technique ... constant folding i.e. the compiler precalculating constant expressions.
I am trying to understand

Will the above code use constant folding ?? As per my understanding "No" ..am i right ?

In the above code guess will also use constant folding .. right ?
 
Nitesh Kant
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Constant folding will be done for every final variable(static or instance variable)

In the examples you have given,



The above code will not use constant folding for length but do so for breadth.

and,


will use constant folding for breadth.

You can easily test what optimizations have the compiler done by decompiling the class file. Tools like cavaj gives a good UI to look at the decompiled classes. Also, there will be plugins for decompilers available for the ide you use.

P.S.: The deciding keyword is final and not static. So, even if your code was something like:

it would still have used constant folding.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, you can easily test this for yourself by compiling example code and then looking at the generated byte code using javap.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!