Win a copy of JDBC Workbook this week in the JDBC and Relational Databases forum
or A Day in Code in the A Day in Code 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
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

StringBuilder question

 
Greenhorn
Posts: 11
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

I have another question from the Oracle practice test:

8. Given the code fragment:
What is the result?
A) -1
B) 3
C) 4
D) A StringIndexOutOfBoundsException is thrown at runtime.

I was wondering if the result would be 0 because s1 took the substring. But the answer is C?

-Simon
 
Ranch Hand
Posts: 491
23
Eclipse IDE Firefox Browser Spring VI Editor AngularJS Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi simon,
Please read the API of StringBuilder.
s1.substring(4) will return a new String and it will not modify the StringBuilder→(s1).
read the documentation of the substring(int start) in the link i have provided.

Hope it helps!

Kind Regards,
Praveen.
 
Greenhorn
Posts: 16
2
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I haven't run the code but I think this is what happens:

"Love" is appended to "Java" on line 3 making s1 "JavaLove".  

Line 4 has no effect.

Line 5 looks for "Love" in s1 and finds it starting at index 4.

So, the answer is (C).
 
pie. tiny ad:
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic