0

Given this example:

package com.company;

public class Main {

    public static void main(String[] args) {
        String myStr= "Hello World ";
        myStr.trim();
        int i1= myStr.indexOf(" ");
        System.out.println(i1);
    }
}

What is the result:

A: An exception is thrown at runtime

B: -1

C: 5

D: 10

I guess it should trim the leading and following spaces from myStr, leaving me with the space at position 5, which was confirmed when I typed in the code.

My question is then why did the example marked the correct answer as "A" instead of "C"? Is it just a typo or is there a special way trim works and I messed up while typing it in? :D

Adrian
  • 8,271
  • 2
  • 26
  • 43
harvy666
  • 3
  • 3
  • This snippet absolutely prints `5`. If you messed up the snippet (or right answer) while copying it, we have no way of knowing it. – Mureinik Mar 13 '20 at 10:12
  • The only thing IntelliJ shows me is a yellow warning that "the result of String.trim is ignored", but I guess thats not important. Damn, the first couple of questions of this test was ok, then I randomly jumped to the 64th one and it has a false answer now how do I trust the other answers? :D – harvy666 Mar 13 '20 at 10:16
  • 1
    Why do you trust **marked answer** over the actual output? No mater if you `trim()` or not, `indexOf()` always gives the index of 1st occurrence of the character/string. – Prashant Mar 13 '20 at 10:19
  • 1
    Just a small hint about that warning: it is important to know that trim() returns the trimmed string and does not edit the input. So, in your example code you never look at the trimmed string but at the source (which doesn't change the output in your case anyways - but still important to know ;)) – fhueser Mar 13 '20 at 10:21
  • Why don't you debug and see? – Nicholas K Mar 13 '20 at 10:27
  • 1
    Good mention fhueser, I know about String immutability :) – harvy666 Mar 13 '20 at 10:29

0 Answers0