0

I'm just asking if different ways of writing a code is compiled differently or the same.

So if i have something like this: ("object" being the class name)

object o = class.getMethod();
if(o != null){
    if(o.get() != null){
        //do whatever....
    }
}

Would it be the same as this?

if(class.getMethod().get() != null){
    //do whatever...
}

When code is compiled like would they both be exactly written the same in bytecode. I heard that while(true) and while(1==1) would be the same in bytecode as they are going to be while(true).

krsteeve
  • 1,794
  • 4
  • 19
  • 29
  • 2
    You know you could always just [take a look at the bytecode yourself](http://stackoverflow.com/questions/3315938/is-it-possible-to-view-bytecode-of-class-file) ;) – Oliver Charlesworth Aug 28 '13 at 12:17
  • 1
    javap -c YourClass.class – Keith Aug 28 '13 at 12:20
  • 1
    Bytecode in general is not very relevant, it's more of a restatement of the Java source code in terms of simpler (but still quite complex) primitives. Real compilation happens just in time while your code is running. – Marko Topolnik Aug 28 '13 at 12:40

3 Answers3

2

The first code fragment behaves differently as the second one if the result of getMethod() is null. So it’s clear that the byte code must differ.

Holger
  • 285,553
  • 42
  • 434
  • 765
0

javap -c YourClass.class what ever the code you compile Compiler starts the functioning by converting the class data to a byte code.

the byte code is similar to machine language which contains only 0,1 so, what ever you craete either it is object or any thing else it converts to bytecode with its particular pattern but not same as your object or what ever you created in your Class

Raj
  • 600
  • 1
  • 5
  • 18
0

First off, you can always check by just compiling and disassembling a class yourself.

Anyway, the first example uses a local variable so it will result in different bytecode. From what I've seen, Javac never optimizes away local variables, even if they're unused or could easily be inlined. Presumably this is to support debugging, though it happens even when compiling without debugging info.

Antimony
  • 37,781
  • 10
  • 100
  • 107