Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on String methods

 
Bala Raj
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This doubt I got while browsing discussions in Maha's site:
class StringMethods
{
public static void main(String args[])
{
String s = "Java Exam"; //1
int beginIndex = 1; //2
char endIndex1 = 4; //3
char endIndex2 = '4'; //4

System.out.println(endIndex1);// 5 printing some junk
System.out.println(s.substring(beginIndex,endIndex1));// 6 (beginIndex-(lastIndex-1))

System.out.println(endIndex2);//7 Output of 4
System.out.println(s.substring(beginIndex,endIndex2));//8 runtime exception
}
}
What is the difference between line 3 & 4? Why line 8 is throwing an exception? Can any one explain me?
Thanks in advance
Bala.
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3708
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Run the following lines and you'll know...
char ch1 = 4;
char ch2 = '4';
int i1 = ch1;
int i2 = ch2;
System.out.println("i1 = "+i1+" i2 = "+i2);
Observe the value of i2 and you'll understand why it throws the exception.
Note that, subtring(...) takes int as parameters.
HTH,
Paul.
------------------
Get Certified, Guaranteed!
http://www.enthuware.com/jqplus
 
Ajith Kallambella
Sheriff
Posts: 5782
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The substring() method takes integer arguments. So, when the method is called, the char variable endIndex2 is widened to an integer with a value of 52....and you know what happens next

Ajith
 
Bala Raj
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul and Ajith.
It cleared my doubt.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic