Search code examples
androidandroid-fragmentsfragmentpageradapter

Why is a "Fragment fragment = null" and what is meaning of this definition of fragment?


Here is a piece of code from getItem method of FragmentPagerAdapter:

 @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;
        switch (position){
            case 0:
                fragment = new FragmentLight();
                break;
            case 1:
                fragment = new FragmentDark();
                break;
        }
        return fragment;
    } 

QUESTIONS:

  • Why is fragment declared as "Fragment fragment = null;", and what is the meaning of null?
  • Why can I not just put here "Fragment fragment;" what is a difference between these two examples?

Solution

  • In the first case you are giving an initial value to the object, and that's null value. In the second case you would be leaving the object uninitialized.

    The important part is the code that follows: if you can guarantee that in any of the branches the code may take, the object will get initialized, than you can leave it uninitialized at the beginning. Otherwise, if there is no guarantee, the compiler will complain (assuming that you will be using that object later on, otherwise you'll get a warning for unused variable).