Email address:
Password:
SCJP/OCPJP 1.6 certification
Practice Exams and Training
SCJP Online Training » Discussions

why no compiler error not occurs for this Line?

20. d.add("A".split("B"));


How this works here

The expression is "A".split("B"). Sure, the given String "A" does not contain the letter "B" for the split by B to make sense, however, that's not a problem.


First, let's assume it IS a problem, and the creators of the String class in Java language didn't want to you to be able to split "A" by "B". Even if that's the case, there is no way this can cause a compile error, because from the compiler's viewpoint, you are only splitting a string from another string - it doesn't necessarily know what each Strings really contain ("A" and "B"). Therefore, the only possible way for this to become a problem is having it throw a runtime exception.


However, the creators of the String class didn't want to prevent you from splitting "A" by "B" even though it doesn't make much sense. What really happens here is since the given delimiter ("B") does not exist in the given string ("A"), it simply returns the given String in a String array that contains just one element.

ExamLab © 2008 - 2024