What is the result?

Given the code fragment:

What is the result?
A. Invalid Name
B. Invalid Name omas
C. Invalid Name omas null null
D. omas ter seph

Download Printable PDF. VALID exam to help you PASS.

6 thoughts on “What is the result?

  1. in provided code its needed
    1) to use curly braces for array initialization ” String names [] = {“Thomas”, “Peter”, “Joseph”};”
    2) use either “pws” or “pwd” array name through all program,
    then result will be C:
    # javac Test43.java
    # java Test43
    Invalid Name
    omas
    null
    null

    1. result description: “try” block will be stopped after caught exception with message “Invalid name” (due to “Peter” don’t have 6th character) , then array “pwd” will be printed with “omas” and two other not initialized values “null” “null”

  2. public static void main(String[] args) {
    String names [] = {“Thomas”,”Peter”,”Joseph”};
    String pws [] = new String[3];
    int idx = 0;
    try{
    for (String n : names){
    pws[idx] = n.substring(2,6);
    idx++;
    }
    }catch (Exception e){
    System.out.println(“Invalid Name”);

    }
    for(String p:pws){
    System.out.println(p);
    }
    }

    The result :
    Invalid Name
    omas
    null
    null

  3. Answer C:

    First to clarify; clearly the “pws” in the third line is a typo of “pwd”.

    Line 3 creates a new array of Strings with 3 vacant places. And since the Strings were not added yet, JVM adds the default values “null”s for all the three places.

    In the “try” block, the for loop iterates through the names, creating a substring of each name each time. However, “Peter” is shorter than the required substring, and this leads to throwing IndexOutOfBoundsException, which is handled in the “catch” block. This causes the loop to break and to print “Invalid name”.

    The second for loop just list the contents of the pwd array. Since we only have the first substring saved (i.e. omas), then we will get (omas null null).

Leave a Reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.