This week's book giveaway is in the Python forum.
We're giving away four copies of Python Continuous Integration and Delivery and have Moritz Lenz on-line!
See this thread for details.
Win a copy of Python Continuous Integration and Delivery this week in the Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Devaka Cooray
  • Junilu Lacar
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Tim Holloway
  • Claude Moore
  • Stephan van Hulst
Bartenders:
  • Winston Gutkowski
  • Carey Brown
  • Frits Walraven

please explain the program  RSS feed

 
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


When i run this program i found the output is:-

0.0
0.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Foo.main(Foo.java:10)
Press any key to continue . . .
please explain me why it is

0.0
0.0
and exception
 
Rancher
Posts: 42974
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"j" is incremented twice in each loop iteration. You might want to print out the value of j before and after the "x[j]=j++" statement to see how its value changes.
 
Sheriff
Posts: 21642
101
Chrome Eclipse IDE Java Spring Ubuntu VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
x[j]=j++ assigns the current value of j to x[j], then increments it. So, if the other increment would be absent, it would result in an array of [0, 1, 2, 3, 4].
Also, after this increment, you're trying to access x[j] again.

So what is happening:
x[0] = 0;
j = 1;
x[1] is printed (0 because not initialized)
j = 2 (loop increment)
x[2] = 2;
j = 3;
x[3] is printed (0 not initialized)
j = 4 (loop increment)
x[4] = 4;
j = 6;
x[5] is printed -> ArrayIndexOutOfBoundsException
 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob and Dittmer for your Explaination
 
He does not suffer fools gladly. But this tiny ad does:
Become a Java guru with IntelliJ IDEA
https://www.jetbrains.com/idea/
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!