Meaningless Drivel is fun!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on String methods 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 "Question on String methods" Watch "Question on String methods" New topic

Question on String methods

Bala Raj
Ranch Hand

Joined: Sep 12, 2000
Posts: 75
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
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3635
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.
Get Certified, Guaranteed!

Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
Ajith Kallambella

Joined: Mar 17, 2000
Posts: 5782
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


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Bala Raj
Ranch Hand

Joined: Sep 12, 2000
Posts: 75
Thanks Paul and Ajith.
It cleared my doubt.
I agree. Here's the link:
subject: Question on String methods
It's not a secret anymore!