File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes About += operator in array. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "About += operator in array. " Watch "About += operator in array. " New topic
Author

About += operator in array.

Sihao Rui
Greenhorn

Joined: Oct 14, 2007
Posts: 10
Hi, I had a question about += operator as follows.

Why names[--a] += "-" and names[--a] = names[--a] + "-" are different in (1) and (2)?
Thanks.

(1)
public class sihao{

public static void main(String[] arg)
{
int a = 1;
String[] names = {"a","b","c"};
names[--a] += "-";

for(int i =0; i<names.length;i++)
{
System.out.println(names[i]);
}
}
}

will print out
a-
b
c

----------------------------------------------------
(2)
public class sihao{

public static void main(String[] arg)
{
int a = 1;
String[] names = {"a","b","c"};
names[--a] = names[--a] + "-";

for(int i =0; i<names.length;i++)
{
System.out.println(names[i]);
}
}
}

will get java.lang.ArrayIndexOutOfBoundsException.
Doug Slattery
Ranch Hand

Joined: Sep 15, 2007
Posts: 294
Hi Shihao,

Originally posted by Sihao Rui:
Hi, I had a question about += operator as follows.

Why names[--a] += "-" and names[--a] = names[--a] + "-" are different in (1) and (2)?
Thanks.

(2)
public class sihao{

public static void main(String[] arg)
{
int a = 1;
String[] names = {"a","b","c"};
names[--a] = names[--a] + "-";

for(int i =0; i<names.length;i++)
{
System.out.println(names[i]);
}
}
}

will get java.lang.ArrayIndexOutOfBoundsException.


Because on the , the variable a goes negative because it has a value of 1 at the execution of the line. On the left side of the =, a has a value of 0 for the index value and on the right side of the =, a has a value of -1 for the index value. Bad news.

Hope this helps...
Aloha,
Doug

-- Nothing is impossible if I'mPossible
Sihao Rui
Greenhorn

Joined: Oct 14, 2007
Posts: 10
But why names[--a] += "-" works?

Thanks
Sihao
Srinivasan Mahadevan
Greenhorn

Joined: Jun 21, 2002
Posts: 5
Please refer the Java Language Specification for "Compound Assignment Operators".

Following is mentioned.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

In the case what you have shown, the expression is evaluated only once and hence it doesn't give exception.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About += operator in array.