Converting and Casting Numeric Data with Automatic conversions - Java Language Basics

Java examples for Language Basics:Number Cast

Introduction

Here are the rules Java follows when doing this conversion:

If one of the values is a double, the other value is converted to a double.

If neither is a double but one is a float, the other is converted to a float.

If neither is a double nor a float but one is a long, the other is converted to a long.

If all else fails, both values are converted to int.

Demo Code

public class Main {
  public static void main(String[] args) {
    double d = 3.1314;
    int i = 5;//from  w  ww.ja v a2 s  . com

    System.out.println(d);
    System.out.println(i);

    
    d = i;

    System.out.println(d);
    System.out.println(i);
  }

}

Related Tutorials