Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Java Data Type Conversion

In this article we will understand how the data type conversion takes place in Java and what all types of conversions are there in Java.

Introduction to Data Type

Changing a value from one data type to another type is known as data type conversion. Data type conversions are either widening or narrowing, it depends on the data capacities of the data types involved. There are different ways of, implicitly or explicitly, changing an entity of one data type into another data type.

An important consideration with a type conversion is whether the result of the conversion is within the range of the destination data type.

Widening Conversion

If a value of narrower (lower size) data type converted to a value of a broader (higher size) data type without loss of information, is called Widening conversion. This is done implicitly by the JVM and also known as implicit casting. For example an integer data type is directly converted to a double.

int a = 100; 
double b = a;
System.out.println(b);

In above example integer (4 Byte) converted into double (8 Byte)

Widening conversion is allowed in the following cases:

  • byte can be converted to short, int, long, float, or double
  • Short can be converted toint, long, float, or double
  • char can be converted toint, long, float, or double
  • intcan be converted to long, float, or double
  • long can be converted to float or double
  • float can be converted to double

Narrowing Conversion

If a value of broader (higher size) data type converted to a value of a narrower (lower size) data type which can result in loss of information, is called Narrowing conversion. This is not done implicitly by the JVM and requires explicit casting. For example double data type explicitly converted into integer

double a = 100.7;
int b = (int) a; 
System.out.println(b);

In above example the double 'a' is explicitly converted to int 'b'.

Narrowing conversion is allowed in these cases:

  • short can be converted to byte or char
  • char can be converted to byte or short
  • intcan be converted to byte, short, or char
  • long can be converted to byte, short, or char
  • float can be converted to byte, short, char, int, or long
  • double can be converted to byte, short, char, int, long, or float

Narrowing conversion should follow the following thumb rule

  • The narrowing conversion must be explicit.
  • The target type need to be specified in parentheses.

Listing 1: Representing the narrowing conversion

public class MainClass {

  public static void main(String[] args) {
    long a = 10;
    int b = (int) a; // narrowing conversion

    System.out.println(a);
    System.out.println(b);
  }

}

As, in narrowing conversion it may occur information loss, if the converted value is larger than the capacity of the target type. The following example illustrates this.

Listing 2: Representing the narrowing conversion

public class MainClass {

  public static void main(String[] args) {
    long a = 12345678965;
    int b = (int) a;
    System.out.println(b);
  }

}

Automatic conversion

Automatic type conversion is similar to widening conversion, it occurs implicitly between the compatible types.

An automatic type conversion will occur if the following two conditions are met:

  • The two types are compatible.
  • The destination type is larger than the source type.

Type Compatibility

Two Types are compatible if values of one type can appear wherever values of the other type are expected, and vice versa.

Java is a strongly typed language and from there comes it’s safety and robustness.

Every variable has a type which is strictly defined.

All assignments ,whether explicit or via parameter passing in method calls ,are checked for type compatibility and any mismatches result in errors .

Casting of Incompatible Types

To perform a conversion between two incompatible types, we must use a cast. A cast is simply an explicit type conversion. It has following general form: (target-type) value

Here, target-type specifies the desired type to convert the specified value to. For example, the following fragment casts an int to a byte. If the integer’s value is larger

int  a = 257;
int b = (int) a; 

Listing 3: Representing the casting of incompatible types

public class MainClass {
  public static void main(String args[]) {
    byte b;
    int i = 399;
    double d = 424.142;
   
    System.out.println("\nConversion of int to byte.");
    b = (byte) i;
    System.out.println("i and b " + i + " " + b);
   
    System.out.println("\nConversion of double to int.");
    i = (int) d;
    System.out.println("d and i " + d + " " + i);
   
    System.out.println("\nConversion of double to byte.");
    b = (byte) d;
    System.out.println("d and b " + d + " " + b);
  }
}

Some Common misunderstandings

Implicit and explicit typecasting of primitive types is frequently misunderstood. Below is a small test program, overloaded with multiple constructors to show when and how type conversion promotion is done with implicit casting.

In this example, since the third value is an integer, but there is no constructor that takes an integer, its value and the float value automatically convert to double. (Case 5: double, double, double)

Listing 4: Representing the implicit casting

public class typetest {  

typetest(double a, double b, short c){  
System.out.println("1 (dbldbl short)");
  } 

typetest(float a, byte b, long c) { 
System.out.println("2 (float byte long)"); 
  }

typetest(long a, long b, long c) { 
System.out.println("3 (long long long)"); 
  }

typetest(float a, long b, short c) { 
System.out.println("4 (float long short)"); 
  } 

typetest(double a, double b, double c) { 
System.out.println("5 (dbldbldbl)"); 
  } 

public static void main(String[] args) { 
typetest t = new typetest();
t.typetest(3.4, 3L, 3); 
    } 
}

Some other examples

Listing 5: Representing the use of intValue() function to fetch the integer value from a string

public class Main {
  public static void main(String[] argv) {

    String strValue = "5";

    try {
      int iValue = new Integer(strValue).intValue();
    } catch (NumberFormatException ex) {
      ex.printStackTrace();
    }
  }
}

Listing 6: Representing the use of toString method of Integer class to convert Integer into String

public class Main {

  public static void main(String[] args) {
    Integer intObj = new Integer(10);
    
    String str = intObj.toString();
    System.out.println("Integer converted to String as " + str);
  }
}

Listing 7:Representing the use of exception handling during conversion

public class Main {
  public void convertStringToInt() throws NumberFormatException {

    String s = "123";
    int number = Integer.parseInt(s);

  }
}

Listing 8: Representing the automatic Type Promotion in Expressions

public class MainClass {
  public static void main(String args[]) {
    byte b = 42;
    char c = 'a';
    short s = 1024;
    int i = 50000;
    float f = 5.67f;
    double d = .1234;
    double result = (f * b) + (i / c) - (d * s);
    System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
    System.out.println("result = " + result);
  }
}

Listing 9: Representing the conversion of byte array to Integer and Long

public class Utils {

  public static void putInt(int value, byte[] array, int offset) {
    array[offset]   = (byte)(0xff & (value >> 24));
    array[offset+1] = (byte)(0xff & (value >> 16));
    array[offset+2] = (byte)(0xff & (value >> 8));
    array[offset+3] = (byte)(0xff & value);
  }

  public static int getInt(byte[] array, int offset) {
    return
      ((array[offset]   & 0xff) << 24) |
      ((array[offset+1] & 0xff) << 16) |
      ((array[offset+2] & 0xff) << 8) |
       (array[offset+3] & 0xff);
  }

  public static void putLong(long value, byte[] array, int offset) {
    array[offset]   = (byte)(0xff & (value >> 56));
    array[offset+1] = (byte)(0xff & (value >> 48));
    array[offset+2] = (byte)(0xff & (value >> 40));
    array[offset+3] = (byte)(0xff & (value >> 32));
    array[offset+4] = (byte)(0xff & (value >> 24));
    array[offset+5] = (byte)(0xff & (value >> 16));
    array[offset+6] = (byte)(0xff & (value >> 8));
    array[offset+7] = (byte)(0xff & value);
  }

  public static long getLong(byte[] array, int offset) {
    return
      ((long)(array[offset]   & 0xff) << 56) |
      ((long)(array[offset+1] & 0xff) << 48) |
      ((long)(array[offset+2] & 0xff) << 40) |
      ((long)(array[offset+3] & 0xff) << 32) |
      ((long)(array[offset+4] & 0xff) << 24) |
      ((long)(array[offset+5] & 0xff) << 16) |
      ((long)(array[offset+6] & 0xff) << 8) |
      ((long)(array[offset+7] & 0xff));
  }
}	

Listing 10: Representing some primitive conversions

public final class PrimitiveUtils {

    
    public static Class getClass(String value) {
        Class clz = null;        
        if ("int".equals(value)) {
            clz = int.class;
        }
        if ("byte".equals(value)) {
            clz = byte.class;
        }
        if ("short".equals(value)) {
            clz = short.class;
        }
        if ("long".equals(value)) {
            clz = long.class;
        }
        if ("float".equals(value)) {
            clz = float.class;
        }
        if ("double".equals(value)) {
            clz = double.class;
        }
        if ("boolean".equals(value)) {
            clz = boolean.class;
        }
        if ("char".equals(value)) {
            clz = char.class;
        }
        return clz;
    }

    public static Object read(String value, Class type) {
        Object ret = value;
        if (Integer.TYPE.equals(type)) {
            ret = Integer.valueOf(value);
        }
        if (Byte.TYPE.equals(type)) {
            ret = Byte.valueOf(value);
        }
        if (Short.TYPE.equals(type)) {
            ret = Short.valueOf(value);
        }
        if (Long.TYPE.equals(type)) {
            ret = Long.valueOf(value);
        }
        if (Float.TYPE.equals(type)) {
            ret = Float.valueOf(value);
        }
        if (Double.TYPE.equals(type)) {
            ret = Double.valueOf(value);
        }
        if (Boolean.TYPE.equals(type)) {
            ret = Boolean.valueOf(value);
        }
        if (Character.TYPE.equals(type)) {
            ret = value.charAt(0);
        }
        // TODO others.
        return ret;
    }
}

Conclusion

In this article we learnt how to work with data type conversion in java development, if you have any question, please let me know in the comments below.

Hope you liked the article, see you next time.



Have total 6+ years of experience in developing enterprise applications using DOT.NET 3.5 and 4.0(C#, VB.NET, ADO.NET, ASP.NET),java, JQuery, JSON, LINQ,WCF, MVC3, MVC4, Silverlight, SQL Server, mobile applications and Oracle etc ...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login