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 ...
  • Campbell Ritchie
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
  • Piet Souris
  • salvin francis
  • fred rosenberger

StringBuilder question

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

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?

Ranch Hand
Posts: 491
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,
Posts: 16
  • 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!
    Bookmark Topic Watch Topic
  • New Topic