1

This is a very simple question:

When you compile a java program, it is converted to byte code, so therefore, every line number of the .java or .class file is missed (I think so, probably I am wrong..). So, when you print a stack trace, how does it manage to get all the class names and line numbers that were in the call stack? I think that I may be missing something here, but I couldn't find anything related to this.

Pablo Matias Gomez
  • 6,614
  • 7
  • 38
  • 72
  • 2
    class names (as well as variable names, method names...) are not erased. They are in the bytecode. You can see that with even a text editor on a .class file. – njzk2 Aug 18 '15 at 01:28
  • This is true for many other languages as well. People soon found out that having "debug symbols" to go along with the raw executable code is a useful thing. – Thilo Aug 18 '15 at 01:31
  • 1
    Even without file names and line numbers (those can be stripped), you would still get class names and method names (those are needed to actually run the program, Java is very late-binding). – Thilo Aug 18 '15 at 01:35

2 Answers2

7

When you compile a java program, it is converted to byte code

Correct.

so therefore, every line number of the .java or .class file is missed (I think so, probably I am wrong..).

You're wrong. Line number information is embedded into the .class file unless you use the -g compiler option in certain ways.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • And when does the bytecode get to be assembly code? I am a little confused here, I think.. – Pablo Matias Gomez Aug 18 '15 at 01:31
  • 1
    @PabloMatíasGomez: Define "assembly code". The bytecode is the compiled output that the JVM runs. It may or may not compile it further down to actual machine code. "assembly" is a human readable programming language very close to binary code (bytecode or machine code). – Thilo Aug 18 '15 at 01:32
  • @Thilo Now I get it! When I said "assembly code" I meant something like assembler, but of course, I missed the part the the JVM runs the bytecode directly. – Pablo Matias Gomez Aug 18 '15 at 01:37
5

If line numbers are present, then the java compiler created bytecode with the debug flag set to true. This can be achieved using java -g

From Oracle's javac documentation:

  • -g
    • Generate all debugging information, including local variables. By default, only line number and source file information is generated.
  • -g:none
    • Do not generate any debugging information.
  • -g:{keyword list} - Generate only some kinds of debugging information, specified by a comma separated list of keywords. Valid keywords are:
    • source
      • Source file debugging information
    • lines
      • Line number debugging information
    • vars
      • Local variable debugging information
Keith
  • 3,079
  • 2
  • 17
  • 26