Given the code fragment:
What is the result?
Given the code fragment:
What is the result?
The code provided has a potential issue when it tries to execute the `substring(2, 6)` method. This method call extracts a substring starting at index 2 and ending at index 5. For the string "Thomas," this operation succeeds, yielding "omas." However, for the string "Peter," attempting to access characters beyond its length will throw a `StringIndexOutOfBoundsException` because it's less than 6 characters long. The exception will be caught, the message "Invalid Name" will be printed, and the `for` loop will terminate prematurely, which means `pwd` array will contain partial data: the first element as "omas" and remaining elements as `null`. During the second `for` loop, it will print the contents of `pwd`, resulting in the output: omas null null
Correnct is C, there are no comments to make. If you want to test the code: public class Main { public static void main(String[] args) { String names [] = {"Thomas", "Peter", "Joseph"}; String pwd [] = new String [3]; int idx = 0; try { for (String n: names) { pwd [idx] = n.substring(2, 6); idx++; } } catch (Exception e) { System.out.println ("Invalid Name"); } for (String p: pwd) { System.out.println (p); } } }
It should be a compilation error, due to syntax, for this line String names[] = ("Thomas", "Peter", "Joshep");
keen eye
C is correct
Correct. Answer is C. In the first 'for', when trying to execute n.substring for the name "Peter", an exception will be thrown. So in the catch block it will print "Invalid Name", in the second 'for' it will print "omas" and the default values of the remaining elements of the pwd array. It can be tested, iSnover give the source code below.