Thursday, May 19, 2005

Implicit Code

Introduction

Wouldn't it be great if the compiler could write a lot of code for you automatically? Especially the boring, tedious stuff that always must be there, but that you would rather not write until absolutely necessary...

Well, the compiler does just that, and often without the programmer even knowing. It's called implicit code, and is source code that is implied rather than directly expressed. The idea behind implicit code is that you do not have to do all the work yourself, because the compiler will write the code for you. Since the source code is implied, it does not actually show up in your program. But implicit code certainly end up as a part of the compiled code.

Concept: Implicit code is source code that is implied rather than directly expressed.

Program

Consider the program:
class Compute {
    public static void main(String[] args) {
        System.out.println(3 + 2 * 2);
    }
}

Output

[user]$ javac Compute.java
[user]$ java Compute
7

The application writes 7, not 10, because the compiler implicitly adds paranthesis around the operator with the highest precedence, 3 + (2 * 2).

Discussion

The compiler fills in the missing code implicitly for you, when needed, without actually changing the source code itself. Only the compiled code is affected. As a result, the source code look simpler, less cluttered and possibly you will also avoid a few bugs. On the other hand, you can always explicitly write the code yourself, if you want to.

The code production is not totally random or uncontrollable. The compiler applies certain rules in order to discover implicit code when compiling source code. The rules will be discussed later at various places in the tutorial.

Concept: Following certain rules, implicit code is added implicitly by the compiler.

Note: There's a lot of implicit stuff going on in Java. The reason is that many programmers usually view implicit features as a convenience. However, the rules for implicit code must be clearly understood and always be remembered, actually making programming less comfortable or easy in many situations.

No comments: