This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on String methods" Watch "Question on String methods" New topic
Author

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
Bala.
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3254
    
    2
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


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

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

Ajith


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: http://aspose.com/file-tools
 
subject: Question on String methods
 
Similar Threads
substring(int i)
String method query
doubt in indexOf()
substring method signature
Doubt in Marcus Test 1