Asserting for a Toast message using Robolectric

toast

I’ve recently put together a few proof of concept applications, and since they’re “rough and ready” applications, a lot of the functionality is actually mocked, or given a stubbed implementation.

For example, I’ve got various buttons for things like “sign in with LinkedIn” or “Connect with Facebook”. Since its just a proof of concept, and those features aren’t really must haves, I stub them with a Toast message saying something along the lines of “feature not yet implemented”.

This gives the user the opinion that the buttons are there, functional, however the actions they take are not yet implemented.

This is fine, however if you have numerous stubbed toast messages across the application, or even real toast messages that you have in production standard code, you’ll want to unit test those to be sure you don’t introduce defects when you’re busy beavering away in other areas of the source code.

Fortunately we can use the Robolectric framework to cover a lot of these unit tests. I won’t go into detail about Robolectric here, so please head over to their site and have a look at the basics before you can understand this post.

The assertion is pretty straight forward, and consists of the following :

@Test
public void assertValidationFailureWithNullInput()
{
	searchEditText.setText(null);
	searchButton.performClick();

	ShadowHandler.idleMainLooper();
	assertThat( ShadowToast.getTextOfLatestToast(), equalTo("Please enter a value."));
}

What I have here, is an EditText that I use for a search button, I set its value to null and then click on it. The purpose of the test is to ensure that submitting “search” with a null input will be caught by my validation, and a toast message prompting the user to enter valid data.

Hope that helps, and if you have any questions please leave a comment :)

A second app to launch; Agile Planning Poker

main menu

After launching my first application onto the market back in March 2011, and amassing somewhere in the region of 15,000 downloads since it’s launch, I was eager to produce another.

I offered up my services at my work to develop an application to “test the water”, teaming up with the marketing director we created a simple yet useful application for agile project managers; planning poker decks.

The concept is simple, when an agile team is in an estimation phase, they assess each task and try to estimate how much effort would be involved to complete that task. There are many different approaches to how the estimation can take place, such as grouping tasks into small/medium/large, or even a simple show of hands voting system. Another method is with the use of planning poker cards.

We decided to keep it simple and offer 3 types of estimation, or 3 decks of card in this application; standard, fibonacci, and hours deck, with the following cards :

Standard

  • 0
  • 0.5
  • 1
  • 2
  • 3
  • 5
  • 8
  • 13
  • 20
  • 40
  • 100

Fibonacci

  • 0
  • 1
  • 2
  • 3
  • 5
  • 8
  • 13
  • 21
  • 34
  • 55
  • 89

Hours

  • 0
  • 0.5
  • 1
  • 2
  • 4
  • 8
  • 12
  • 16

In addition to the numbers above, each deck has the following special cards :

  • ? – Played when you genuinely have no idea how long it would take
  • Infinity symbolPlayed when you believe the task would take forever, or at least longer than is feasible
  • Coffee mugPlayed when you’ve just had enough, and need a timeout

The idea is that when estimating tasks, the users would all select the appropriate card, and on call display their selection to the rest of the team. This rules out any obvious biased choices as the users would all select their own cards, and display at the same time ruling out any options for copying the developer next to you.

The idea is to stimulate discussion and justification of the estimates, so if you estimate a task would be 5 days, but Dalibor estimates it’s only a few hours, it opens up a debate and can rule out any obvious misunderstandings or misconceptions about the task itself, or how it could be achieved, eventually resulting in more accurate estimates.

Click here to view/download the application from the market.

If you’re interested in web services, systems integration and other such enterprise technologies, be sure to check out our blog, also have a look at my write up from DroidCon UK 2011, plenty of android goodness lies within.

How to add a splash screen to your android application in under 5 minutes

realistic-water-drop-splash

Adding a splash screen to your application is a quick and easy way to make it look more well rounded, complete, and more professional, it can also serve as a useful distraction whereby you have an extra few seconds to initialise your application components before displaying them to the user.

In this post I’ll show you how to quickly and easily add a splash screen into your application, I’ll also show you how you can create an option whereby users may disable or enable the splash screen for subsequent launches of your application. I’ll also post up my sample code freely on Github so you can checkout what I’ve done and use as you please.

So lets get started right away and create the application, we’ll go ahead and create 3 activities as detailed below, and also shut off the title bar.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.jameselsey.android.demo.androidsplashscreen"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
        <activity android:name="SplashActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="MainActivity"
                  android:label="@string/app_name">
        </activity>
        <activity android:name="EditPreferences"
                android:label="@string/app_name">
        </activity>
    </application>
</manifest>

The Splash activity will be the activity that handles the splash screen (Oh, really?!). Since we want to intercept any user launches of the application, we’ll make this the main entry point.

public class SplashActivity extends Activity
{
	// Set the display time, in milliseconds (or extract it out as a configurable parameter)
	private final int SPLASH_DISPLAY_LENGTH = 3000;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
		// Obtain the sharedPreference, default to true if not available
		boolean isSplashEnabled = sp.getBoolean("isSplashEnabled", true);

		if (isSplashEnabled)
		{
			new Handler().postDelayed(new Runnable()
			{
				@Override
				public void run()
				{
					//Finish the splash activity so it can't be returned to.
					SplashActivity.this.finish();
					// Create an Intent that will start the main activity.
					Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
					SplashActivity.this.startActivity(mainIntent);
				}
			}, SPLASH_DISPLAY_LENGTH);
		}
		else
		{
			// if the splash is not enabled, then finish the activity immediately and go to main.
			finish();
			Intent mainIntent = new Intent(SplashActivity.this, MainActivity.class);
			SplashActivity.this.startActivity(mainIntent);
		}
	}
}

In the onCreate we’re initialising the view layout, in my case I’m just referring to the splash view which has just a simple ImageView, but yours could contain anything such as images, text, adverts, possibly even combine it with a ProgressBar.

In the onResume, which is invoked after the create, we’re attempting to retrieve a saved variable, defaulting to true if it is not currently set.

A simple check on that boolean decides whether we should spawn a handler with a pre-defined delay, or finish the activity and move onto the main. In either case, we always want to call finish on the splash activity so that the activity is destroyed safely and the user cannot return back to it, then we create an intent to MainActivity and start it.

Arguably, there is more than one way of achieving this, we could use an AsyncTask, or even just spawn off a raw Thread, but I find the handler approach is much cleaner for this task whereby we can use an anonymous inner class rather than a regular inner class, also we don’t need any of the hooks into the UI which the AsyncTask provides, I deem that slightly overkill for such scenario.

That will pretty much get you a splash screen, now lets improve this a little by letting the user disable if they want.

First task we need to do is allow the use of the “menu” button on the device, by adding an override on onOptionsItemSelected in the MainActivity (or anywhere we want to allow this behaviour)

public class MainActivity extends Activity
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.options_menu, menu);
		return true;
	}

	/**
	 * This method will be called any time a user selects one of the options
	 * on the menu. For the implementation, whichever button is clicked is
	 * mapped onto the relevant activity.
	 * @param item MenuItem
	 * @return boolean
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case R.id.preferences:
				startActivity(new Intent(this, EditPreferences.class));
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}
}

Of course we also need to create the EditPreferences activity too, which in all fairness, exists purely to load preferences from an XML resource file :

public class EditPreferences extends PreferenceActivity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		addPreferencesFromResource(R.xml.preferences);
	}
}

Adding the following shared preference :

<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference
            android:id="@+id/isSplashEnabled"
            android:key="isSplashEnabled"
            android:title="Splash screen enabled"
            android:summary="Select to enable the splash screen on application startup"
            android:defaultValue="true"/>
</PreferenceScreen>

That is all you need to do! I’ve intentionally left out some of the layout resource files, but you can look them all up on the Github entry I created.

Hope that helps, any comments or suggestions please let me know!

Converting dp to pixels in android

Sometimes in android you have to deal with pixels, which can often be awkward, such as view.setPadding(int, int, int, int).  Obviously this is not ideal as pixel ratings vary from device to device, nonetheless there is a work around for this

Simply come up with the value you want in dip (density independent pixels), such as 10, and then convert into pixels using the display metrics of the device you’re working on. This will ensure that when the conversion runs, it’ll always scale to the device the application is running on.

float sizeInDip = 10f;
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, sizeInDip, getResources().getDisplayMetrics());

Enjoy!

Top 10 Techie things I want to achieve in 2012

to-do-list-nothing

I’m not the type of person that gets bored easily, I’ve always got many things to keep me amused, mostly side projects at home. I’m a firm believer, that if you don’t set yourself goals in the first place, then you won’t have anything to fail to achieve, so I’ve set myself a list of targets that I’d like to achieve in 2012 knowing full well I probably won’t get around to them all, but if I can do at least 3, it was worth it.

SCJP

I first picked up the SCJP study guide sometime around 2008, and I’ve had a love-hate relationship ever since. It’s by no means a trivial read, in fact, over 800 pages of solid technical details, a fair chunk of which I’ve never actually used, and probably never will once I’ve got through the exam. Reading the book is not enough to get through the exam, you also need to spend countless hours writing small code snippets to back up understanding, and spend plenty of time in mock exam simulators to prepare yourself. I have a terrible habit of getting obsessively involved in studying for a few weeks, before something pops up (working extra hours on a recent project at work is one good example) and I’ll not touch the book for weeks, only to have to re-cover the chapter where I last left off. This is definitely my goal for 2012, if I achieve nothing else but this, I’d be contempt.

Update AndroidSam

I put my first android app out on the market earlier this year, since its release I’ve had some fantastic feedback, amassing well over 15,000 downloads in the first 6 months alone. The app was very much an experimentation, and I certainly cut a few corners in the UI department prior to launch. I’ve been working on a few look and feel improvements, and a few other tweaks that I’d like to get out there soon.

Become more active on JR and SO, and java black belt

This is a must, theres no end goal and its more of an ongoing task that I must do. StackOverflow is a technical Q&A site, I’ve mostly become involved on the questions asking side, but the site has almost doubled in size in recent years so now there are plenty of unanswered questions that I can sneak in answers to, so I’ll have to start sweeping through my tags and get answering. JavaRanch is also a great site, I read this daily, however I rarely leave any posts. I’m planning to get more active and try to chip in with my comments more often. JavaBlackBelt is yet another great site, I was invited to be a beta question creator on the android exam but I just didn’t get round to providing any content, perhaps I can get more involved in 2012.

Complete SCJP study write ups

I found that a good way to help remember topics when studying, was to try and blog about them. I took the index of the SCJP study guide and outlined all the topics, and then gradually made my way through them all blogging about them in my own words. When trying to explain something, you often realise how you know (or sometimes how well you don’t know a particular subject). I’m about halfway through, and I’d really like to complete the blog posts, and get as much of my sample code up onto my Github account so it can help others.

Read, digest, and blog about technical books

Books, I’ve got a whole shelf of books that need some time. The main 3 that I’m interested in reading in 2012 are Effective Java, Clean Code, and Pragmatic Programmers Guide.

Effective Java is basically a compilation of tips and tricks that a Java developer should use if at all possible, Clean Code tells you how you should be writing your code and approaching problems, and the Pragmatic Programmers Guide is just more theory to lay on top. They’re not trivial reads, and some of it may possibly be too advanced for me, but if I can take anything away from it, it should help my progression.

Finish off my other android projects

I’ve been using Evernote to brain dump app ideas, its a handy little tool. Sometimes you get ideas spring into mind at the most awkward of moments, but most of the time I have my phone to hand, so I just tap them into evernote and let my ideas develop. Right now, in my cooking pot of ideas, I’ve got about 6 apps that I feel are worth putting to code, most are utlitlies but I have a few heavyweight ideas in there. Hopefully I can progress these throughout the year and get at least a few out to market.

Explore Spring Web MVC

The first company that I worked at solely produced Java web applications, that was where I got my first taste for the likes of Struts, Stripes, and a little bit of Spring MVC. I particularly liked working with the Stripes MVC framework, but it did lack a lot of community support, I’d like to explore a little with Spring MVC, since it’s always handy to know how to use the basics of Spring anyway. I started writing my own sales tracking system on Google App Engine, perhaps I’ll do something similar with Spring MVC and host it in the cloud somewhere.

Complete a cloud based CI environment

I’ve got various little side projects on the go, sometimes I use my windows PC at home to work on them, sometimes my works laptop, or my linux machine, so it can be a bit of a pain managing source code and builds. Fortunately I discovered something called Unfuddle, an online SVN repository where I could check my code into. I’ve also discovered something called CloudBees, which is a free on-line Jenkins installation, I’m planning to use that to build all my projects in the cloud, and dump artefacts onto DropBox. I may look at maven repositories too. Ultimately, I want to get my build processes in the cloud, so its purely coding that happens outside the cloud.

Ubuntu Certification

OK so one certification in the year is optomistic, but what about two? I’ve been an on-off linux user since I was in college, only really dipping back into Windows when I go through phases of gaming (WINE is just too much effort). Being competent with the shell terminal is going to help in the long run, so why not dedicate some time to skilling up in something useful. I’m not sure if I’d specifically go for the UCP, but it seemed an obvious choice since I have some familiarity with Ubuntu.

Explore Android ICS

With the latest Ice Cream Sandwich android released, theres plenty to be experimenting with, even if theres only a handful of devices that support it. I imagine that ICS will become more and more supported as the year goes on, so its probably time for me to devote some hours into picking up the new features of the SDK, and coming up with something nice. I’m also desperately in need of upgrading my 2.1 Orange San Francisco sub £100 handset, so possibly an excuse for a nice new shiny upgrade?

Revisit GAE Sales Tracker

About 2 years back I began working on an open source sales tracking system, to monitor progression of sales prospects. I started this in Stripes MVC framework and deployed to the Google App Engine. At the time GAE was still in its infinacy, but after a few years and several upgrades, I think developing on this platform may be slightly less painful now. I still have all the source code, and still have a running demo, maybe I can pick it up again and see what GAE improvements have come around.

SMS text messaging simulation on android

sms-incoming
As part of an application I’m currently developing, I need to be able to interogate incoming SMS messages. Since I’ll be developing against the emulator initially I need a way of sending in SMS messages to the emulator. Fortunately, we can use adb to poke in SMS messages at will, as detailed below.
Ultimately, you’ll need to telnet into your emulator, and you’ll need two things:
  • The port the emulator runs on. To find this out, open up a command window and type :

adb devices

You should see something like this :

C:\development\projects\AndroidSam\trunk_androidsam>adb devices
List of devices attached
emulator-5554 device
So my emulator is running on the default port of 5554.
  • Secondly, if you’re a Windows 7 / Vista user, you probably won’t have telnet enabled by default, so switch that on by going into Control Panel > Programs > Programs and Features > Turn Windows features on or off.

Now, lets actually send in an SMS. From the command window, type :

telnet localhost 5554

sms send 07841123123 Hello this is a sample message
OK

Then have a look at your emulator, you should see the SMS come through.
Stick around, I’ll post up some more SMS related tips in the coming weeks!

How to remove the default grey title bar on android apps

Fed up of the default title bar on your android applications?

We can get rid of that easy, either use the following in your activities to do it :

requestWindowFeature(Window.FEATURE_NO_TITLE);

Or, the way I prefer, disable it application wide by slipping the following into the AndroidManifest.xml file :

android:theme="@android:style/Theme.NoTitleBar"

Automating android application signing and zipaligning with maven

Code rage

This is something that has had me tearing my hair out for a few days now, I was pretty much border-line braveheart-ing my screen….

Code rage

I’ve recently been on a little drive to try to maven-ize my projects. All had been going well until I needed to sign and zipalign my APKs. This post will help you conquer that barrier with the use of some maven plugins.

When using ant, I was able to simply enter keystore details into build.properties and just call “ant release”. Unfortunately that approach doesn’t carry across to maven, and you have to provide some more configuration.

Firstly, before we go any further, I’m going to assume that you already have a maven android project setup, so you have a pom.xml, you’ve configured the maven-android-plugin and you can run “mvn clean install” to build your APK, and “mvn android:deploy” to deploy it to an emulator. If you haven’t got that far, I’d suggest you have a look at one of my previous posts to help get you up to speed.

So, when you want to build your application with maven, you’d run “mvn install”. That will, by default, use a debug key to sign your APK. When we want to build a releasable APK we still want to execute the same install goal, however we’ll want to use a proper key. Luckily, maven provides something called profiles.

In short, maven profiles allow you to still perform the same standard goals, yet they behave slightly different, in the manner of binding extra steps to them, all will come clearer in a moment.

This has already been covered, in a useful post by the guys at Novoda, and various other blog posts scattered around the web. I’ve followed at least 10 tutorials and each time I was unable to get the signing process to work correctly, each time I encountered the following error :

INFO] jarsigner: attempt to rename C:\android-projects\jameselsey_andsam_branch_mavenbranch\target\LanguageSelection-1.0.0-SNAPSHOT.jar to C:\android-projects\jameselsey_ands
am_branch_mavenbranch\target\LanguageSelection-1.0.0-SNAPSHOT.jar.orig failed
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Failed executing 'cmd.exe /X /C "C:\development\tools\Java\jdk1.6.0_20\jre\..\bin\jarsigner.exe -verbose -keystore my-release-key.keystore -storepass '*****' -keypass '
*****' C:\android-projects\jameselsey_andsam_branch_mavenbranch\target\LanguageSelection-1.0.0-SNAPSHOT.jar mykeystore"' - exitcode 1
[INFO] ------------------------------------------------------------------------

I’d tried everything, even copying out the command and pasting into a command window worked, but I could not get it to work from maven. Unfortunately it seems there may be an issue with the maven-jarsigner-plugin (as suggested in the comments on the Novoda post). However fear not, for there is an alternative, the maven-jar-plugin.

The maven-jar-plugin is a similar plugin to the jarsigner plugin, however the signing APIs are now deprecated and it points you to use the (apparently) broken maven-jarsigner-plugin. Using a deprecated API doesn’t particulary concern me in this instance, as its just signing artefacts.

Take a look at my profiles section, copy this into your pom.xml :

<profiles>
<profile><!-- release profile. uses keystore defined in keystore.* properties. signs and zipaligns the app to the target folder-->
            <id>release</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <defaultGoal>install</defaultGoal>
                <finalName>${project.artifactId}-${project.version}</finalName>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>2.2</version>
                        <executions>
                            <execution>
                                <id>signing</id>
                                <goals>
                                    <goal>sign</goal>
                                </goals>
                                <phase>package</phase>
                                <inherited>true</inherited>

                                <configuration>
                                    <keystore>
                                        my-release-key.keystore
                                    </keystore>
                                    <storepass>mypassword</storepass>
                                    <keypass>mypassword</keypass>
                                    <alias>mykeystore</alias>
                                    <verbose>true</verbose>
                                    <verify>true</verify>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>

                    <plugin>
                        <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                        <artifactId>maven-android-plugin</artifactId>
                        <inherited>true</inherited>
                        <configuration>
                            <sign>
                                <debug>false</debug>
                            </sign>
                        </configuration>
                    </plugin>

                    <plugin>
                        <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                        <artifactId>maven-android-plugin</artifactId>
                        <configuration>
                            <zipalign>
                                <verbose>true</verbose>
                                <skip>false</skip>
                                <!-- defaults to true -->
                                <inputApk>${project.build.directory}/${project.artifactId}-${project.version}.apk</inputApk>
                                <outputApk>${project.build.directory}/${project.artifactId}-${project.version}-RELEASE.apk
                                </outputApk>
                            </zipalign>

                        </configuration>
                        <executions>
                            <execution>
                                <id>zipalign</id>
                                <phase>install</phase>
                                <goals>
                                    <goal>zipalign</goal>
                                </goals>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
</profiles>

OK, so lets walk through what the above profile does. Firstly, the “id” of the profile is “release”, so when you want to apply this profile, you’d run “mvn install -Prelease”. The “activeByDefault” is set to false, which means you need to use the above arguement, if you flip that over, you won’t need the P flag.

The execution goal is to “sign”, which is the API on the plugin, documented here. We bind this execution on to the standard “package” goal. Then we provide the configuration elements which specify the details of the keystore.

In pure English, this binds the plugin phase onto the package goal of maven, so anytime we run using this profile it’ll execute the jar signing of our artefacts. The “verify” tag gives us extra piece of mind by verifying that the signing was successful afterwards.

I’ve also setup a zipalign profile that will take the APK, zipalign it, and rename it to “*-RELEASE.apk”, so I know that particular APK is the one which I’ll release to market.

So thats it, once more a success, and its just one small step on the ladder to android glory!

Phhew!! Done, finally I was able to shutdown the laptop and go to sleep at 3am….on a school night!!!

Good luck, feel free to comment!

Peace.

String concatenation operator

The string concatenation operator is a bit like a hedgehog, it looks cute and sweet, but try to grab hold of it quickly and you’ll soon know about it…

It’s actually quite simple, however there are some traps that are very easily overlooked (just got caught out with it on a mock test, so I’m here to rant).

The rule of thumb is, that if either one of the operands being “+” is a String, then concatenation will occur, but if they are both numbers, arithmetic addition will occur. Sounds simple right? What do you think the following equate to?

package operators;
public class MockTest
{
    public static void main(String[] args)
    {
        System.out.println(3 + 2);
        System.out.println(3 + "s");
        System.out.println("s" + 2);
        System.out.println("hello " + "world");
    }
}

Think you know it? Well its going to be : 5, 3s, s2. The first one is an arithmetic addition, since both sides of the operator are numeric. The second and third are String concatenation, because at least one of them is a String. The fourth one are both Strings, so concatenation once again.

those are the simple ones, however it can get a lot more tricky, have a look at these common ones that those exam creators try to catch you with!

package operators;

public class MockTest
{
    public static void main(String[] args)
    {
        // Inside brackets are evaluated first, so it'll be 7String
        System.out.println( (3 + 4) + "String");

        /* This is the little bugger that caught me, I vouched for 34String, but its actually 7String.
         Concatenation happens from left to right, one at a time, so it'll break it down to:
            3 + 4 then...
            <thing on left> + "String"

         Careful on these ones!
        */
        System.out.println(3 + 4 + "String");

    }
}


So remember, it’ll evaluate from left to right, one “+” operator at a time. Brackets are always evaluated first however.

Take my examples and have a play!

Happy coding (or raging at the screen if the mock tests catch you out…)

The instanceof Operator

The instanceof operator is a great way for checking if a reference variable is of a given type, in other words, does it pass the IS-A inheritance test. Ask yourself, is a Cat a Dog? A Dog a Cat? Or is a Cat an Animal and a Dog an Animal? In true Harry Hill style, there is only one way to decide….FIGHT!!!!

Have a look at my following example :

package operators;

public class InstanceOfOperatorDemo
{
    public static String myString = "James";

    public static void main(String[] args)
    {
        // myString variable is of type String, so returns true
        System.out.println("myString instanceof String : " + (myString instanceof String));
        // Even though myString is a String, a String is actually an Object (extends from Object), so the below is also true
        System.out.println("myString instanceof Object : " + (myString instanceof Object));

        B b = new B();
        // B is technically an instance of the implemented interface, so this should return true
        System.out.println("B instance of Foo : " + (b instanceof Foo));
        // This should return true also for the same reasons as above
        System.out.println("A new A() instance of Foo : " + (new A() instanceof Foo));
        // An A isn't an instance of a B, its the other way around; a B IS-A A, so returns false
        System.out.println("A new A() instance of B : " + (new A() instanceof B));

        // Any checks with null always return false, since null isn't an instance of anything
        System.out.println("null instanceof Object : " + (null instanceof Object));

        int[] myInts = new int[10];
        // Even though this array contains primitives, the array itself is still an Object at heart..
        System.out.println("myInts instanceof Object : " + (myInts instanceof Object));
    }
}

interface Foo {}
class A implements Foo {}
class B extends A {}

As we can see, a String IS-A Object, so that will pass the instanceof test. It is also important to note, that interfaces are also included in the instanceof check, so by checking if a class or a subclass is an instanceof an interface will return true.

Arrays, no matter what they hold, are always objects themselves, so they can be checked for instanceof too, of which they are Objects, as shown above.

It is important to note, that you can’t use instanceof across class hierarchies, this is something they’ll try to trick you out of in the exam, such as comparing a cat against a dog, you can compare up the hierarchy, but not across it, have a look at this example :

package operators;

public class InstanceOfOperatorCrossHierarchyDemo
{
    public static void main(String[] args)
    {
        // a Cat IS-A Dog, plain and simple
        System.out.println("Is cat an instanceof Animal? : " + (new Cat() instanceof Animal));

        // This will fail to compile, since we are not allowed to instanceof check across the
        // object hierarchy, a Cat is not an instance of Dog, so compiler fails
        System.out.println("Is cat an instanceof Dog? : " + (new Cat() instanceof Dog));
    }
}

class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}

That’s it! A nice and easy one, please leave me comments if you can suggest improvements!

Happy coding.