Skip to content
Exercises · Q6

Q.Predict the output of the following code and explain each result:
String s = "Commerce";  
System.out.println(s.length());  
System.out.println(s.substring(0, 3));  
System.out.println(s.toUpperCase());  
System.out.println(s.indexOf("m"));  

ChseodishaTextbookSubjectiveImportance★★★★★est
43% · 6/14 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Take each statement in turn, with s = "Commerce". Remember that indexes start at 0: C=0, o=1, m=2, m=3, e=4, r=5, c=6, e=7.

s.length() → 8. length() returns the number of characters. 'Commerce' has 8 letters, so the result is 8.

s.substring(0, 3) → "Com". substring(a, b) returns the characters from index a up to but not including index b. So it takes indexes 0, 1 and 2 — 'C', 'o', 'm' — giving "Com". (Index 3 is not included.)

s.toUpperCase() → "COMMERCE". This returns a new string with every letter in capitals. Note the original s is unchanged, because strings are immutable. …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.