aspose file tools*
The moose likes Java in General and the fly likes 1.5 Integer with += Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "1.5 Integer with +=" Watch "1.5 Integer with +=" New topic
Author

1.5 Integer with +=

Kevin Stock
Greenhorn

Joined: Jul 18, 2004
Posts: 18
Why does this work:


But not this:


Thanks,
Kevin
[ March 02, 2005: Message edited by: Kevin Stock ]
Mark Patrick
Ranch Hand

Joined: Feb 22, 2004
Posts: 51
Neither compiles.

You can't add a number to an object using the '+' operator.

From the language specification...

15.15.3 Unary Plus Operator +

The type of the operand expression of the unary + operator must be a primitive numeric type, or a compile-time error occurs.


Mark Patrick<br />SCJP 1.4
James Carman
Ranch Hand

Joined: Feb 20, 2001
Posts: 580
They specified 1.5 in the title. So, they CAN use the "+" operator with an Integer object. It's called "autoboxing" (in this case unboxing actually) which is a new feature of the Java language in 1.5. The reason you can't do the second operation is because the left-hand side of an assignment has to be a variable. In your case, it's not. It's an expression (the result of casting i to an Integer).


James Carman, President<br />Carman Consulting, Inc.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Also note that += is not the unary + operator. The latter is similar to the unary - operator:
Kevin Stock
Greenhorn

Joined: Jul 18, 2004
Posts: 18
Thanks James,

I tryed some test cases, and when not casting on the left it works fine. Why can't expressions such as that be on the left side? Doesn't casting effectivly 'replace' what was there with the casted object?
Dan Bizman
Ranch Hand

Joined: Feb 25, 2003
Posts: 387
The problem is your casting parenthesis. Try this:

( ( Integer ) i ) += 1;
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Dan Bizman:
Try this:
( ( Integer ) i ) += 1;
I tried it using JDK 1.5 for kicks, and it failed. As James said, you need an assinable variable on the left side of an assignment operator (called an lvalue). Casting a variable evalutes to the value the variable holds cast to the specified type which is not assignable (called an rvalue).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: 1.5 Integer with +=
 
Similar Threads
Garbage Collection
re: ambiguous method calls
Confused about Arrays.binarySearch
overloading
How to find the elements present in the Array