Type Cast

Posted on 2003-03-27
Medium Priority
Last Modified: 2010-03-31
   Does anyone know where I can find a good tutorial on type casting objects?

Question by:LearningJava
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +3

Accepted Solution

m3th0dm4n earned 1000 total points
ID: 8222277
LVL 92

Expert Comment

ID: 8222308
What did you want to know?

Object a = new MyObject();
MyObject b = (MyObject) a;

You can only cast an object to a class that it is an instance of.

X casted = (X) original;

original must be an instance of a class X, an instance of a subclass of X, or an instance of a class that implements the interface X.
ie. (original instanceof X) must return true if original is not null.

Author Comment

ID: 8222349
Hi Object:
          I am studying for my java exam(university) and I was looking for a tutorial with exercises to test myself?

If you can think of a good question then please post it and I will give it a try.

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

LVL 92

Expert Comment

ID: 8222489
You could try www.brainbench.com for general Java tests.
LVL 30

Expert Comment

by:Mayank S
ID: 8223590
>> You can only cast an object to a class that it is an instance of.

Yeah! You cannot cast 'objects' to all objects!

<objects, just kidding, buddy!>

LVL 30

Expert Comment

by:Mayank S
ID: 8223605
GRIN :-)
LVL 35

Expert Comment

ID: 8223688
 Another web page about casting: http://www.geocities.com/SiliconValley/Pines/6133/javaguide/lj_5_5.html but you will not find loads of explicit information about casting. As already said just remember that you can only cast an object to its superclass (and up the hierarchy tree) or the interface it implements.

Expert Comment

ID: 8223739

Try logging onto Bruce Eckel's website (http://www.mindview.net/Books/DownloadSites) and downloading the latest version of his book Thinking In Java. That is an excellent source of information about Java and should help you get to grips with the concept of casting object from one type to another.

Good luck

PS You should be able to download a copy free of charge - it may not be the latest version but general OOP stuff such as casting does not change a great deal.
LVL 30

Expert Comment

by:Mayank S
ID: 8223796
If the two types are compatible, conversion can also be done automatically. Some are actually done automatically, whereas some require an explicit cast. e.g., it is always possible to assign an 'int' value to a 'long'. However, not all types are compatible, e.g., there is no defined conversion defined from 'double' to 'byte'. Fortunately, it is still possible to obtain a conversion, using a cast.

When one type of data is assigned to another, an automatic type converion occurs if the following 2 conditions are satisfied:

1. The 2 types are compatible
2. The destination type has larger storage than the source type

In this case, the implicit type conversion which takes place is also called as 'widening'. e.g., a 'long' is always large enough to hold an 'int', an 'int' ia always large enough to hold a 'byte', etc. However, the numeric types are not compatible with 'char' and 'boolean' (which are themselves not compatible). Also, within the numeric types, 'int' and 'float' are not compatible with each other for automatic widening.

There might be some situations when you need to assign, say, the value of an 'int' to a 'byte'. In such cases, the conversion will not be automatic and a type-cast will be required. Such a cast is also called as 'narrowing', because you are assigning a value after explicitly narrowing it so that it can fit. The general form for this is:

(target_type) value


int a = 5 ;
long l ;
byte b ;
b = a ; // invalid
b = (byte) a ; // valid
l = a ; // valid

Now, when a floating-point value is cast in this way to an integer-type, as:

int intVal = (int) floatVal ;

Then a 'truncation' is also said to take place as integers don't have a fractional-part, and so, the fractional-part is removed.

While dealing with expressions, there are some 'promotions' which occur in the types. e.g., 'byte' and 'short' are always converted to 'int's in arithmetic expressions.

byte a = 40 ;
byte b = 50 ;
byte c = 100 ;
int d = a * b / c ;

The expression a * b exceeds the range of a 'byte', but thankfully, Java converts 'byte' to an 'int' during evaluation of arithmetic expressions, and so, the computation is performed and the value can be assigned to an 'int'. But, for the same reason, the following will not run:

byte a = 50 ;
byte b = a * 2 ; // invalid

Though a * 2 = 100, which fits in the range for a 'byte', remember that a 'byte' will be converted to an 'int' implicitly while expression-evaluation, so the RHS of the above equation is an 'int' type, and we know tht for automatic conversion, the LHS must have more storage than the RHS, which will not be the case here. So, you can narrow it by casting as:

byte a = 50 ;
byte b = (byte) ( a * 2 ) ; // valid

There are also some other type-promotion rules as:

1. All 'byte' and 'short' variables are converted to 'int's (as already discussed)
2. If one operand is 'long' (and others of smaller storage as 'int'), then all variables are converted to 'long'
3. Sameway, if one operand is 'float' and others are smaller, then all are converted to 'float's and if one operand is 'double', then all are converted to 'double's.

Hope that helps!


Author Comment

ID: 8225801
Thank-you, everyone for the expert help.

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month13 days, 21 hours left to enroll

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question