This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why do i get this run time eroor... plz help

 
Anish Nagraj
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My program is like this...

public class Propogate {

String reverse(String val) throws Exception{

String reverseStr ="";
System.out.println(val);
if(val.length()== 0){
throw new Exception();
}
else{

for(int i = val.length(); i>0; --i){
reverseStr = reverseStr + val.charAt(i);
}
val = reverseStr;
}
return val;

}
public static void main(String[] args) {

Propogate eh = new Propogate();
try{
System.out.println(eh.reverse("java"));
}catch(Exception e){
System.out.println(e);

}


}
}

i get a ru time error telling

java.lang.StringIndexOutOfBoundsException: String index out of range: 4
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The first index in a String is position 0. So the last position is not the length of the String, but one less. You are trying to access the position in the String indicated by its length.
 
srilatha kareddy
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
for(int i = val.length(); i>0; --i){
reverseStr = reverseStr + val.charAt(i);
}

val.length()=4;

val.charAt(4); ...Its not there so run-time exception occur

...this will work.........
for(int i = val.length()-1; i>=0; --i){
reverseStr = reverseStr + val.charAt(i);
}
 
Anish Nagraj
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. i want to know exactly when the pre-increment of i works out and the value of i becomes 2 in the program i specified.

2. i also want what difference does a pre-decrement and post-decrement in this program makes... hope it makes no difference... let me know the exact description...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic