Shn_Android_Dev Shn_Android_Dev - 7 months ago 10
Java Question

Two (easy?) Android/Java syntax questions

I just switched from Xamarin/C# to Android Studio/Java and am familiarizing myself with the dissimilarities between the two languages. I'm reading an android book written in java and came across the following two lines of code:

1)

PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(preferencesChangeListener);


In the first line, i'm confused by how preferencesChangeListener is used. In C# you can't just toss a new preferencesChangeListener object into an argument without instantiating the object. So in Java, are you allowed to implicitly instantiate?

2)

int screenSize = getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK;


Secondly, I am confused by the '&' symbol used here. I thought the ampersand was used for boolean arguments, yet you see here that the left side of the equality is expecting an integer. What's going on here?

Answer
  1. No, you are not allowed to implicitly instantiate, and if that variable isn't instantiated then you will likely get a NullPointerException, unless the method you are calling it is using it as an output
  2. In most languages, including java, && is the boolean operator and & is the bitwise operator. & is a bitwise AND, so for example (0101) & (1110) would be (0100). In your example, it is being used to zero out certain bits.
Comments