Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Re boxed primitives in Java and .NET

3.60/5 (5 votes)
23 Mar 2010CPOL1 min read 1  
Why i = i++ expression returns different results in C++ and Java/.NET?

One of my colleagues posted the following question once “why <i = i++> expression returns different results in C++ and Java/.NET?”. For instance, try this:

C/C++

C++
int i = 1;
i = i++; 
printf("%d\n", i);
result is 2

Java

Java
int i = 1;
i = i++; 
System.out.println(i);
result is 1

Many C++ developers will argue that <i = i++> is left undefined in C++ (i.e. it is up to compiler implementers to return whatever they think it is most appropriate). However, at a more practical level, <i = i++> against a primitive int type, in C/C++, is a simple (optimized ASM code, avoiding all the formalities with moving to/from registers):

C++
mov i, i
inc i

at the same "address location" (in a simplistic way). So the result is 2.

Now, let's look at what C++ suggests about operator++(int). It suggests making a copy of the current instance, increasing current instance and returning the copy. Following this rule, the result is:

C++
class MyInt {
private:
	int i;
public:
	MyInt(int iVal) { i = iVal; };
	int val() const { return i; };
	MyInt(const MyInt& t) { i = t.val(); };

	MyInt& operator=(const MyInt& t) {
		i = t.val();
		return *this;
	};

	MyInt operator++(int) {
		MyInt t = *this;
		i++;
		return t;
	};
};

MyInt func() {
	MyInt i = MyInt(1);
	i = i++;
	return i;
}

int _tmain(int argc, _TCHAR* argv[])
{
	int i = 1;
	i = i++;
	_tprintf(_T("%d\n"), i);

	MyInt t = func();
	_tprintf(_T("%d\n"), t.val());
	return 0;
}
Result is
2
1

But it is exactly what Java/.NET returns. From this, it is logical to conclude that Java/.NET primitives are boxed (which seems to be logical, otherwise it is hard to imagine how to support platform independence in Java/.NET, for example replacing the above class with a structure like "struct MyInt { int i : 32; };" in order to support 32 bits integers). Also this means that C/C++ works faster with primitives :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)