Casting Variables in Java

Casting variables in Java

Casting in Java isn't magic, it's you telling the compiler that an Object of type A is actually of more specific type B, and thus gaining access to all the methods on B that you wouldn't have had otherwise. You're not performing any kind of magic or conversion when performing casting, you're essentially telling the compiler "trust me, I know what I'm doing and I can guarantee you that this Object at this line is actually an <Insert cast type here>." For example:

Object o = "str";
String str = (String)o;

The above is fine, not magic and all well. The object being stored in o is actually a string, and therefore we can cast to a string without any problems.

There's two ways this could go wrong. Firstly, if you're casting between two types in completely different inheritance hierarchies then the compiler will know you're being silly and stop you:

String o = "str";
Integer str = (Integer)o; //Compilation fails here

Secondly, if they're in the same hierarchy but still an invalid cast then a ClassCastException will be thrown at runtime:

Number o = new Integer(5);
Double n = (Double)o; //ClassCastException thrown here

This essentially means that you've violated the compiler's trust. You've told it you can guarantee the object is of a particular type, and it's not.

Why do you need casting? Well, to start with you only need it when going from a more general type to a more specific type. For instance, Integer inherits from Number, so if you want to store an Integer as a Number then that's ok (since all Integers are Numbers.) However, if you want to go the other way round you need a cast - not all Numbers are Integers (as well as Integer we have Double, Float, Byte, Long, etc.) And even if there's just one subclass in your project or the JDK, someone could easily create another and distribute that, so you've no guarantee even if you think it's a single, obvious choice!

Regarding use for casting, you still see the need for it in some libraries. Pre Java-5 it was used heavily in collections and various other classes, since all collections worked on adding objects and then casting the result that you got back out the collection. However, with the advent of generics much of the use for casting has gone away - it has been replaced by generics which provide a much safer alternative, without the potential for ClassCastExceptions (in fact if you use generics cleanly and it compiles with no warnings, you have a guarantee that you'll never get a ClassCastException.)

Is there a way that I can cast the variables in my Java program so that I get a double output?

Well the average variable must be double
and you cast the division result to fit in the average variable

    double average;
// 4. Write a formula to calculate the sum of the 3 grades (add them up).
sum = grade1 + grade2 + grade3;
// 5. Write a formula to calculate the average of the 3 grades from the sum using division and type casting.
average = (double) sum / 3;
System.out.println(average);

Casting during assignment in Java

Casting during assignment is not redundant when you know something the compiler doesn't.

When you assign Student object to Person variable, there is no need to cast because the compiler knows Student inherits from Person. But if you assign Person object to Student variable, the compiler doesn't know if the Person object is also Student object.

In that case you'd have to use cast during assignment to tell the compiler you know this specific Person object is also Student. You would usually verify this first with instanceof.

if (P instanceof Student) {
Student S2 = (Student) P; // here the casting during assignment is required
S2.getGpa();
}

What is point of type casting?

char is an integral type in Java, and when you perform arithmetic the result is an int (JLS-4.2.2. Integer Operations says, in part, the numerical operators, which result in a value of type int or long and adds that does include the additive operators + and -).

char c = 'A';
System.out.printf("'%c' = %d%n", c, (int) c);
int d = (c - 'A' + 'a'); // c - 65 + 97
System.out.printf("'%c' = %d%n", (char) d, d);

And I get

'A' = 65
'a' = 97

Multiple typecasting in a single line in Java program

It's basically just a chain of casts and unary + and -.

float i = (char) +(int) -(long) (byte) 100;

It's equivalent to

byte tmp1 = (byte) 100;
long tmp2 = (long) tmp1;
long tmp3 = -tmp2;
int tmp4 = (int) tmp3;
int tmp5 = +tmp4;
char tmp6 = tmp5;
float i = tmp6;

The final assignment is from char to float, which is a widening primitive conversion. See JLS Chapter 5: Conversions and Promotions

19 specific conversions on primitive types are called the widening primitive conversions:

  • byte to short, int, long, float, or double
  • short to int, long, float, or double
  • char to int, long, float, or double
  • int to long, float, or double
  • long to float or double
  • float to double

Typecasting in Java with respect to if statement

The line currObj = (aSubType) currObj doesn't really have any net effect. In order to call someMethodofaSubtype(), the compiler wants to know that the object really is of type aSubType. The cast doesn't really change the underlying object. Casting and then storing the result of the cast as a new variable of type aSubType would do the trick. You probably want something like:

aSubType subCurrObj = (aSubType) currObj;
subCurrObj.someMethodofaSubtype();

Why can't i cast (byte) Data Type into (short) Data Type in Java

When we add two byte type variables or byte type variable with int type variable the result is automatically cast (implicit casting) to int. So the compiler will give error if we want to assign the result of addition to a short type variable.

While you can assign it to short type variable by explicit casting.

public static void main(String[] args) throws MyException {
byte number = 2;
//Explicit casting
short updateNumber = (short) (number + 2);

System.out.println(updateNumber); // output : Error
}

As the result of the addition can overflow because here number variable value can be changed at runtime. So if you declare number as final and addition of the numbers fits in range of byte then you won't need to do explicit casting because compiler would be knowing in advance weather the result of addition can be hold by byte or not.

public static void main(String[] args) throws MyException {
final byte number = 2;
//Explicit casting not needed as number is final
short updateNumber = number + 2;

System.out.println(updateNumber); // output : Error
}


Related Topics



Leave a reply



Submit