I am wondering which of the following is the most efficient?
int x = 1, y = 2;
System.out.print(x+y)
or...
int x = 1, y = 2, z = 3;
System.out.print(z);
I'm guessing it's the first, but not sure - thanks.
I am wondering which of the following is the most efficient?
int x = 1, y = 2;
System.out.print(x+y)
or...
int x = 1, y = 2, z = 3;
System.out.print(z);
I'm guessing it's the first, but not sure - thanks.
The real answer is: talking about efficiency on such a level does not make any sense at all.
Keep in mind that the overall performance and efficiency of a Java program is determined by many many factors - for example when/how the JIT kicks in in order to turn byte code into machine code.
Worrying about such subtleties will not help you to create a meaningful, maintainable, "good OO" design. Heck; in your case, depending on context, it could even be that the compiler does constant folding and turns your whole thing into println(3) (as it is really straight forward to throw away those variables); so maybe in both cases, the compiler creates the exact same bytecode.
Dont get me wrong: it is fair to ask/learn/understand what compilers, JVMs and JITs do. But: dont assume that you can categorize things that easily into "A more efficient than B".
If you truly mean the case where you have supplied all the literal values like that, then the difference doesn't exist at all, at least not after your code is JIT-compiled. In either case you will have zero calculation done at runtime. The JIT compiler will work out the result and hardcode it into all its use sites. The optimization techniques involved are Constant Propagation and Constant Folding.
It would be second option as you do not need any memory for calculation. You're just print a number instead of adding them together and than printing.
This is simple example, so performance is not noticeable at this level..
Good practice is to assign the task appropriately to different functions.