Next page | Contents page |

The instanceof operator

	boolean b = c instanceof d;
	// c is an object, d is a class or interface type

Often used for checking whether safe to cast, to avoid a ClassCastException when running:

	Object [] mixture = new Object [] { "abc", new X (),
						new Integer (10), ... };

	for (int i = 0; i < mixture.length; i++)
	{
		if (mixture [i] instanceof String) // OK to cast
		{
			System.out.println ((String) mixture [i]);
		} 
	}

(Remember that keywords are always all lower case, even though this one is made from 2 words.)

Next page | Contents page |