Doubt about why it does not give nullpointexception

Asked

Viewed 37 times

-2

It’s a dumb doubt 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' it should not be run either?

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;
}
  • 1

    What is the purpose of the code? Why do you have this null there? Why do you have this if true there?

3 answers

2


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

Realize that lista2 receives the result of teste() is the result of teste() will never be null.

This is 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
}
  • Thanks! That’s just what I wanted to know. The reason, now I know.

1

No, just an instruction from return can be executed. Once you call the return, change of context, leaving the function.

  • Got it...a Re-turn executed at a time huh...

1

The null is not running because your block if always returns true. Also, in java, each instruction has only one return.

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

  • thanks, got it. ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.