AP Computer Science A : Object-Oriented Development

Study concepts, example questions & explanations for AP Computer Science A

varsity tutors app store varsity tutors android store

Example Questions

Example Question #222 : Computer Science

JAVA EXPLICIT TYPE CASTING

Consider the following JAVA code:

 

public static void main(String[] args)

{

     double number1 = 99.05;

     int number2 = (int) number1;

     System.out.println("number1 = " + number1);

     System.out.println("number2 = " + number2);

}

What would be the console output?

Possible Answers:

number1 = 99.05

number2 = 99.05

number1 = 99.05

number2 = 99.00

number1 = 99

number2 = 99

number1 = 99.05

number2 = 99

Correct answer:

number1 = 99.05

number2 = 99

Explanation:

Type casting deals with assigning the value of a variable to another variable that is of a different type. In this case we have two variables one that is a double, and another that is an integer. number1 is a double that has a value of 99.05. However, when number2 is assigned the value of number1, there is some explicit type casting going on. When an integer is assigned the value of a double, it drops off the decimal places. This means that number2 has a value of 99.

Learning Tools by Varsity Tutors