Take the 2-minute tour ×

For example I have an Object "pretending" to be String:

Object o = new String("dsadsa");

if I want to use the String functions of that object, first I have to convert it to a string like this:


Which becomes really annoying and unreadable when there are so many brackets! Especially when that has to go in an IF statement or in a function!

if (((String)o).equals("dsadsa")) {}

What is the best way to avoid this kind of situation?

share|improve this question
Why do you have an Object if you know its a String? BTW You don't need to use new String(String) here or just about anywhere else. –  Peter Lawrey Aug 22 '12 at 15:33
Yea I know that, new String() was just an example to really show that that object is a string, and also, I would gladly avoid this but when I'm using a Vector for example, and I want to store the string, they are all object so I have no choice. :/ –  SmRndGuy Aug 22 '12 at 15:39
If you are using a Vector to store the string you don't need a cast. A String is an Object, so it will work. But if you are using a Vector, unless you are using j2me or java 1.4, you can use Vector<String>, or even ArrayList<String> will (probably) serve you better –  Pablo Grisafi Aug 22 '12 at 15:41
You should try Lisp. –  GriffeyDog Aug 22 '12 at 20:32
There is no "Object pretending to be String", there is only a String assigned to a variable of type Object. –  herman Aug 22 '12 at 23:14
show 1 more comment

10 Answers

up vote 8 down vote accepted

Cast the object in one line.

Use the casted object in another line.

share|improve this answer
add comment

A solution is to ensure your object is of a precise class before, for example in the prototype of your method.

This is the best practice as it also helps avoiding runtime errors.

That's increasingly easier with parameterized classes (generics).

Said otherwise : if you have a lot of casts in your code, there is probably a design problem. But we'd need more code to suggest a solution.

share|improve this answer
add comment

In practice the correct use of generics gets rid of most casts you used to see in code.

But if for some reason you can't do it (older Java version, legacy libraries), create a local variable where you do the cast at the earliest opportunity.

A special case is when you cast an object from an interface type to its implementation. That's almost always wrong and means that the interface is badly designed.

share|improve this answer
Seems like generics are much more important than I previously thought. Too bad I'm unable to use it because I'm actually programming in JavaME which doesn't support generics. x_x I believe I should use the second option then. –  SmRndGuy Aug 22 '12 at 15:48
I was assuming you were really after getting rid of the brackets. If you want to get rid of the casts altogether, generics are exactly what you're after (if they're available to you). –  Hbcdev Aug 22 '12 at 16:15
add comment

The standard practice is to always capture your object into a variable of the narrower type, in your case a String str variable, and use that afterwards.

Note that in your third example you don't need to downcast: o.equals(o2) also works.

If you decide to study Java Generics, you may be soon disappointed: often they just shift the verbosity from downcasts to type declaration. Many code snippets are as long, and some even longer, when rewritten into Generics.

share|improve this answer
+1 for spotting that casting isn't even required in the example. I would argue though that while generics are indeed verbose, they're a lot easier to read and interpret. –  biziclop Aug 22 '12 at 15:35
@biziclop It varies with the use case---collection types are a win, especially in combination with the enhanced for. Callbacks used as lambda functions on the other hand, are quite a fail, due to the weak type inference. –  Marko Topolnik Aug 22 '12 at 15:39
at least in java 7, it's not quote as verbose: List<String> list = new ArrayList<String>() becomes List<String> list = new ArrayList<>(); –  Matt Aug 22 '12 at 16:32
@Matt true, that helps, but only when type inference actually works. I have banged my head on many, many examples where it fails. –  Marko Topolnik Aug 22 '12 at 16:39
@MarkoTopolnik : I routinely bang my head against the wall when dealing with generics in general. I understand they wanted backward compatibility, but it's caused so many darned headaches, it wasn't worth it. –  Matt Aug 22 '12 at 17:03
add comment

I'm assuming you meant to say your String is pretending to be an Object.

Your handle is of type Object, which it needn't be.

  1. If you are using an Object type, because that's the parameter your method gets, consider changing the parameter type to String, if you are actually expecting a String.
  2. If this comes from a Collection, consider changing the Collection to use Generics so that you can defined the collection to be of type String.
  3. If for someone reason you can't change the type of the object coming in, verify that it is, in fact, a String, and cast it once to another variable of String type.

This is what the code would look like, for the third option.

String s;
if (o instanceof String) {
    s = (String) o;
} else {
    s = null;
    throw new IllegalArgumentException();
    // Or take some corrective action.
share|improve this answer
add comment

you can do some dangerous things taking advantage of generics like

public static <T> T cast(Object o){
    return (T) o;

This allows you do do things like

Object o="";
String s = cast(o);

It is really hacky but you could do something like

public static String s(Object o){
    return (String) o;

and then

    Object o = "";
share|improve this answer
add comment

I don't recommend it, but you could do this:

share|improve this answer
add comment

I don't think so. You have to cast explicitly for superclass to subclass.

String str;

if(o instanceOf String){
   str =(String)o;
share|improve this answer
The trouble with this solution, apart from it being even harder to read is that if o isn't a String, you get an NPE instead of a ClassCastException, which is very confusing for a code maintainer. –  biziclop Aug 22 '12 at 15:33
If you are going to test o instanceof String (note: small 'o' in instanceof), there is no point in separately testing o!=null right before. null instanceof Whatever will be false as intended. (Apart from that, I am not quite sure what you are actually addressing here.) –  arne.b Aug 22 '12 at 18:53
@arne.b - thanks for correcting –  Subhrajyoti Majumder Aug 22 '12 at 19:03
add comment

It seems you don't want compile-time type checking. Then just use a scripting language e.g. Groovy which also runs on the JVM but does not require static typing.

share|improve this answer
add comment

"dsadsa".equals(someString) is how it's done - effective removes any chances for NPE and ensures no virtual call even if someString is actually declared as object.

Also you do not need cast to call equals().

Aside that you can use generics but they have overly verbose syntax, esp when it comes to stuff like <T extends Foo &Bar> T selectFooBared(List<java.lang.ref.Reference<T>> list, Comparator<? super T> c);

share|improve this answer
add comment

Your Answer


