Chaitanya Babar
Chaitanya Babar

Reputation: 289

How Type Casting Works in java?

  1. Why values of c are 2.0 and 2.5 although they have same data type
  2. How is conversion taking place in a/b

    public static void main(String[] args) 
            {
                int a = 5,b=2;
                float c;
                c=a/b;
                System.out.println(c);
                c=(float)a/b;
                System.out.println(c);
            }
    

Upvotes: 1

Views: 917

Answers (3)

Larois
Larois

Reputation: 1

The first division is int / int --> int result. the second is Float / int, --> Float results.

Upvotes: 0

Robin Krahl
Robin Krahl

Reputation: 5308

In the first statement, a/b is calculated. As both variables are integers, the result is an integer too: 2. In your second statement, a is first converted to a float and then divided by b. As one of the values is a float, the result is a float too: 2.5.

Upvotes: 0

rgettman
rgettman

Reputation: 178253

The answer lies in understanding that despite declaring c as float, integer division still takes place with a/b. Integer division in Java truncates any fractional part (so it can remain an int). Only then is it implicitly converted to a float upon assignment to c, and 2.0 is printed.

The cast to a float in (float)a/b changes a to 5.0f and forces floating point division before the result is assigned to c, so the correct result 2.5 is printed.

Upvotes: 3

Related Questions