Wednesday, December 5, 2018
Home > java > Java typecasting

Java Typecasting

Typecasting is the phenomenon of assigning the value of one variable to another. As the Java type system is of two types: primitives and references. So, the java typecasting is the process in which we can convert one primitive type to another primitive data type or one reference object to another object. Both of these conversions may look alike but they are different in many ways.

Primitive Typecasting in Java

Primitive type casting in Java includes the conversion of primitive data types available in java. Different primitive data types in Java are:

  •      byte – A byte is of 8 bits and signed.
  •      short – Short values are 16 bits and signed.
  •      char – A character is also 16 bits but it is unsigned.
  •      int – An integer is of 32 bits and signed.
  •      long – Long value is 64 bits and signed.
  •      float – Floating point values are 32 bits and signed.
  •      double – Double values are 64 bits and signed.
  •      boolean – A Boolean is not a numeric and can only have two values either true or false.

Primitive conversion is of two types:

  1.      Widening
  2.      Narrowing

Widening

Sometimes we may refer to widening as implicit type conversion or automatic type conversion. This type of type conversion happens when the two data types are compatible or we are converting the value of a smaller data type to a larger data type. As the numeric data types are compatible in java so we can convert or type cast them.  In implicit type casting we don’t have to worry about losing the data.  As we are going from lower to a higher data type.

java typecasting implicit

E.g.

package example;
public class TypeCasting {
     public static void main(String[] args) {
     byte b = 32;
     
     //widening from lower data type (byte) to higher data type (short)
     short s = b;

     // conversion from short to integer
     int i = s;

     // conversion from integer to long
     long l = i;

     // long to float
     float f = l;

     // float to double
     double d = f;

     System.out.println("Byte Value is :" + b);
     System.out.println("Short Value is :" + b);
     System.out.println("Integer value is :" + i);
     System.out.println("Long value is :" + l);
     System.out.println("Floating point value is :" + f);
     System.out.println("Double value is :" + d);
     }
}

Output:

implicit typecasting in java

Narrowing 

Narrowing or explicit type casting is the one in which we convert the value from a larger data type to a smaller data type.  In this type of conversion, we may lose some part of the data as well. So it is really necessary to have a look at it while converting a larger data type to a smaller data type. This type of conversion is useful when the two types are not compatible and we explicitly set the data type.

java typecasting explicit

package example;
public class TypeCasting {
     public static void main(String[] args) {
     double d = 32.4;

     //narrowing from double to float
     float f = (float) d;

     // float to long
     long l = (long) f;

     // long to int
     int i = (int) l;

     //int to short
     short s = (short) i;

     //short to byte
     byte b = (byte) s;

     System.out.println("Double value is :" + d);
     System.out.println("Floating point value is :" + f);
     System.out.println("Long value is :" + l);
     System.out.println("Integer value is :" + i);
     System.out.println("Short Value is :" + b);
     System.out.println("Byte Value is :" + b);
     }
}

Output:

explicit typecasting in java

Here in the above example, we can see that we have lost the part after the point in 32.4 as we convert from float point to long.

When we are using these data type in an expression java automatically promotes the lower data types to the higher most data type if we are storing the output to a larger data type.

E.g.  If we have long int and float type values in an expression, then the java compiler will automatically typecast the int and long value to floating point value. The result will be stored in the highest data type.

package example;
public class TypeCasting {
     public static void main(String[] args) {
     byte b = 10;
     char c = 'x';
     short s = 4096;
     int i = 50;
     float f = 3.11f;
     double d = .4242;

     // The Expression using primitive data types
     double result = (s / d) + (f + b) - (i / c);

     // Result after all types are converted to double
     System.out.println("Result is stored in double data type");
     System.out.println("Result = " + result);
     }
}

Output:

implicit java typecasting in expression

 

But if we are using different data types in our expression and we try to save the result of the expression to a smaller data type used in the expression. The java compiler will generate the compile-time error so we must explicitly convert the result to the smaller data type.

E.g.

package example;
public class TypeCasting {
     public static void main(String[] args) {
     byte b = 10;
     char c = 'x';
     short s = 4096;
     int i = 50;
     float f = 3.11f;
     double d = .4242;

     // This will generate the compile time error.
     //byte result = (s / d) + (f + b) - (i / c);

     //expicitly converting the result to byte
byte result = (byte) ((s / d) + (f + b) - (i / c));

     // Result after all types are converted to double
     System.out.println("Result is stored in byte data type");
     System.out.println("Result = " + result);
     }
}

 

Output

explicit typecasting in java expression

Reference Typecasting in java

The second type of java typecasting is the reference type casting or object typecasting.  Reference variables (objects) are different from the primitive data types as they contain the value but objects only contain the reference to an object. Just like primitive type conversion we also have two types of reference type casting. Upcasting and downcasting.  One narrows the number of functions and properties while the other extends them.

Upcasting

When we convert an object of a subclass to an object of the superclass, this is upcasting.  Typically, the Java compiler automatically performs the upcasting for us. We can say that upcasting the references has a very close relation to inheritance in java.

E.g.

package example;
public class Person {
     private String name;
     private int age;

     public String getName() {
          return name;
     }
     public void setName(String name) {
          this.name = name;
     }
     public int getAge() {
          return age;
     }
     public void setAge(int age) {
          this.age = age;
     }
     public void eat(){
          System.out.println("Person Eats");
     }
     public void sleep(){
          System.out.println("Person Sleep");
     }
}

Here is another class teacher that extends the class person.

package example;
public class Teacher extends Person{
     private String designation;
     public String getDesignation() {
          return designation;
     }
     public void setDesignation(String designation) {
          this.designation = designation;
     }
     public void teaches(){
          System.out.println("Teacher teaches");
     }
}

Class to use the above classes is:

package example;
public class ObjectTypeCasting {
     public static void main(String[] args) {
     Teacher t = new Teacher();

     // implicit type casting
     Person p = t;

     //We are just setting these values to show that what we can access 
       in person class we can do this. */
     t.setName("Jan Doe");
     t.setAge(32);
     t.setDesignation("Professor");

     /*
     * We are not allowed to set the designation of teacher
     * using person class object.
     */

     // we can only set these two
     p.setAge(10);
     p.setName("jhon");

     /*
     * similarly we are not allowed to access the functions
     * of the teacher class with person object.
     */

     p.sleep();
     p.eat();

     //to access teacher class function we use teacher class object.
     t.teaches();
     }
}

 

Output:

reference typecasting in java

Upcasting can also be achieved by using polymorphism and function overriding.

Downcasting

Downcasting is the conversion of a superclass object to a subclass object. We explicitly do the downcasting of the objects. As in the above example what if we want to call the functions of the teacher class with the person class object. Or we want to access the data members of the teacher class with person class object. To do so, we need to downcast the person class object to teacher class object explicitly.

E.g.

package example;
public class Person {
     private String name;
     private int age;

     public String getName() {
          return name;
     }
     public void setName(String name) {
          this.name = name;
     }
     public int getAge() {
          return age;
     }
     public void setAge(int age) {
          this.age = age;
     }
     public void eat(){
          System.out.println("Person Eats");
     }
     public void sleep(){
          System.out.println("Person Sleep");
     }
}

Here is another class teacher that extends the class person.

package example;
public class Teacher extends Person{
     private String designation;
     public String getDesignation() {
          return designation;
     }
     public void setDesignation(String designation) {
          this.designation = designation;
     }
     public void teaches(){
          System.out.println("Teacher teaches");
     }
}

 

The class that uses these two above classes will be like this:

package example;
public class DownCasting {
     public static void main(String[] args) {
     // creating new person object
Person p =      new Teacher();

     // We can do this by explicitly downcasting the person object
     ((Teacher) p).setName("Jan Doe");
     ((Teacher) p).setAge(32);
     ((Teacher) p).setDesignation("Professor");

     /* to access teacher class function we explicitly downcast 
      person class object. */
     ((Teacher) p).teaches();
     }
}

Output

object downcasting in java

Downcasting can lead us to ClassCastException which will occur at the runtime of the program. So we can avoid this by using the instanceof operator.

Another way to do java typecasting is by using the cast() method of the class.

One thought on “Java typecasting

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.