Home > database >  How many objects are created in the following Java Program?
How many objects are created in the following Java Program?

Time:12-12

public class Test {
    public static void main (String[] args) {
        Long a = (long) 1;
        Long b = (long) 2;
        Long c =   a   b  ;
        System.out.println(a   " "   b   " "   c);
    }
}

First I thought that there would be 3 objects (a, b, and c) but I wasn't sure if c would be an independent object which isn't dependent to a and b. Also, I'm not sure if other objects exists or not.

CodePudding user response:

Well, it depends on how you calculate it and which objects you include.

  • There are three Long variables, which all have a different value eventually (2, 3 and 4 respectively). So those are three objects.

  • Then there's a string concatenation expression a " " b " " c, which perhaps creates intermediate String objects.

However, if we look closely, there are many more objects:

  • System.out is also an object, as well as args.

  • Longs with values -128 to 127 are required to yield the same instance, as mandated by JLS § 5.1.7. This requires for some Long cache. And

    The implementation may cache these, lazily or eagerly

    So there may or may not already be 256 Long instances.

  • Then Java Language Specification § 15.18.1. String Concatenation Operator says something about intermediate String objects as well:

    An implementation may choose to perform conversion and concatenation in one step to avoid creating and then discarding an intermediate String object. To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

    (Emphasis mine.)

So in the end, it really depends on the actual Java implementation used.


I think questions like these are often too theoretical, and almost always answerable with "it depends". I think the exact number of objects doesn't really matter, what matters more is whether you pick the right data structures, and make your code readable.

  • Related