Java type conversion and casting Question 1

Question

What is the output of the following code?

public class Main {
  public static void main(String[] args) {
    System.out.println((int)1.7); 

    System.out.println((double)1 / 2); 

    System.out.println(1 / 2); //from   w w w .  ja  v  a  2  s.c  o  m

  }
}


1
0.5
0

Note

To cast a type, specify the target type in parentheses.

For example, the following statement

System.out.println((int)1.7); 

displays 1. When a double value is cast into an int value, the fractional part is truncated.

The following statement

System.out.println((double)1 / 2); 

displays 0.5, because 1 is cast to 1.0 first, then 1.0 is divided by 2. However, the statement

System.out.println(1 / 2); 

displays 0, because 1 and 2 are both integers and the resulting value should also be an integer.




PreviousNext

Related