≡ Menu

Casting in Java

Today we have a quick Java tutorial about casting variables. This topic isn’t very interesting, but it’s definitely something that you should be familiar with if you want to be a programmer (in any language).

What is Casting in Java?

Well, all casting really means is taking an Object of one particular type and “turning it into” another Object type. This process is called casting a variable.

This topic is not specific to Java, as many other programming languages support casting of their variable types. But, as with other languages, in Java you cannot cast any variable to any random type.

What are the Rules behind Casting Variables?

It’s fairly simple, you remember our talk about how everything in Java is an Object, and any Object you create extends from Object? This was inheritance, and this is important to understand when dealing with casting.

If you are going to cast a variable, you’re most likely doing what’s known as a downcast. This means that you’re taking the Object and casting it into a more “specific” type of Object. Here’s an example:

Object aSentenceObject = "This is just a regular sentence";
String aSentenceString = (String)aSentenceObject;

You see what we’ve done here? Since the type Object is a very broad type for a variable, we are “downcasting” the variable to be a String type. Now, the question is, is this legal? Well, you can see that the value stored in the aSentenceObject is just a plain old String, so this cast is perfectly legal. Let’s look at the reverse scenario, an “upcast”:

String aSentenceString = "This is just another regular sentence";
Object aSentenceObject = (Object)aSentenceString;

Here we are taking a variable with a more specific type (String) and casting it to a variable type that’s more generic (Object). This is also legal, and really, it is always legal to upcast.

What are the benefits of casting variables?

There are times when you want to get more specific functionality out of a generic Object. For example, in my line of work, I deal with web applications, and I’m always dealing with something called a “model”. This “model” represents data that I want to display on a webpage, and the model is essentially a generic Map. The Map stores key/value pairs, where the key is a String and the value is usually just the generic Object type. So, an example of what would appear in this model would be:

“name” -> “Trevor Page”
“email” -> “tpage@ecosim.ca”
“birthday” -> “07-01-83”

Here’s what that Map would look like in code:

Map<String, Object> model = new HashMap<String, Object>();

This Map is a candidate for casting, and here’s how we would deal with the casting:

// get the individual date units (Year / Month / Day) from the model
// Note: we cast the value to a String and wrap it with additional brackets
// in order to get access to the built-in String methods (i.e. split())
String[] dateUnits = ((String)model.get("birthday")).split("-");
Integer year = Integer.valueOf(dateUnits[0]);
Integer month = Integer.valueOf(dateUnits[1])-1; // note that we subtract 1 here because Java wants a zero based index value for the month unit
Integer day = Integer.valueOf(dateUnits[2]);
String name = (String)model.get("name");
String email = (String)model.get("email");
Calendar cal = Calendar.getInstance();
cal.set(year, month, day);
Date birthday = cal.getTime();

You see how we did three separate casts there? Since all the objects stored in the map are of type Object, this means that they are very generic and could most likely be downcasted. Since we know that the “name” is a String, and the “email” is a String, and the “birthday” is a Date, we can do these three downcasts safely.

This would then give us more flexibility with those three variables, because now we have an actual birthday Date object, so we have access to methods like getTime() instead of just the default Object methods.

This is quite a valuable approach to storing Objects in a Map, because if we had created the Map with something more specific than Object as the value, then we would be constrained to only storing Objects of that specific type (and its sub-classes).

What are the downsides to Casting?

Well, there is a certain amount of risk that goes along with downcasting your variables. If you were to try to cast something like a Date object to an Integer object, then you’ll get a ClassCastException. This is what’s known as a run-time exception, as it’s really only detectable when your code is running. So, unless you’re doing something with error handling, then your program will likely exit or you’ll get an ugly error message on your webpage.

So just make sure that if you are doing any downcasting, that you’re well aware of the type of object you’ll be casting.

Want Free Access to my Best Java Courses?

Alright, so if you’re read this far down the article, then you’re clearly interested in learning how to code. You can currently get access to my 2 best courses on Java for free for 30 days (then it’s just $10/month afterwards, or $97/year).

When you sign up you’ll receive login information to start learning about Java. If you decide you don’t like the courses, you can cancel at any time. If you decide you love the courses then you don’t have to do anything and you can stay subscribed for as long as you like for just $10/month or $97/year.

It’s like Netflix for coders!

Go ahead an click the button below to get started!


To sum up, casting is a very useful mechanism that allows you to write more generic code that will allow you to handle many coding situations. But this mechanism can introduce some risk if you’re not careful with what you will be casting.

Also be sure to check out the below resources:

{ 15 comments… add one }

  • Matthew Clarke April 13, 2014, 12:27 pm

    Object aSentenceObject = “This is just a regular sentence”;
    String aSentenceString = (String)aSentanceObject;

    there’s a typo in aSentanceObject being casted to String

  • Svend May 21, 2014, 3:23 pm

    Thanks for the great tutorials, Trevor.

    There’s a typo:

    Map<String, Object> model = new HashMap<String, Object>();

    should be

    Map; model = new HashMap;();

  • Svend May 21, 2014, 3:26 pm

    Actually, I see that the HTML escape characters got removed and the offending characters got converted into the desired greater than / less than signs, so my correction doesn’t look right now.

    • Trevor Page May 22, 2014, 11:14 am

      Thanks for pointing that out, I’ve updated the post to reflect the proper syntax

  • Anon February 22, 2015, 4:47 am

    Well explained, thank you! 😉

  • Diana April 28, 2015, 5:20 pm

    And that’s how I just understand the cast 🙂
    PS. Is my first visit here. Good job with these tutorials 😉

  • Lucas June 27, 2015, 10:06 am

    Why it’s possible to assign String to Object? Is there hidden upcasting?
    Object aSentenceObject = “This is just a regular sentence”;
    Object aSentenceObject = (Object) “This is just a regular sentence”;

    It looks illogic.

    • Trevor Page June 29, 2015, 1:12 am

      Because everything in Java is an Object (except primitives)

  • shiv August 11, 2015, 7:37 am

    well done…very easy to understand.thanks

  • Mister Programmer March 10, 2016, 11:41 am

    Is this line really worked for you?
    Date birthday = (Date)model.get(“birthday”)
    It throws casting error for me…

    • Trevor Page March 11, 2016, 2:47 pm

      You’re absolutely right. When you put any String date value into the model for the key “birthday” it fails to cast properly. I’ll update the post with the correct code

  • Yimenu May 7, 2016, 12:54 am

    I am the first for this tutorial.it is greate idea that I wanted to support.but is it possible casting from super class to sub class?if it is possible how?

  • raed July 29, 2016, 6:37 pm

    really it a good job
    thanks alot
    I think that I really understand the casting

  • zoxy games May 19, 2017, 5:33 pm

    I blog quite often and I seriously appreciate your content.

    The article has really peaked my interest. I am going to bookmark
    your website and keep checking for new details about once per week.
    I subscribed to your RSS feed too.

Leave a Comment

Next post:

Previous post: