Hi Rashad, welcome to CodeRanch!
Rashad Alik wrote:Basically, when I write something like int a = 5+5; and after watching bytecode generated with javap I see that 10 is pushed on the operand stack, so addition operation is skipped.
1. Can someone tell me why is this?
Because the compiler sees that you only use constants, so it can evaluate the expression ahead of time because the results will never change. This will save the JVM from having to execute the addition at every program run.
2. Instructions for both blocks are written, although else block will never execute. Why ?
I think the language designers figured that this situation is very rare in production code, and optimization doesn't lead to a big performance
boost, so it's more trouble than it's worth it to implement the improvement.
3. Now, question in general, is it viable option when building compilers, to create full interpreter (ala old ver. of ruby,basic and alike), execute program and output results (where appropriate) to bytecode instructions ?
For example, in above example write if block directly, skipping if instructions (ifeq), since they would be interpreted already ?
Output results in bytecode? So you're really building a translator/compiler, not an interpreter. Anyway, it won't work in general, because determining whether an expression always results in true or false reduces to the halting problem, and may cause your translator to run indefinitely.