Doubt about why it does not give nullpointexception

-2

It's a stupid question but why does this code work?

 public static void main(String[] args) throws ParseException {


    List<String> lista2 = teste();
    System.out.println(lista2.toString());
}

In this method I should return a list but have a second 'return null' should it not be executed too?

public static List<String> teste(){

    List<String> meu = new ArrayList<String>();
    meu.add("iodfsj");
    meu.add("jfgfy");
    meu.add("ophgkyp");
    meu.add("jifrl");

    if(true){
        return meu;
    }

    return null;
}
    
asked by anonymous 04.05.2017 / 20:24

3 answers

2

NullPointerException pops up whenever an attempt is made to access a member of a null object.

Note that lista2 gets the result of teste() is the result of teste() will never be null .

This happens because the execution of the method for immediately on the first return .

public static List<String> teste(){    
    List<String> meu = new ArrayList<String>();
    meu.add("iodfsj");
    meu.add("jfgfy");
    meu.add("ophgkyp");
    meu.add("jifrl");

    if(true) { // Sempre vai entrar no bloco
        return meu; // Aqui tem um return. "meu" será retornado e a execução do método para
    }

    return null;
    // Isto só será executado quando não entrar no if. 
    // Ou seja, nunca, no código atual
}
    
04.05.2017 / 20:43
1

No, only a return statement can be executed. Once you call the return , switch context, exiting the function.

    
04.05.2017 / 20:26
1

null is not running because its if block always returns true . In addition, in Java, each instruction has only return .

If you still want to return two values, you can try concatenating them

    
04.05.2017 / 20:27